Programs & Examples On #Dcom

Distributed COM (DCOM) is a protocol that enables software components to communicate with one another over a network.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I have same problem after upgrading to Gradle Wrapper 5.1.rec3. I am back to Gradle 4.6

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

As Mentioned in above repilies:

Starting with MySQL 8.0.4, the MySQL team changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.

So there are three ways to resolve this issue:

 1. drop USER 'user_name'@'localhost';
    flush privileges;
    CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'user_name';
    GRANT ALL PRIVILEGES ON * . * TO 'user_name'@'localhost';
    ALTER USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY 
    'user_name';

 2. drop USER 'user_name'@'localhost';
    flush privileges;
    CREATE USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY 'user_name';
GRANT ALL PRIVILEGES ON * . * TO 'user_name'@'localhost'

 3. If the user is already created, the use the following command:

    ALTER USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY 
        'user_name';

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case, I was transport class component from parent and use it inside as a prop var, using typescript and Formik, and run well like this:

Parent 1

import Parent2 from './../components/Parent2/parent2'
import Parent3 from './../components/Parent3/parent3'

export default class Parent1 extends React.Component {
  render(){
    <React.Fragment>
      <Parent2 componentToFormik={Parent3} />
    </React.Fragment>
  }
}

Parent 2

export default class Parent2 extends React.Component{
  render(){
    const { componentToFormik } = this.props
    return(
    <Formik 
      render={(formikProps) => {
        return(
          <React.fragment>
            {(new componentToFormik(formikProps)).render()}
          </React.fragment>
        )
      }}
    />
    )
  }
}

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

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

You're trying to use the MatFormFieldComponent in SearchComponent but you're not importing the MatFormFieldModule (which exports MatFormFieldComponent); you only export it.

Your MaterialModule needs to import it.

@NgModule({
  imports: [
    MatFormFieldModule,
  ],
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})
export class MaterialModule { }

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I solved it by deleting "/.idea/libraries" from project. Thanks

Angular: Cannot Get /

You can see the errors after stopping debbuging by choosing the option to display ASP.NET Core Web Server output in the output window. In my case I was pointing to a different templateUrl.

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

You can't use fetch in actions without middleware. Actions must be plain objects. You can use a middleware like redux-thunk or redux-saga to do fetch and then dispatch another action.

Here is an example of async action using redux-thunk middleware.

export function checkUserLoggedIn (authCode) {
 let url = `${loginUrl}validate?auth_code=${authCode}`;
  return dispatch => {
    return fetch(url,{
      method: 'GET',
      headers: {
        "Content-Type": "application/json"
      }
      }
    )
      .then((resp) => {
        let json = resp.json();
       if (resp.status >= 200 && resp.status < 300) {
          return json;
        } else {
          return json.then(Promise.reject.bind(Promise));
        }
      })
      .then(
        json => {
          if (json.result && (json.result.status === 'error')) {
            dispatch(errorOccurred(json.result));
            dispatch(logOut());
          }
          else{
            dispatch(verified(json.result));
          }
        }
      )
      .catch((error) => {
        dispatch(warningOccurred(error, url));
      })
  }
}

Angular + Material - How to refresh a data source (mat-table)

I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server: https://blog.angular-university.io/angular-material-data-table/

Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!

organization.model.ts:

export class Organization {
    id: number;
    name: String;
}

organization.service.ts:

import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';

import { Organization } from './organization.model';

export class OrganizationService {
  getConstantOrganizations(filter: String): Observable<Organization[]> {
    if (filter === "All") {
      let Organizations: Organization[] = [
        { id: 1234, name: 'Some data' }
      ];
      return of(Organizations);
     } else {
       let Organizations: Organization[] = [
         { id: 5678, name: 'Some other data' }
       ];
     return of(Organizations);
  }

  // ...just a sample, other filterings would go here - and of course data instead fetched from server.
}

organizationdatasource.model.ts:

import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';

export class OrganizationDataSource extends DataSource<Organization> {
  private organizationsSubject = new BehaviorSubject<Organization[]>([]);

  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(private organizationService: OrganizationService, ) {
    super();
  }

  loadOrganizations(filter: String) {
    this.loadingSubject.next(true);

    return this.organizationService.getOrganizations(filter).pipe(
      catchError(() => of([])),
      finalize(() => this.loadingSubject.next(false))
    ).subscribe(organization => this.organizationsSubject.next(organization));
  }

  connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
    return this.organizationsSubject.asObservable();
  }

  disconnect(collectionViewer: CollectionViewer): void {
    this.organizationsSubject.complete();
    this.loadingSubject.complete();
  }
}

organizations.component.html:

<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">
    <mat-spinner></mat-spinner>
</div>

<div>
  <form [formGroup]="formGroup">
    <mat-form-field fxAuto>
      <div fxLayout="row">
        <mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
          <mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"
            [value]="organizationSelectionAlternative">
            {{organizationSelectionAlternative.name}}
          </mat-option>
        </mat-select>
      </div>
    </mat-form-field>
  </form>
</div>

<mat-table fxLayout="column" [dataSource]="organizationDataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.name}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="number">
    <mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

organizations.component.scss:

.spinner-container {
    height: 360px;
    width: 390px;
    position: fixed;
}

organization.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';

@Component({
  selector: 'organizations',
  templateUrl: './organizations.component.html',
  styleUrls: ['./organizations.component.scss']
})
export class OrganizationsComponent implements OnInit {
  public displayedColumns: string[];
  public organizationDataSource: OrganizationDataSource;
  public formGroup: FormGroup;

  public organizationSelectionAlternatives = [{
    id: 1,
    name: 'All'
  }, {
    id: 2,
    name: 'With organization update requests'
  }, {
    id: 3,
    name: 'With contact update requests'
  }, {
    id: 4,
    name: 'With order requests'
  }]

  constructor(
    private formBuilder: FormBuilder,
    private organizationService: OrganizationService) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      'organizationSelectionControl': []
    })

    const toSelect = this.organizationSelectionAlternatives.find(c => c.id == 1);
    this.formGroup.get('organizationSelectionControl').setValue(toSelect);

    this.organizationDataSource = new OrganizationDataSource(this.organizationService);
    this.displayedColumns = ['name', 'number' ];
    this.updateOrganizationSelection();
  }

  updateOrganizationSelection() {
    this.organizationDataSource.loadOrganizations(this.formGroup.get('organizationSelectionControl').value.name);
  }
}

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

The Above error occurs if any wrong import done. For example sometimes Service files may be added in TestBed.configureTestingModule. And also while importing Material component for example import from

import {MatDialogModule} from '@angular/material/dialog'

not from

import {MatDialogModule} from '@angular/material'

how to refresh page in angular 2

window.location.reload() or just location.reload()

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

'router-outlet' is not a known element

Try with:

@NgModule({
  imports: [
      BrowserModule,
      RouterModule.forRoot(appRoutes),
      FormsModule               
  ],
  declarations: [
      AppComponent,  
      DashboardComponent      
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

There is no need to configure the exports in AppModule, because AppModule wont be imported by other modules in your application.

Angular 2 'component' is not a known element

This convoluted framework is driving me nuts. Given that you defined the custom component in the the template of another component part of the SAME module, then you do not need to use exports in the module (e.g. app.module.ts). You simply need to specify the declaration in the @NgModule directive of the aforementioned module:

// app.module.ts

import { JsonInputComponent } from './json-input/json-input.component';

@NgModule({
  declarations: [
    AppComponent,
    JsonInputComponent
  ],
  ...

You do NOT need to import the JsonInputComponent (in this example) into AppComponent (in this example) to use the JsonInputComponent custom component in AppComponent template. You simply need to prefix the custom component with the module name of which both components have been defined (e.g. app):

<form [formGroup]="reactiveForm">
  <app-json-input formControlName="result"></app-json-input>
</form>

Notice app-json-input not json-input!

Demo here: https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I faced the similar problem in no reason, i think it was caused by IDE(android studio). I have tried all of above solutions but not worked. Finally, in my own situation, i solved this problem by the following actions: - Close the current project and remove it from the list of projects in android studio ,and reopen it by Open an existing Android Studio project, then it may be worked. I hope that my experience will be useful for you.

Error: the entity type requires a primary key

This worked for me:

using System.ComponentModel.DataAnnotations;

[Key]
public int ID { get; set; }

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

'Connect-MsolService' is not recognized as the name of a cmdlet

I had to do this in that order:

Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD

Hibernate Error executing DDL via JDBC Statement

Dialects are removed in recent SQL so use

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>

No provider for Router?

I had a routerLink="." attribute at one of my HTML tags which caused that error

not finding android sdk (Unity)

1- Just open https://developer.android.com/studio/index.html

2- scroll down to the bottom of that page

3- download last version of tools for your OS (for example tools_r25.2.3-windows.zip)

4- Unzip it

5- Delete folder tools from previous Android Sdk folder

6- Copy new folder tools to Android SDK Folder like this image:

enter image description here

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

You are missing either the inclusion of the route package, or including the router module in your main app module.

Make sure your package.json has this:

"@angular/router": "^3.3.1"

Then in your app.module import the router and configure the routes:

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

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent}
        ])
    ],

Update:

Move the AppRoutingModule to be first in the imports:

imports: [
    AppRoutingModule.
    BrowserModule,
    FormsModule,
    HttpModule,
    AlertModule.forRoot(), // What is this?
    LayoutModule,
    UsersModule
  ],

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If someone needs to call Dialog from services here is how to solve the issue. I agree with some of above answer, my answer is for calling dialog in services if someone may face issues on.

Create a service for example DialogService then move your dialog function inside the services and add your dialogservice in the component you call like below code:

 @Component({
  selector: "app-newsfeed",
  templateUrl: "./abc.component.html",
  styleUrls: ["./abc.component.css",],
  providers:[DialogService]
})

otherwise you get error

Reload child component when variables on parent component changes. Angular2

In case, when we have no control over child component, like a 3rd party library component.

We can use *ngIf and setTimeout to reset the child component from parent without making any change in child component.

.template:

.ts:

show:boolean = true

resetChildForm(){
   this.show = false;

   setTimeout(() => {
      this.show = true
    }, 100);
}

React component initialize state from props

set the state data inside constructor like this

constructor(props) {
    super(props);
    this.state = {
      productdatail: this.props.productdetailProps
    };
}

it will not going to work if u set in side componentDidMount() method through props.

Use component from another module

The main rule here is that:

The selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports.

So, try to export it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

What should I export?

Export declarable classes that components in other modules should be able to reference in their templates. These are your public classes. If you don't export a class, it stays private, visible only to other component declared in this module.

The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state(as Ward Bell said in https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2)

Angular creates transitive module for each of @NgModules.

This module collects directives that either imported from another module(if transitive module of imported module has exported directives) or declared in current module.

When angular compiles template that belongs to module X it is used those directives that had been collected in X.transitiveModule.directives.

compiledTemplate = new CompiledTemplate(
    false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);

https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/jit/compiler.ts#L250-L251

enter image description here

This way according to the picture above

  • YComponent can't use ZComponent in its template because directives array of Transitive module Y doesn't contain ZComponent because YModule has not imported ZModule whose transitive module contains ZComponent in exportedDirectives array.

  • Within XComponent template we can use ZComponent because Transitive module X has directives array that contains ZComponent because XModule imports module (YModule) that exports module (ZModule) that exports directive ZComponent

  • Within AppComponent template we can't use XComponent because AppModule imports XModule but XModule doesn't exports XComponent.

See also

Error: Unexpected value 'undefined' imported by the module

This issue of circular dependencies of two module

Module 1:import Module 2
Module 2:import Module 1

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

Angular 4 in combination with feature modules (if you are for instance using a shared-module) requires you to also export the ReactiveFormsModule to work.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { } 

React js change child component's state from parent component

The state should be managed in the parent component. You can transfer the open value to the child component by adding a property.

class ParentComponent extends Component {
   constructor(props) {
      super(props);
      this.state = {
        open: false
      };

      this.toggleChildMenu = this.toggleChildMenu.bind(this);
   }

   toggleChildMenu() {
      this.setState(state => ({
        open: !state.open
      }));
   }

   render() {
      return (
         <div>
           <button onClick={this.toggleChildMenu}>
              Toggle Menu from Parent
           </button>
           <ChildComponent open={this.state.open} />
         </div>
       );
    }
}

class ChildComponent extends Component {
    render() {
      return (
         <Drawer open={this.props.open}/>
      );
    }
}

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

<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
                         ^^^^^^^^^^^^^^^^^^^^^^^^

In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.

In CreateReportCardForm, these are your only three inputs:

@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];

Add one for currentReportCardCount and you should be good to go.

WARNING: sanitizing unsafe style value url

Check this handy pipe for Angular2: Usage:

  1. in the SafePipe code, substitute DomSanitizationService with DomSanitizer

  2. provide the SafePipe if your NgModule

  3. <div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>

Adb install failure: INSTALL_CANCELED_BY_USER

Sometimes the application is bad generated: bad signed or bad aligned and report a mistake.

Check your jarsigner and zipaligned commands.

Angular2 router (@angular/router), how to set default route?

With the current version of angular 2 you can't use '/' on a path or give a name to your route. What you can do is create a route file like "app.routes.ts" and import your components, make sure of the path when importing.

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';`

Add:

import {RouterConfig, provideRouter } from '@angular/router';

Then your routes:

const routes:RouterConfig = [      
    { path: 'Dashboard', component: DashboardComponent },
    { path: 'ConfigManager', component: ConfigManagerComponent },
    { path: 'Merge', component: MergeComponent },
    { path: 'ApplicationManagement', component: ApplicationMgmtComponent }
 ];

Then export:

export  const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)]

In your main.ts import APP_ROUTER_PROVIDERS and add bootstrap the router providers to the main.ts like this:

bootstrap(AppComponent,[APP_ROUTER_PROVIDERS]);

Finally, your link will look like this:

li class="nav hidden-xs"><a [routerLink]="['./Dashboard']" routerLinkActive="active">Dashboard</a>/li>

How do I pass data to Angular routed components?

say you have

  1. component1.ts
  2. component1.html

and you want to pass data to component2.ts.

  • in component1.ts is a variable with data say

      //component1.ts
      item={name:"Nelson", bankAccount:"1 million dollars"}
    
      //component1.html
       //the line routerLink="/meter-readings/{{item.meterReadingId}}" has nothing to 
      //do with this , replace that with the url you are navigating to
      <a
        mat-button
        [queryParams]="{ params: item | json}"
        routerLink="/meter-readings/{{item.meterReadingId}}"
        routerLinkActive="router-link-active">
        View
      </a>
    
      //component2.ts
      import { ActivatedRoute} from "@angular/router";
      import 'rxjs/add/operator/filter';
    
      /*class name etc and class boiler plate */
      data:any //will hold our final object that we passed 
      constructor(
      private route: ActivatedRoute,
      ) {}
    
     ngOnInit() {
    
     this.route.queryParams
      .filter(params => params.reading)
      .subscribe(params => {
      console.log(params); // DATA WILL BE A JSON STRING- WE PARSE TO GET BACK OUR 
                           //OBJECT
    
      this.data = JSON.parse(params.item) ;
    
      console.log(this.data,'PASSED DATA'); //Gives {name:"Nelson", bankAccount:"1 
                                            //million dollars"}
       });
      }
    

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

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

I fixed mine I added to my project > app > libs android volley.jar and my problem was solved

configuring project ':app' failed to find Build Tools revision

It happens because Build Tools revision 24.4.1 doesn't exist.

The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/ directory.

Don't confuse the Android SDK Tools with SDK Build Tools.

Change in your build.gradle

android {
   buildToolsVersion "23.0.2"
   // ...

}

Angular 2 router no base href set

https://angular.io/docs/ts/latest/guide/router.html

Add the base element just after the <head> tag. If the app folder is the application root, as it is for our application, set the href value exactly as shown here.

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.

<head>
  <base href="/">
  ...
</head>

Alternatively add

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

in your bootstrap.

In older versions the imports had to be like

< Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

< RC.0

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

See also Location and HashLocationStrategy stopped working in beta.16

Angular2: child component access parent class variable/function

If you use input property databinding with a JavaScript reference type (e.g., Object, Array, Date, etc.), then the parent and child will both have a reference to the same/one object. Any changes you make to the shared object will be visible to both parent and child.

In the parent's template:

<child [aList]="sharedList"></child>

In the child:

@Input() aList;
...
updateList() {
    this.aList.push('child');
}

If you want to add items to the list upon construction of the child, use the ngOnInit() hook (not the constructor(), since the data-bound properties aren't initialized at that point):

ngOnInit() {
    this.aList.push('child1')
}

This Plunker shows a working example, with buttons in the parent and child component that both modify the shared list.

Note, in the child you must not reassign the reference. E.g., don't do this in the child: this.aList = someNewArray; If you do that, then the parent and child components will each have references to two different arrays.

If you want to share a primitive type (i.e., string, number, boolean), you could put it into an array or an object (i.e., put it inside a reference type), or you could emit() an event from the child whenever the primitive value changes (i.e., have the parent listen for a custom event, and the child would have an EventEmitter output property. See @kit's answer for more info.)

Update 2015/12/22: the heavy-loader example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs array property that is bound to the child components. The child components push() onto that array, and the parent component displays the array.

eloquent laravel: How to get a row count from a ->get()

Direct get a count of row

Using Eloquent

 //Useing Eloquent
 $count = Model::count();    

 //example            
 $count1 = Wordlist::count();

Using query builder

 //Using query builder
 $count = \DB::table('table_name')->count();

 //example
 $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

execute below

Python manage.py makemigrations

It will show missing package.

Install missing package and again run below command to make sure if nothing is missed.

Python manage.py makemigrations

It will resolve your issue.

Dynamically Add Images React Webpack

If you are looking for a way to import all your images from the image

// Import all images in image folder
function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));

Then:

<img src={images['image-01.jpg']}/>

You can find the original thread here: Dynamically import images from a directory using webpack

Your project path contains non-ASCII characters android studio

What I actually did was redirect (I don't actually know the term) the path to my other user (my path was C:\Users\Keith Peñas\ etc.) then, I thought that I had this Spanish letter on, so I redirected the path to my other user, in this case it was (C:\Users\Keith). Then I had another problem: it was somewhat like "Your path cannot be with the rooted path". So I made a folder with the name of my app and then it worked!

Another problem I encountered was: "your path contains white space etc." and it was from my other disk.

Hope this helps!

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

Reasons caused this issue:

  1. An internal issue in Recycler when item animations are enabled
  2. Modification on Recycler data in another thread
  3. Calling notify methods in a wrong way

SOLUTION:

-----------------SOLUTION 1---------------

  • Catching the exception (Not recommended especially for reason #3)

Create a custom LinearLayoutManager as the following and set it to the ReyclerView

    public class CustomLinearLayoutManager extends LinearLayoutManager {

            //Generate constructors

            @Override
            public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {

                try {

                    super.onLayoutChildren(recycler, state);

                } catch (IndexOutOfBoundsException e) {

                    Log.e(TAG, "Inconsistency detected");
                }

            }
        }

Then set RecyclerVIew Layout Manager as follow:

recyclerView.setLayoutManager(new CustomLinearLayoutManager(activity));

-----------------SOLUTION 2---------------

  • Disable item animations (fixes the issue if it caused de to reason #1):

Again, create a custom Linear Layout Manager as follow:

    public class CustomLinearLayoutManager extends LinearLayoutManager {

            //Generate constructors

             @Override
             public boolean supportsPredictiveItemAnimations() {
                 return false;
             }
        }

Then set RecyclerVIew Layout Manager as follow:

recyclerView.setLayoutManager(new CustomLinearLayoutManager(activity));

-----------------SOLUTION 3---------------

  • This solution fixes the issue if it caused by reason #3. You need to make sure that you are using the notify methods in the correct way. Alternatively, use DiffUtil to handle the change in a smart, easy, and smooth way. Using DiffUtil in Android RecyclerView

-----------------SOLUTION 4---------------

  • For reason #2, you need to check all data access to recycler list and make sure that there is no modification on another thread.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Steps:

  1. Add platform runner in build.gralde
    => testCompile group: 'org.junit.platform', name: 'junit-platform-runner', version: '1.7.0'
  2. Anotate test class with @RunWith => @RunWith(JunitPlatform.class)

Reading Excel file using node.js

There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.

Node-xlsx

Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.

node-xlsx project page

Example for parsing file

var xlsx = require('node-xlsx');

var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file

var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer

ExcelJS

Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.

exceljs project page

Code example:

// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
    .then(function() {
        // use workbook
    });

// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

How do I assign a null value to a variable in PowerShell?

These are automatic variables, like $null, $true, $false etc.

about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396

$NULL
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects.

PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello

As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value.

However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored.

$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0

foreach($day in $calendar)
{
    if($day –ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}

output:

Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

How to resolve Value cannot be null. Parameter name: source in linq?

Value cannot be null. Parameter name: source

Above error comes in situation when you are querying the collection which is null.

For demonstration below code will result in such an exception.

Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();

Here is the output of the above code.

Hello World Run-time exception (line 11): Value cannot be null. Parameter name: source

Stack Trace:

[System.ArgumentNullException: Value cannot be null. Parameter name: source] at Program.Main(): line 11

In your case ListMetadataKor is null. Here is the fiddle if you want to play around.

Null pointer Exception on .setOnClickListener

Submit is null because it is not part of activity_main.xml

When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.

try this instead :

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

android:layout_below="@+id/LoginTitle"

but what you want is probably

android:layout_below="@id/LoginTitle"

See this question about the difference between @id and @+id.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Always check if your java files are in src/main/java and not on some other directory path.

Using "-Filter" with a variable

Try this:

$NameRegex = "chalmw-dm"  
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}

Running CMD command in PowerShell

To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.

Input the following into the script:

cmd.exe /c "rd /s /q C:\#TEMP\test1"

cmd.exe /c "rd /s /q C:\#TEMP\test2"

cmd.exe /c "rd /s /q C:\#TEMP\test3"

*Each command needs to be put on a new line calling cmd.exe again.

This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.

It is a much safer way than running batch files!

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Copied from the stacktrace:

BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()

By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib has a constructor with a SessionFactory argument. By adding the @Autowired annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory in your case, and provide it as a constructor argument, e.g.

@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
    // ...
}

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

I am using Windows 10 Home edition.

I tried various combination,

netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork

and also,

Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...

But still cannot activate WiFi hotspot.

While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:

[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]

Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Here the packaging is jar type, hence you need to use manifest plugin, in order to add dependencies into the Manifest.mf

The problem here is that maven could find the dependencies in pom file and compile the source code and create the output jar. But when executing the jar, manifest.mf file contains no details of dependencies. Hence you got this error. This is a case of classpath errors.

Here you can find the details on how to do it.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:

http://mvnrepository.com

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

could not extract ResultSet in hibernate

I Used the following properties in my application.properties file and the issue got resolved

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

and

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

earlier was getting an error

There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is 
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:280)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:254)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

html div onclick event

put your jquery function inside ready function for call click event:

$(document).ready(function() {

  $("#ancherComplaint").click(function () {
     alert($(this).attr("id"));
  });

});

How do I change selected value of select2 dropdown with JqGrid?

Just wanted to add a second answer. If you have already rendered the select as a select2, you will need to have that reflected in your selector as follows:

$("#s2id_originalSelectId").select2("val", "value to select");

Name does not exist in the current context

Jobs.aspx

This is the phyiscal file -> CodeFile="Jobs.aspx.cs"

This is the class which handles the events of the page -> Inherits="Members_Jobs"

Jobs.aspx.cs

This is the partial class which manages the page events -> public partial class Members_Jobs : System.Web.UI.Page

The other part of the partial class should be -> public partial class Members_Jobs this is usually the designer file.

you dont need to have partial classes and could declare your controls all in 1 class and not have a designer file.

EDIT 27/09/2013 11:37

if you are still having issues with this I would do as Bharadwaj suggested and delete the designer file. You can then right-click on the page, in the solution explorer, and there is an option, something like "Convert to Web Application", which will regenerate your designer file

" netsh wlan start hostednetwork " command not working no matter what I try

Same issue.

I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:

1.- Activate (Network Connections) by right click

2.- netsh wlan set hostednetwork mode=allow

3.- netsh wlan start hosted network

Good luck mate !!!

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

  1. Make sure that you have Office runtime installed on the server.
  2. If you are using Windows Server 2008 then using office interops is a lenghty configuration and here are the steps.

Better is to move to Open XML or you can configure as below

  • Install MS Office Pro Latest (I used 2010 Pro)
  • Create User ExcelUser. Assign WordUser with Admin Group
  • Go to Computer -> Manage
  • Add User with below options
  • User Options Password Never Expires
  • Password Cannot Be Change

Com+ Configuration

  • Go to Control Panel - > Administrator -> Component Services -> DCOM Config
  • Open Microsoft Word 97 - 2003 Properties
  • General -> Authentication Level : None
  • Security -> Customize all 3 permissions to allow everyone
  • Identity -> This User -> Use ExcelUser /password
  • Launch the Excel App to make sure everything is fine

3.Change the security settings of Microsoft Excel Application in DCOM Config.

Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.

Right click to get properties dialog. Go to Security tab and customize permissions

See the posts here: Error while creating Excel object , Excel manipulations in WCF using COM

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

Two things are important for above solutions to work:

  1. When applying bindings, you need to specify scope (element) !!

  2. When clearing bindings, you must specify exactly same element used for scope.

Code is below

Markup

<div id="elt1" data-bind="with: data">
    <input type="text" data-bind="value: text1" >
</form>

Binding view

var myViewModel = {
  "data" : {
    "text1" : "bla bla"
  }
}:

Javascript

ko.applyBindings(myViewModel, document.getElementById('elt1'));

Clear bindings

ko.cleanNode(document.getElementById('elt1'));

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

Removing fields from struct or hiding them in JSON Response

You can use tagging attribute "omitifempty" or make optional fields pointers and leave those you want skipped uninitialized.

Windows 7, 64 bit, DLL problems

I solved the problem. When I registered the OCX files, I ran it with the Command Window that had been executed as an administrator.

The remote server returned an error: (403) Forbidden

Looks like problem is based on a server side.

Im my case I worked with paypal server and neither of suggested answers helped, but http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error

I was facing this issue and just got the reply from Paypal technical. Add this will fix the 403 issue. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";

How to use sed to extract substring

Explaining how you can use cut:

cat yourxmlfile | cut -d'"' -f2

It will 'cut' all the lines in the file based on " delimiter, and will take the 2nd field , which is what you wanted.

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Can't access Eclipse marketplace

Im my case, I changed the default browser to internet explorer from google chrome and the issue was resolved.

Change UITableView height dynamically

for resizing my table I went with this solution in my tableview controller witch is perfectly fine:

[objectManager getObjectsAtPath:self.searchURLString
                         parameters:nil
                            success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                NSArray* results = [mappingResult array];
                                self.eventArray = results;
                                NSLog(@"Events number at first: %i", [self.eventArray count]);
                                CGRect newFrame = self.activityFeedTableView.frame;
                                newFrame.size.height = self.cellsHeight + 30.0;
                                self.activityFeedTableView.frame = newFrame;

                                self.cellsHeight = 0.0;

                            }
                            failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                message:[error localizedDescription]
                                                                               delegate:nil
                                                                      cancelButtonTitle:@"OK"
                                                                      otherButtonTitles:nil];
                                [alert show];
                                NSLog(@"Hit error: %@", error);
                            }];

The resizing part is in a method but here is just so you can see it. Now the only problem I haveis resizing the scroll view in the other view controller as I have no idea when the tableview has finished resizing. At the moment I'm doing it with performSelector: afterDelay: but this is really not a good way to do it. Any ideas?

submit the form using ajax

It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.

So, your code will look like:

function sendMyComment() {
    $('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
    $.ajax({
        type: 'POST',
        url: $('#addComment').attr('action'),
        data: $('form').serialize(), 
        success: function(response) { ... },
    });

}

How to increase IDE memory limit in IntelliJ IDEA on Mac?

Current version: Help | Change Memory Settings:

Change memory settings

Since IntelliJ IDEA 15.0.4 you can also use: Help | Edit Custom VM Options...:

This will automatically create a copy of the .vmoptions file in the config folder and open a dialog to edit it.


Older versions:

IntelliJ IDEA 12 is a signed application, therefore changing options in Info.plist is no longer recommended, as the signature will not match and you will get issues depending on your system security settings (app will either not run, or firewall will complain on every start, or the app will not be able to use the system keystore to save passwords).

As a result of addressing IDEA-94050 a new way to supply JVM options was introduced in IDEA 12:

Now it can take VM options from ~/Library/Preferences/<appFolder>/idea.vmoptions and system properties from ~/Library/Preferences/<appFolder>/idea.properties.

For example, to use -Xmx2048m option you should copy the original .vmoptions file from /Applications/IntelliJ IDEA.app/bin/idea.vmoptions to ~/Library/Preferences/IntelliJIdea12/idea.vmoptions, then modify the -Xmx setting.

The final file should look like:

-Xms128m
-Xmx2048m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

Copying the original file is important, as options are not added, they are replaced.

This way your custom options will be preserved between updates and application files will remain unmodified making signature checker happy.


Community Edition: ~/Library/Preferences/IdeaIC12/idea.vmoptions file is used instead.

Unable to open debugger port in IntelliJ

This error can happen Tomcat is already running. So make sure Tomcat isn't running in the background if you've asked Intellij to start it up ( default ).

Also, check the full output window for more errors. As a more useful error may have preceded this one ( as was the case with my configuration just now )

How to JUnit test that two List<E> contain the same elements in the same order?

I prefer using Hamcrest because it gives much better output in case of a failure

Assert.assertThat(listUnderTest, 
       IsIterableContainingInOrder.contains(expectedList.toArray()));

Instead of reporting

expected true, got false

it will report

expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."

IsIterableContainingInOrder.contain

Hamcrest

According to the Javadoc:

Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items

So the listUnderTest must have the same number of elements and each element must match the expected values in order.

How to fix 'Microsoft Excel cannot open or save any more documents'

After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account

how to remove empty strings from list, then remove duplicate values from a list

Amiram's answer is correct, but Distinct() as implemented is an N2 operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.

A sorted list can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:

public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
   var toDedupe = input.OrderBy(x=>x);

   T prev;
   foreach(var element in toDedupe)
   {
      if(element == prev) continue;

      yield return element;
      prev = element;      
   }
}

//Usage
dtList  = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();

This returns the same elements; they're just sorted.

Powershell v3 Invoke-WebRequest HTTPS error

If you run this as administrator, that error should go away

Dealing with "Xerces hell" in Java/Maven?

Frankly, pretty much everything that we've encountered works just fine w/ the JAXP version, so we always exclude xml-apis and xercesImpl.

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

How do I specify the JDK for a GlassFish domain?

In my case the problem was the JAVA_HOME variable was set an installed jre.

An alternative to setting the AS_JAVA variable is to set JAVA_HOME environment variable to the jdk (i.e. /usr/local/jdk1.7.0.51).

Tomcat 7 "SEVERE: A child container failed during start"

I have faced a similar problem, but it consoles the error like an encoding issue. After changing the IDE encoding, it works fine. Eclipse IDE

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours). If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed.

MySQL suggests:

You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property autoReconnect=true to avoid this problem.

How to force table cell <td> content to wrap?

If you want fix the column you should set width. For example:

<td style="width:100px;">some data</td>

The result of a query cannot be enumerated more than once

if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-

repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();

try like this

An item with the same key has already been added

I have had the same error. When i check the code then i found that declare "GET" request in my angular (font-end) side and declare "POST" request in the ASP.net (back-end) side. Set POST/GET any one in both side. Then solved the error.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Your ComboBox is trying to bind to bind to GridItem[x].CompanyItems, which doesn't exist.

Your RelativeBinding is close, however it needs to bind to DataContext.CompanyItems because Window.CompanyItems does not exist

How to stop BackgroundWorker correctly

The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again. How to do this is explained in this SO question.

Change label text using JavaScript

Have you tried .innerText or .value instead of .innerHTML?

System.Runtime.InteropServices.COMException (0x800A03EC)

It 'a permission problem when IIS is running I had this problem and I solved it in this way

I went on folders

C:\Windows\ System32\config\SystemProfile

and

C:\Windows\SysWOW64\config\SystemProfile

are protected system folders, they usually have the lock.

Right-click-> Card security-> Click on Edit-> Add untente "Autenticadet User" and assign permissions.

At this point everything is solved, if you still have problems try to give all permissions to "Everyone"

FIND_IN_SET() vs IN()

Let me explain when to use FIND_IN_SET and When to use IN.

Let's take table A which has columns named "aid","aname". Let's take table B which has columns named "bid","bname","aids".

Now there are dummy values in Table A and Table B as below.

Table A

aid aname

1 Apple

2 Banana

3 Mango

Table B

bid bname aids

1 Apple 1,2

2 Banana 2,1

3 Mango 3,1,2

enter code here

Case1: if you want to get those records from table b which has 1 value present in aids columns then you have to use FIND_IN_SET.

Query: select * from A JOIN B ON FIND_IN_SET(A.aid,b.aids) where A.aid = 1 ;

Case2: if you want to get those records from table a which has 1 OR 2 OR 3 value present in aid columns then you have to use IN.

Query: select * from A JOIN B ON A.aid IN (b.aids);

Now here upto you that what you needs through mysql query.

DataGridView.Clear()

Set the datasource property to an empty string then call the Clear method.

Binding Button click to a method

Some more explanations to the solution Rachel already gave:

"WPF Apps With The Model-View-ViewModel Design Pattern"

by Josh Smith

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

How to check "hasRole" in Java Code with Spring Security?

you can use the isUserInRole method of the HttpServletRequest object.

something like:

public String createForm(HttpSession session, HttpServletRequest request,  ModelMap   modelMap) {


    if (request.isUserInRole("ROLE_ADMIN")) {
        // code here
    }
}

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

.NET Console Application Exit Event

For the CTRL+C case, you can use this:

// Tell the system console to handle CTRL+C by calling our method that
// gracefully shuts down.
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);


static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
            Console.WriteLine("Shutting down...");
            // Cleanup here
            System.Threading.Thread.Sleep(750);
}

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

How to resolve a Java Rounding Double issue

As the previous answers stated, this is a consequence of doing floating point arithmetic.

As a previous poster suggested, When you are doing numeric calculations, use java.math.BigDecimal.

However, there is a gotcha to using BigDecimal. When you are converting from the double value to a BigDecimal, you have a choice of using a new BigDecimal(double) constructor or the BigDecimal.valueOf(double) static factory method. Use the static factory method.

The double constructor converts the entire precision of the double to a BigDecimal while the static factory effectively converts it to a String, then converts that to a BigDecimal.

This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the BigDecimal constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.

double value = 0.585;
System.out.println(new BigDecimal(value));
System.out.println(BigDecimal.valueOf(value));

on my system gives

0.58499999999999996447286321199499070644378662109375
0.585

Has anyone ever got a remote JMX JConsole to work?

You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.

One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.

There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from

http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore

http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx

http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html

It's even possible to setup an ssh tunnel and still get it to work :-)

Could not load type from assembly error

I had the same issue. I just resolved this by updating the assembly via GAC.

To use gacutil on a development machine go to: Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010).

I used these commands to uninstall and Reinstall respectively.

gacutil /u myDLL

gacutil /i "C:\Program Files\Custom\mydllname.dll"

Note: i have not uninstall my dll in my case i have just updated dll with current path.

Attributes / member variables in interfaces?

The point of an interface is to specify the public API. An interface has no state. Any variables that you create are really constants (so be careful about making mutable objects in interfaces).

Basically an interface says here are all of the methods that a class that implements it must support. It probably would have been better if the creators of Java had not allowed constants in interfaces, but too late to get rid of that now (and there are some cases where constants are sensible in interfaces).

Because you are just specifying what methods have to be implemented there is no idea of state (no instance variables). If you want to require that every class has a certain variable you need to use an abstract class.

Finally, you should, generally speaking, not use public variables, so the idea of putting variables into an interface is a bad idea to begin with.

Short answer - you can't do what you want because it is "wrong" in Java.

Edit:

class Tile 
    implements Rectangle 
{
    private int height;
    private int width;

     @Override
    public int getHeight() {
        return height;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public void setHeight(int h) {
        height = h;
    }

    @Override
    public void setWidth(int w) { 
        width = w;  
    }
}

an alternative version would be:

abstract class AbstractRectangle 
    implements Rectangle 
{
    private int height;
    private int width;

     @Override
    public int getHeight() {
        return height;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public void setHeight(int h) {
        height = h;
    }

    @Override
    public void setWidth(int w) { 
        width = w;  
    }
}

class Tile 
    extends AbstractRectangle 
{
}

What are best practices that you use when writing Objective-C and Cocoa?

If you're using Leopard (Mac OS X 10.5) or later, you can use the Instruments application to find and track memory leaks. After building your program in Xcode, select Run > Start with Performance Tool > Leaks.

Even if your app doesn't show any leaks, you may be keeping objects around too long. In Instruments, you can use the ObjectAlloc instrument for this. Select the ObjectAlloc instrument in your Instruments document, and bring up the instrument's detail (if it isn't already showing) by choosing View > Detail (it should have a check mark next to it). Under "Allocation Lifespan" in the ObjectAlloc detail, make sure you choose the radio button next to "Created & Still Living".

Now whenever you stop recording your application, selecting the ObjectAlloc tool will show you how many references there are to each still-living object in your application in the "# Net" column. Make sure you not only look at your own classes, but also the classes of your NIB files' top-level objects. For example, if you have no windows on the screen, and you see references to a still-living NSWindow, you may have not released it in your code.

Typescript - multidimensional array initialization

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {
    private things: Thing[][];

    constructor() {
        this.things = [];

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = [];
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();
            }
        }
    }
}

What is the default access modifier in Java?

Default access modifier - If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).

Swift - encode URL

For Swift 5 to endcode string

func escape(string: String) -> String {
    let allowedCharacters = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":=\"#%/<>?@\\^`{|}").inverted) ?? ""
    return allowedCharacters
}

How to use ?

let strEncoded = self.escape(string: "http://www.edamam.com/ontologies/edamam.owl#recipe_e2a1b9bf2d996cbd9875b80612ed9aa4")
print("escapedString: \(strEncoded)")

how to check for null with a ng-if values in a view with angularjs?

See the correct way with your example:

<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>

Regards, Nicholls

Laravel back button

Indeed using {{ URL:previous() }} do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.

In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.

When I use URL:previous(), Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:

<a href="javascript:history.back()" class="btn btn-default">Voltar</a>

I'm tested this on Laravel 5.3, just for clarification.

Javascript: Extend a Function

Use extendFunction.js

init = extendFunction(init, function(args) {
  doSomethingHereToo();
});

But in your specific case, it's easier to extend the global onload function:

extendFunction('onload', function(args) {
  doSomethingHereToo();
});

I actually really like your question, it's making me think about different use cases.

For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert() would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.

Java: How to convert a File object to a String object in java?

Use a library like Guava or Commons / IO. They have oneliner methods.

Guava:

Files.toString(file, charset);

Commons / IO:

FileUtils.readFileToString(file, charset);

Without such a library, I'd write a helper method, something like this:

public String readFile(File file, Charset charset) throws IOException {
    return new String(Files.readAllBytes(file.toPath()), charset);
}

Remove all spaces from a string in SQL Server

this is useful for me:

CREATE FUNCTION dbo.TRIM(@String VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
    RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END
GO

.

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

What is the role of the bias in neural networks?

In particular, Nate’s answer, zfy’s answer, and Pradi’s answer are great.

In simpler terms, biases allow for more and more variations of weights to be learnt/stored... (side-note: sometimes given some threshold). Anyway, more variations mean that biases add richer representation of the input space to the model's learnt/stored weights. (Where better weights can enhance the neural net’s guessing power)

For example, in learning models, the hypothesis/guess is desirably bounded by y=0 or y=1 given some input, in maybe some classification task... i.e some y=0 for some x=(1,1) and some y=1 for some x=(0,1). (The condition on the hypothesis/outcome is the threshold I talked about above. Note that my examples setup inputs X to be each x=a double or 2 valued-vector, instead of Nate's single valued x inputs of some collection X).

If we ignore the bias, many inputs may end up being represented by a lot of the same weights (i.e. the learnt weights mostly occur close to the origin (0,0). The model would then be limited to poorer quantities of good weights, instead of the many many more good weights it could better learn with bias. (Where poorly learnt weights lead to poorer guesses or a decrease in the neural net’s guessing power)

So, it is optimal that the model learns both close to the origin, but also, in as many places as possible inside the threshold/decision boundary. With the bias we can enable degrees of freedom close to the origin, but not limited to origin's immediate region.

Print in new line, java

"\n" this is the simple method to separate the continuous String

How can I convince IE to simply display application/json rather than offer to download it?

I found the answer.

You can configure IE8 to display application/json in the browser window by updating the registry. There's no need for an external tool. I haven't tested this broadly, but it works with IE8 on Vista.

To use this, remember, all the usual caveats about updating the registry apply. Stop IE. Then, cut and paste the following into a file, by the name of json-ie.reg.

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Then double-click the .reg file. Restart IE. The new behavior you get when tickling a URL that returns a doc with Content-Type: application/json or Content-Type: text/json is like this:

alt text

What it does, why it works:

The 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" action. Basically this registry entry is telling IE that for docs that have a mime type of application/json, just view it in place. This won't affect any application/json documents downloaded via <script> tags, or via XHR, and so on.

The CLSID and Encoding keys get the same values used for image/gif, image/jpeg, and text/html.

This hint came from this site, and from Microsoft's article Handling MIME Types in Internet Explorer .


In FF, you don't need an external add-on either. You can just use the view-source: pseudo-protocol. Enter a URL like this into the address bar:

view-source:http://myserver/MyUrl/That/emits/Application/json

This pseudo-protocol used to be supported in IE, also, until WinXP-sp2, when Microsoft disabled it for security reasons.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

5 Jan 2021: link update thanks to @Sadap's comment.

Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.

For example, you can see that _WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).

Anyway, I found the tables quite informative and thought I'd share here.

How to run Nginx within a Docker container without halting?

For all who come here trying to run a nginx image in a docker container, that will run as a service

As there is no whole Dockerfile, here is my whole Dockerfile solving the issue.

Nice and working. Thanks to all answers here in order to solve the final nginx issue.

FROM ubuntu:18.04
MAINTAINER stackoverfloguy "[email protected]"
RUN apt-get update -y
RUN apt-get install net-tools nginx ufw sudo -y
RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER docker
RUN sudo ufw default allow incoming
RUN sudo rm /etc/nginx/nginx.conf
RUN sudo rm /etc/nginx/sites-available/default
RUN sudo rm /var/www/html/index.nginx-debian.html
VOLUME /var/log
VOLUME /usr/share/nginx/html
VOLUME /etc/nginx
VOLUME /var/run
COPY conf/nginx.conf /etc/nginx/nginx.conf
COPY content/* /var/www/html/
COPY Dockerfile /var/www/html
COPY start.sh /etc/nginx/start.sh
RUN sudo chmod +x /etc/nginx/start.sh
RUN sudo chmod -R 777 /var/www/html
EXPOSE 80
EXPOSE 443
ENTRYPOINT sudo nginx -c /etc/nginx/nginx.conf -g 'daemon off;'

And run it with:

docker run -p 80:80 -p 443:443 -dit

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

Cannot make a static reference to the non-static method

for others that find this in the search:

I often get this one when I accidentally call a function using the class name rather than the object name. This typically happens because i give them too similar names : P

ie:

MyClass myclass = new MyClass();

// then later

MyClass.someFunction();

This is obviously a static method. (good for somethings) But what i really wanted to do (in most cases was)

myclass.someFunction();

It's such a silly mistake, but every couple of months, i waste about 30 mins messing with vars in the "MyClass" definitions to work out what im doing wrong when really, its just a typo.

Funny note: stack overflow highlights the syntax to make the mistake really obvious here.

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Use case/esac to test:

case "$var" in
  "") echo "zero length";;
esac

Change old commit message on Git

FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!

Program to find prime numbers

    public static void Main()
    {  
        Console.WriteLine("enter the number");
        int i = int.Parse(Console.ReadLine());

        for (int j = 2; j <= i; j++)
        {
            for (int k = 2; k <= i; k++)
            {
                if (j == k)
                {
                    Console.WriteLine("{0}is prime", j);

                    break;
                }
                else if (j % k == 0)
                {
                    break;
                }
            }
        }
        Console.ReadLine();          
    }

Read all worksheets in an Excel workbook into an R list with data.frames

You can load the work book and then use lapply, getSheets and readWorksheet and do something like this.

wb.mtcars <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", 
                          package = "XLConnect"))
sheet_names <- getSheets(wb.mtcars)
names(sheet_names) <- sheet_names

sheet_list <- lapply(sheet_names, function(.sheet){
    readWorksheet(object=wb.mtcars, .sheet)})

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this

    router.post('/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


    return res.json({Name: req.body.name, Phone: req.body.phone});
});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"
}

<script>
  $(document).ready(function(){

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

Does JSON syntax allow duplicate keys in an object?

Posting and answer because there is a lot of outdated ideas and confusion about the standards. As of December 2017, there are two competing standards:

RFC 8259 - https://tools.ietf.org/html/rfc8259

ECMA-404 - http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf

json.org suggests ECMA-404 is the standard, but this site does not appear to be an authority. While I think it's fair to consider ECMA the authority, what's important here is, the only difference between the standards (regarding unique keys) is that RFC 8259 says the keys should be unique, and the ECMA-404 says they are not required to be unique.

RFC-8259:

"The names within an object SHOULD be unique."

The word "should" in all caps like that, has a meaning within the RFC world, that is specifically defined in another standard (BCP 14, RFC 2119 - https://tools.ietf.org/html/rfc2119) as,

  1. SHOULD This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

ECMA-404:

"The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs."

So, no matter how you slice it, it's syntactically valid JSON.

The reason given for the unique key recommendation in RFC 8259 is,

An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

In other words, from the RFC 8259 viewpoint, it's valid but your parser may barf and there's no promise as to which, if any, value will be paired with that key. From the ECMA-404 viewpoint (which I'd personally take as the authority), it's valid, period. To me this means that any parser that refuses to parse it is broken. It should at least parse according to both of these standards. But how it gets turned into your native object of choice is, in any case, unique keys or not, completely dependent on the environment and the situation, and none of that is in the standard to begin with.

How can I declare a global variable in Angular 2 / Typescript?

IMHO for Angular2 (v2.2.3) the best way is to add services that contain the global variable and inject them into components without the providers tag inside the @Component annotation. By this way you are able to share information between components.

A sample service that owns a global variable:

import { Injectable } from '@angular/core'

@Injectable()
export class SomeSharedService {
  public globalVar = '';
}

A sample component that updates the value of your global variable:

import { SomeSharedService } from '../services/index';

@Component({
  templateUrl: '...'
})
export class UpdatingComponent {

  constructor(private someSharedService: SomeSharedService) { }

  updateValue() {
    this.someSharedService.globalVar = 'updated value';
  }
}

A sample component that reads the value of your global variable:

import { SomeSharedService } from '../services/index';

@Component({
  templateUrl: '...'
})
export class ReadingComponent {

  constructor(private someSharedService: SomeSharedService) { }

  readValue() {
    let valueReadOut = this.someSharedService.globalVar;
    // do something with the value read out
  }
}

Note that providers: [ SomeSharedService ] should not be added to your @Component annotation. By not adding this line injection will always give you the same instance of SomeSharedService. If you add the line a freshly created instance is injected.

How to do associative array/hashing in JavaScript

https://gist.github.com/alexhawkins/f6329420f40e5cafa0a4

var HashTable = function() {
  this._storage = [];
  this._count = 0;
  this._limit = 8;
}


HashTable.prototype.insert = function(key, value) {

  // Create an index for our storage location by passing
  // it through our hashing function
  var index = this.hashFunc(key, this._limit);

  // Retrieve the bucket at this particular index in
  // our storage, if one exists
  //[[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ]  [ [k,v] ] ]
  var bucket = this._storage[index]

  // Does a bucket exist or do we get undefined
  // when trying to retrieve said index?
  if (!bucket) {
    // Create the bucket
    var bucket = [];
    // Insert the bucket into our hashTable
    this._storage[index] = bucket;
  }

  var override = false;

  // Now iterate through our bucket to see if there are any conflicting
  // key value pairs within our bucket. If there are any, override them.
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {

      // Override value stored at this key
      tuple[1] = value;
      override = true;
    }
  }

  if (!override) {
    // Create a new tuple in our bucket.
    // Note that this could either be the new empty bucket we created above
    // or a bucket with other tupules with keys that are different than
    // the key of the tuple we are inserting. These tupules are in the same
    // bucket because their keys all equate to the same numeric index when
    // passing through our hash function.
    bucket.push([key, value]);
    this._count++

    // Now that we've added our new key/val pair to our storage
    // let's check to see if we need to resize our storage
    if (this._count > this._limit * 0.75) {
      this.resize(this._limit * 2);
    }
  }
  return this;
};


HashTable.prototype.remove = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];
  if (!bucket) {
    return null;
  }

  // Iterate over the bucket
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];

    // Check to see if key is inside bucket
    if (tuple[0] === key) {

      // If it is, get rid of this tuple
      bucket.splice(i, 1);
      this._count--;
      if (this._count < this._limit * 0.25) {
        this._resize(this._limit / 2);
      }
      return tuple[1];
    }
  }
};


HashTable.prototype.retrieve = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];

  if (!bucket) {
    return null;
  }

  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {
      return tuple[1];
    }
  }

  return null;
};


HashTable.prototype.hashFunc = function(str, max) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    var letter = str[i];
    hash = (hash << 5) + letter.charCodeAt(0);
    hash = (hash & hash) % max;
  }
  return hash;
};


HashTable.prototype.resize = function(newLimit) {
  var oldStorage = this._storage;

  this._limit = newLimit;
  this._count = 0;
  this._storage = [];

  oldStorage.forEach(function(bucket) {
    if (!bucket) {
      return;
    }
    for (var i = 0; i < bucket.length; i++) {
      var tuple = bucket[i];
      this.insert(tuple[0], tuple[1]);
    }
  }.bind(this));
};


HashTable.prototype.retrieveAll = function() {
  console.log(this._storage);
  //console.log(this._limit);
};

/******************************TESTS*******************************/

var hashT = new HashTable();

hashT.insert('Alex Hawkins', '510-599-1930');
//hashT.retrieve();
//[ , , , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Boo Radley', '520-589-1970');
//hashT.retrieve();
//[ , [ [ 'Boo Radley', '520-589-1970' ] ], , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Vance Carter', '120-589-1970').insert('Rick Mires', '520-589-1970').insert('Tom Bradey', '520-589-1970').insert('Biff Tanin', '520-589-1970');
//hashT.retrieveAll();
/*
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '520-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '520-589-1970' ] ] ]
*/

// Override example (Phone Number Change)
//
hashT.insert('Rick Mires', '650-589-1970').insert('Tom Bradey', '818-589-1970').insert('Biff Tanin', '987-589-1970');
//hashT.retrieveAll();

/*
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '818-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '650-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]

*/

hashT.remove('Rick Mires');
hashT.remove('Tom Bradey');
//hashT.retrieveAll();

/*
[ ,
  [ [ 'Boo Radley', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]


*/

hashT.insert('Dick Mires', '650-589-1970').insert('Lam James', '818-589-1970').insert('Ricky Ticky Tavi', '987-589-1970');
hashT.retrieveAll();


/* NOTICE HOW THE HASH TABLE HAS NOW DOUBLED IN SIZE UPON REACHING 75% CAPACITY, i.e. 6/8. It is now size 16.
 [,
  ,
  [ [ 'Vance Carter', '120-589-1970' ] ],
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Dick Mires', '650-589-1970' ],
    [ 'Lam James', '818-589-1970' ] ],
  ,
  ,
  ,
  ,
  ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Ricky Ticky Tavi', '987-589-1970' ] ],
  ,
  ,
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]

*/

console.log(hashT.retrieve('Lam James'));  // 818-589-1970
console.log(hashT.retrieve('Dick Mires')); // 650-589-1970
console.log(hashT.retrieve('Ricky Ticky Tavi')); //987-589-1970
console.log(hashT.retrieve('Alex Hawkins')); // 510-599-1930
console.log(hashT.retrieve('Lebron James')); // null

Measure execution time for a Java method

If you are currently writing the application, than the answer is to use System.currentTimeMillis or System.nanoTime serve the purpose as pointed by people above.

But if you have already written the code, and you don't want to change it its better to use Spring's method interceptors. So for instance your service is :

public class MyService { 
    public void doSomething() {
        for (int i = 1; i < 10000; i++) {
            System.out.println("i=" + i);
        }
    }
}

To avoid changing the service, you can write your own method interceptor:

public class ServiceMethodInterceptor implements MethodInterceptor {
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = methodInvocation.proceed();
        long duration = System.currentTimeMillis() - startTime;
        Method method = methodInvocation.getMethod();
        String methodName = method.getDeclaringClass().getName() + "." + method.getName();
        System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
        return null;
    }
}

Also there are open source APIs available for Java, e.g. BTrace. or Netbeans profiler as suggested above by @bakkal and @Saikikos. Thanks.

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

Total width of element (including padding and border) in jQuery

[Update]

The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.

Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border and padding by default, and also the margin if the first argument of the function is true


[Original answer]

The width method no longer requires the dimensions plugin, because it has been added to the jQuery Core

What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width method

Something like this:

var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width

Split into multiple lines to make it more readable

That way you will always get the correct computed value, even if you change the padding or margin values from the css

How to make phpstorm display line numbers by default?

Follow the below steps:

  • Click on File->Settings->
  • In the Settings dialog box Expand Editor under IDE Settings
  • Click Apperance - > select Show line numbers.
  • Click Apply->Ok.

How to make html <select> element look like "disabled", but pass values?

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.

$('#myForm').submit(function() {
    $('select').removeAttr('disabled');
});

Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.

$(document).ready(function() {
    $('select').attr('disabled', 'disabled');
});

Webview load html from assets directory

Whenever you are creating activity, you must add setcontentview(your layout) after super call. Because setcontentview bind xml into your activity so that's the reason you are getting nullpointerexception.

 setContentView(R.layout.webview);  
 webView = (WebView) findViewById(R.id.webView1);
 wv.loadUrl("file:///android_asset/xyz.html");

How to change default language for SQL Server?

Using SQL Server Management Studio

To configure the default language option

  1. In Object Explorer, right-click a server and select Properties.
  2. Click the Misc server settings node.
  3. In the Default language for users box, choose the language in which Microsoft SQL Server should display system messages. The default language is English.

Using Transact-SQL

To configure the default language option

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute.

This example shows how to use sp_configure to configure the default language option to French

USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

The 33 languages of SQL Server

| LANGID |        ALIAS        |
|--------|---------------------|
|    0   | English             |
|    1   | German              |
|    2   | French              |
|    3   | Japanese            |
|    4   | Danish              |
|    5   | Spanish             |
|    6   | Italian             |
|    7   | Dutch               |
|    8   | Norwegian           |
|    9   | Portuguese          |
|   10   | Finnish             |
|   11   | Swedish             |
|   12   | Czech               |
|   13   | Hungarian           |
|   14   | Polish              |
|   15   | Romanian            |
|   16   | Croatian            |
|   17   | Slovak              |
|   18   | Slovenian           |
|   19   | Greek               |
|   20   | Bulgarian           |
|   21   | Russian             |
|   22   | Turkish             |
|   23   | British English     |
|   24   | Estonian            |
|   25   | Latvian             |
|   26   | Lithuanian          |
|   27   | Brazilian           |
|   28   | Traditional Chinese |
|   29   | Korean              |
|   30   | Simplified Chinese  |
|   31   | Arabic              |
|   32   | Thai                |
|   33   | Bokmål              |

Error: Can't set headers after they are sent to the client

I boiled my head over this issue and it has happened due to a careless mistake on handling the callbacks. non returned callbacks cause the response to be set twice.!

My program had a code which validate request and query the DB. after validating if error is there, I was calling back the index.js with the validation errors . And if validation passes it goes ahead and hit the db with success/failure.

    var error = validateRequestDetails("create",queryReq);
    if (error)
        callback(error, null);
   else
    some code 
    callback(null, success);

What was happening is : Incase validation fails the callback get called and response get set. But not returned. So it still continues the method goes to db and hit success/failure . It calls the same callback again causing the response to be set twice now.

So solution is simple, you need to 'return' the callback so that the method don't continue executing, once the error has occurred and hence set the response object once

  var error = validateRequestDetails("create",queryReq);
    if (error)
        callback(error, null);
        return;
    else
       some code 
       callback(null, success);

Where are $_SESSION variables stored?

They're generally stored on the server. Where they're stored is up to you as the developer. You can use the session.save_handler configuration variable and the session_set_save_handler to control how sessions get saved on the server. The default save method is to save sessions to files. Where they get saved is controlled by the session.save_path variable.

How to specify a multi-line shell variable?

read does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.

oneLine=$(printf %s \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)
multiLine=$(printf '%s\n' \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)

I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.

I use it like this

export LS_COLORS=$(printf %s    \
    ':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33'   \
    ...
    ':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')

in a file sourced from both my .bashrc and .zshrc.

How to stop a function

This will end the function, and you can even customize the "Error" message:

import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here 

How can I create an array with key value pairs?

You can create the single value array key-value as

$new_row = array($row["datasource_id"]=>$row["title"]);

inside while loop, and then use array_merge function in loop to combine the each new $new_row array.

100% height minus header?

As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.

The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.

How to generate and validate a software license key?

The C# / .NET engine we use for licence key generation is now maintained as open source:

https://github.com/appsoftware/.NET-Licence-Key-Generator.

It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.

As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.

Linux: Which process is causing "device busy" when doing umount?

Check for open loop devices mapped to a file on the filesystem with "losetup -a". They wont show up with either lsof or fuser.

java.text.ParseException: Unparseable date

Check your Pattern (DD-MMM-YYYY) and the input for the parse("29-11-2018") method. Input to the parse method should follow : DD-MMM-YYYY i,e. 21-AUG-2019

In My Code:

String pattern = "DD-MMM-YYYY";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

    try {
        startDate = simpleDateFormat.parse("29-11-2018");// here no pattern match 
        endDate = simpleDateFormat.parse("28-AUG-2019");// Ok 
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Bootstrap 4 img-circle class not working

Now the class is this

_x000D_
_x000D_
 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
_x000D_
_x000D_

Force IE10 to run in IE10 Compatibility View?

While you should fix your site so it works without Compatibility View, try putting the X-UA-Compatible meta tag as the very first thing after the opening <head>, before the title

Default value in an asp.net mvc view model

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

Composer install error - requires ext_curl when it's actually enabled

Enable in php 7 try below command

sudo apt-get install php7.0-curl

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

CSS - center two images in css side by side

I understand that this question is old, but there is a good solution for it in HTML5. You can wrap it all in a <figure></figure> tag. The code would look something like this:

<div id="wrapper">
<figure>

<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp- 
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>

<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp- 
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>

</figure>
</div>

and the CSS:

#wrapper{
 text-align:center;
}

Running Facebook application on localhost

Ok I'm not sure what's up with these answers but I'll let you know what worked for me as advised by a senior dev at my work. I'm working in Ruby on Rails and using Facebook's JavaScript code to get access tokens.

Problem: To do authentication, Facebook is taking the url from your address bar and comparing that with what they have on file. They don't allow you to use localhost:3000 for whatever reason. However, you can use a completely made-up domain name like yoursite.dev by running a local server and pointing yoursite.dev to 127.0.0.1:3000 or wherever your localhost was pointing to.

Step 1: Install or update Nginx

$ brew install nginx (install) or $ brew upgrade nginx (update)

Step 2: Open up your nginx config file

/usr/local/etc/nginx/nginx.conf (usually here)

/opt/boxen/config/nginx/nginx.conf(if you use Boxen)

Step 3 Add this bit of code into your http {} block

Replace proxy_pass with wherever you want to point yoursite.dev to. In my case it was replacing localhost:3000 or the equivalent 127.0.0.1:3000

server {
  listen       yoursite.dev:80;
  server_name  yoursite.dev;
  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}

Step 4: Edit your hosts file, in /etc/hosts on Mac to include

127.0.0.1   yoursite.dev

This file directs domains to localhost. Nginx listens in on localhost and redirects if it matches a rule.

Step 5: Every time you use your dev environment going forward, you use the yoursite.dev in the address bar instead of localhost:3000 so Facebook logs you in correctly.

what is the difference between ajax and jquery and which one is better?

They aren't comparable.

Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.

jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

ImportError: cannot import name

The problem is that you have a circular import: in app.py

from mod_login import mod_login

in mod_login.py

from app import app

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import

How can I send a file document to the printer and have it print?

This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.

private void SendToPrinter()
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"c:\output.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Hidden;

  Process p = new Process();
  p.StartInfo = info;
  p.Start();

  long ticks = -1;
  while (ticks != p.TotalProcessorTime.Ticks)
  {
    ticks = p.TotalProcessorTime.Ticks;
    Thread.Sleep(1000);
  }

  if (false == p.CloseMainWindow())
    p.Kill();
}

Java Code for calculating Leap Year

this answer is great but it won't work for years before Christ (using a proleptic Gregorian calendar). If you want it to work for B.C. years, then use the following adaptation:

public static boolean isLeapYear(final int year) {
    final Calendar cal = Calendar.getInstance();
    if (year<0) {
        cal.set(Calendar.ERA, GregorianCalendar.BC);
        cal.set(Calendar.YEAR, -year);
    } else
        cal.set(Calendar.YEAR, year);
    return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}

You can verify that for yourself by considering that year -5 (i.e. 4 BC) should be pronounced as a leap year assuming a proleptic Gregorian calendar. Same with year -1 (the year before 1 AD). The linked to answer does not handle that case whereas the above adapted code does.

How do I start PowerShell from Windows Explorer?

In Windows Explorer, just go to the Address Bar at the top (keyboard shortcuts: Alt+D or Ctrl+L) and type powershell or powershell_ise and press Enter. A PowerShell command window opens with the current directory.

keycloak Invalid parameter: redirect_uri

If you're trying to redirect to the keycloak login page after logout (as I was), that is not allowed by default but also needs to be configured in the "Valid Redirect URIs" setting in the admin console of your client.

How to vertically center <div> inside the parent element with CSS?

http://jsfiddle.net/dvL512e7/

Unless the aligned div has fixed height, try using the following CSS to the aligned div:

{
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: table;
}

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

Copy output of a JavaScript variable to the clipboard

When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject

How to subtract hours from a date in Oracle so it affects the day also

date - n will subtract n days form given date. In order to subtract hrs you need to convert it into day buy dividing it with 24. In your case it should be to_char(sysdate - (2 + 2/24), 'MM-DD-YYYY HH24'). This will subract 2 days and 2 hrs from sysdate.

Get timezone from users browser using moment(timezone).js

You can also get your wanted time using the following JS code:

new Date(`${post.data.created_at} GMT+0200`)

In this example, my received dates were in GMT+0200 timezone. Instead of it can be every single timezone. And the returned data will be the date in your timezone. Hope this will help anyone to save time

How to select only 1 row from oracle sql?

This syntax is available in Oracle 12c:

select * from some_table fetch first 1 row only;
select * from some_table fetch first 1 rows only;
select * from some_table fetch first 10 row only;
select * from some_table fetch first 10 rows only;

^^I just wanted to demonstrate that either row or rows (plural) can be used regardless of the plurality of the desired number of rows.)

Usage of sys.stdout.flush() method

As per my understanding sys.stdout.flush() pushes out all the data that has been buffered to that point to a file object. While using stdout, data is stored in buffer memory (for some time or until the memory gets filled) before it gets written to terminal. Using flush() forces to empty the buffer and write to terminal even before buffer has empty space.

How to get primary key of table?

Shortest possible code seems to be something like

// $dblink contain database login details 
// $tblName the current table name 
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
$iColName = $r['Column_name']; 

Can I target all <H> tags with a single selector?

The new :is() CSS pseudo-class can do it in one selector:

:is(h1, h2, h3, h4, h5, h6) {
  color: red;
}

How do I show the schema of a table in a MySQL database?

describe [db_name.]table_name;

for formatted output, or

show create table [db_name.]table_name;

for the SQL statement that can be used to create a table.

Playing mp3 song on python

from win32com.client import Dispatch

wmp = Dispatch('WMPlayer.OCX')

liste = [r"F:\Mp3\rep\6.Evinden Uzakta.mp3",
         r"F:\Mp3\rep\07___SAGOPA_KAJMER___BIR__I.MP3",
         r"F:\Mp3\rep\7.Terzi.mp3",
         r"F:\Mp3\rep\08. Rüya.mp3",
         r"F:\Mp3\rep\8.Battle Edebiyati.mp3",
         r"F:\Mp3\rep\09_AUDIOTRACK_09.MP3",
         r"F:\Mp3\rep\02. Sagopa Kajmer - Uzun Yollara Devam.mp3",
         r"F:\Mp3\rep\2Pac_-_CHANGE.mp3",
         r"F:\Mp3\rep\03. Herkes.mp3",
         r"F:\Mp3\rep\06. Sagopa Kajmer - Istakoz.mp3"]


for x in liste:
    mp3 = wmp.newMedia(x)
    wmp.currentPlaylist.appendItem(mp3)

wmp.controls.play()

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

If you are using Java configuration in a spring-data-jpa project, make sure you are scanning the package that the entity is in. For example, if the entity lived com.foo.myservice.things then the following configuration annotation below would not pick it up.

You could fix it by loosening it up to just com.foo.myservice (of course, keep in mind any other effects of broadening your scope to scan for entities).

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories("com.foo.myservice.repositories")
public class RepositoryConfiguration {
}

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

Check if DataRow exists by column name in c#?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}

How can I make setInterval also work when a tab is inactive in Chrome?

I think that a best understanding about this problem is in this example: http://jsfiddle.net/TAHDb/

I am doing a simple thing here:

Have a interval of 1 sec and each time hide the first span and move it to last, and show the 2nd span.

If you stay on page it works as it is supposed. But if you hide the tab for some seconds, when you get back you will see a weired thing.

Its like all events that didn't ucur during the time you were inactive now will ocur all in 1 time. so for some few seconds you will get like X events. they are so quick that its possible to see all 6 spans at once.

So it seams chrome only delays the events, so when you get back all events will occur but all at once...

A pratical application were this ocur iss for a simple slideshow. Imagine the numbers being Images, and if user stay with tab hidden when he came back he will see all imgs floating, Totally mesed.

To fix this use the stop(true,true) like pimvdb told. THis will clear the event queue.

Characters allowed in GET parameter

Alphanumeric characters and all of

~ - _ . ! * ' ( ) ,

are valid within an URL.

All other characters must be encoded.

Select all text inside EditText when it gets focus

This is works for me:

myEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(myEditText.isFocused()){
                myEditText.requestFocus();
                myEditText.clearFocus();
                myEditText.setSelection(myEditText.getText().length(), 0);
            }else{
                myEditText.requestFocus();
                myEditText.clearFocus();
            }

        }
    });

What does "yield break;" do in C#?

Tells the iterator that it's reached the end.

As an example:

public interface INode
{
    IEnumerable<Node> GetChildren();
}

public class NodeWithTenChildren : INode
{
    private Node[] m_children = new Node[10];

    public IEnumerable<Node> GetChildren()
    {
        for( int n = 0; n < 10; ++n )
        {
            yield return m_children[ n ];
        }
    }
}

public class NodeWithNoChildren : INode
{
    public IEnumerable<Node> GetChildren()
    {
        yield break;
    }
}

Show div #id on click with jQuery

This is simple way to Display Div using:-

$("#musicinfo").show();  //or
$("#musicinfo").css({'display':'block'});  //or
$("#musicinfo").toggle("slow");   //or
$("#musicinfo").fadeToggle();    //or

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

Setting format and value in input type="date"

I think this can help

function myFormatDateFunction(date, format) {
     ...
}

jQuery('input[type="date"]')                                             
    .each(function(){                                                              
        Object.defineProperty(this,'value',{                                         
          get: function() {                                   
            return myFormatDateFunction(this.valueAsDate, 'dd.mm.yyyy');      
          },                                                                         
          configurable: true,                                                        
          enumerable : true                                                          
        });                                                                          
      });                                                                                

Send text to specific contact programmatically (whatsapp)

_x000D_
_x000D_
 public void shareWhatsup(String text) {_x000D_
_x000D_
_x000D_
        String smsNumber = "91+" + "9879098469"; // E164 format without '+' sign_x000D_
_x000D_
        Intent intent = new Intent(Intent.ACTION_VIEW);_x000D_
_x000D_
        try {_x000D_
            String url = "https://api.whatsapp.com/send?phone=" + smsNumber + "&text=" + URLEncoder.encode(text, "UTF-8");_x000D_
            intent.setPackage("com.whatsapp");_x000D_
            intent.setData(Uri.parse(url));_x000D_
        } catch (Exception e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
_x000D_
        //    intent.setAction(Intent.ACTION_SEND);_x000D_
        //   intent.setType("image/jpeg");_x000D_
        //   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUriArray);_x000D_
        startActivity(intent);_x000D_
_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_

Android Studio Stuck at Gradle Download on create new project

What worked for me:

  1. Create a dummy project, when it gets stuck on the Build screen, kill the studio process.
  2. Open the android studio and open the project, the projet will be broken
  3. Create a new project with the dummy project already opened it will create the project without problems
  4. Close the dummy project and have fun

Android - Dynamically Add Views into View

To make @Mark Fisher's answer more clear, the inserted view being inflated should be a xml file under layout folder but without a layout (ViewGroup) like LinearLayout etc. inside. My example:

res/layout/my_view.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/i_am_id"
    android:text="my name"
    android:textSize="17sp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"/>

Then, the insertion point should be a layout like LinearLayout:

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/aaa"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/insert_point"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </LinearLayout>

</RelativeLayout>

Then the code should be

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shopping_cart);

    LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.my_view, null);
    ViewGroup main = (ViewGroup) findViewById(R.id.insert_point);
    main.addView(view, 0);
}

The reason I post this very similar answer is that when I tried to implement Mark's solution, I got stuck on what xml file should I use for insert_point and the child view. I used layout in the child view firstly and it was totally not working, which took me several hours to figure out. So hope my exploration can save others' time.

Laravel: How do I parse this json data in view blade?

If your data is coming from a model you can do:

App\Http\Controller\SomeController

public function index(MyModel $model)
{
    return view('index', [
        'data' => $model->all()->toJson(),
    ]);
}

index.blade.php

@push('footer-scripts')
  <script>
    (function(global){
      var data = {!! $data !!};
      console.log(data);
      // [{..}]
    })(window);
  </script>
@endpush

Deleting Objects in JavaScript

The delete operator deletes only a reference, never an object itself. If it did delete the object itself, other remaining references would be dangling, like a C++ delete. (And accessing one of them would cause a crash. To make them all turn null would mean having extra work when deleting or extra memory for each object.)

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed. If references remain to a large object, this can cause it to be unreclaimed - even if the rest of your program doesn't actually use that object.

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

Use awk to find average of a column

awk 's+=$2{print s/NR}' table | tail -1

I am using tail -1 to print the last line which should have the average number...

Can CSS force a line break after each word in an element?

The answer given by @HursVanBloob works only with fixed width parent container, but fails in case of fluid-width containers.

I tried a lot of properties, but nothing worked as expected. Finally I came to a conclusion that giving word-spacing a very huge value works perfectly fine.

p { word-spacing: 9999999px; }

or, for the modern browsers you can use the CSS vw unit (visual width in % of the screen size).

p { word-spacing: 100vw; }

How to find the highest value of a column in a data frame in R?

max(ozone$Ozone, na.rm = TRUE) should do the trick. Remember to include the na.rm = TRUE or else R will return NA.

-bash: export: `=': not a valid identifier

I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.

Scenario 1: There cannot be spaces beside the = (equals) sign

$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question

$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier

$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier

Scenario 2: Object value assignment should not have spaces besides quotes

$ export TEMP_ENV={ "key" : "json example" } 
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier

Scenario 3: List value assignment should not have spaces between values

$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier

I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

I had this problem and found that removing the following folder helped, even with the non-Express edition.Express:

C:\Users\<user>\Documents\IISExpress

Find document with array that contains a specific value

Though agree with find() is most effective in your usecase. Still there is $match of aggregation framework, to ease the query of a big number of entries and generate a low number of results that hold value to you especially for grouping and creating new files.

  PersonModel.aggregate([
            { 
                 "$match": { 
                     $and : [{ 'favouriteFoods' : { $exists: true, $in: [ 'sushi']}}, ........ ]  }
             },
             { $project : {"_id": 0, "name" : 1} }
            ]);

Using grep and sed to find and replace a string

My use case was I wanted to replace foo:/Drive_Letter with foo:/bar/baz/xyz In my case I was able to do it with the following code. I was in the same directory location where there were bulk of files.

find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'

hope that helped.

How to position a Bootstrap popover?

To bootstrap 3.0.0:

.popover{ right:0!important; }

And modify too

.popover { max-width:WWWpx!important; } 

where WWW is your correct max-width to show your popover content.

Laravel 5 Carbon format datetime

just use

Carbon::createFromFormat('Y-m-d H:i:s', $item['created_at'])->format('M d Y');

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    {
        _datatable.Columns.Add(grdReport.Columns[i].ToString());
    }
    foreach (GridViewRow row in grdReport.Rows)
    {
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
        {
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
        }

        _datatable.Rows.Add(dr);
    }
    ExportDataTableToExcel(_datatable);
}

What is the closest thing Windows has to fork()?

fork() semantics are necessary where the child needs access to the actual memory state of the parent as of the instant fork() is called. I have a piece of software which relies on the implicit mutex of memory copying as of the instant fork() is called, which makes threads impossible to use. (This is emulated on modern *nix platforms via copy-on-write/update-memory-table semantics.)

The closest that exists on Windows as a syscall is CreateProcess. The best that can be done is for the parent to freeze all other threads during the time that it is copying memory over to the new process's memory space, then thaw them. Neither the Cygwin frok [sic] class nor the Scilab code that Eric des Courtis posted does the thread-freezing, that I can see.

Also, you probably shouldn't use the Zw* functions unless you're in kernel mode, you should probably use the Nt* functions instead. There's an extra branch that checks whether you're in kernel mode and, if not, performs all of the bounds checking and parameter verification that Nt* always do. Thus, it's very slightly less efficient to call them from user mode.

sequelize findAll sort order in nodejs

If you want to sort data either in Ascending or Descending order based on particular column, using sequlize js, use the order method of sequlize as follows

// Will order the specified column by descending order
order: sequelize.literal('column_name order')
e.g. order: sequelize.literal('timestamp DESC')

How to set placeholder value using CSS?

From what I understand using,

::-webkit-input-placeholder::beforeor ::-webkit-input-placeholder::after,

to add more placeholder content doesn't work anymore. Think its a new Chrome update.

Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:

<input type="text" value="" id="email1" placeholder="I am on one line.                                              I am on a second line                                                                                     etc etc..." />

Getting the SQL from a Django QuerySet

This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

Calculate average in java

It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.

  • In your case, you want to convert args which is String[] into double or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
  • Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
  • If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.

What's the difference between KeyDown and KeyPress in .NET?

KeyPress is only fired by printable characters and is fired after the KeyDown event. Depending on the typing delay settings there can be multiple KeyDown and KeyPress events but only one KeyUp event.

KeyDown
KeyPress
KeyUp

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

I could also just add that I knew everything about the syntax change between Python2.7 and Python3, and my code was correctly written as print("string") and even print(f"string")...

But after some time of debugging I realized that my bash script was calling python like:

python file_name.py

which had the effect of calling my python script by default using python2.7 which gave the error. So I changed my bash script to:

python3 file_name.py

which of coarse uses python3 to run the script which fixed the error.

Asynchronous method call in Python?

My solution is:

import threading

class TimeoutError(RuntimeError):
    pass

class AsyncCall(object):
    def __init__(self, fnc, callback = None):
        self.Callable = fnc
        self.Callback = callback

    def __call__(self, *args, **kwargs):
        self.Thread = threading.Thread(target = self.run, name = self.Callable.__name__, args = args, kwargs = kwargs)
        self.Thread.start()
        return self

    def wait(self, timeout = None):
        self.Thread.join(timeout)
        if self.Thread.isAlive():
            raise TimeoutError()
        else:
            return self.Result

    def run(self, *args, **kwargs):
        self.Result = self.Callable(*args, **kwargs)
        if self.Callback:
            self.Callback(self.Result)

class AsyncMethod(object):
    def __init__(self, fnc, callback=None):
        self.Callable = fnc
        self.Callback = callback

    def __call__(self, *args, **kwargs):
        return AsyncCall(self.Callable, self.Callback)(*args, **kwargs)

def Async(fnc = None, callback = None):
    if fnc == None:
        def AddAsyncCallback(fnc):
            return AsyncMethod(fnc, callback)
        return AddAsyncCallback
    else:
        return AsyncMethod(fnc, callback)

And works exactly as requested:

@Async
def fnc():
    pass

How to get the Parent's parent directory in Powershell?

You can use

(get-item $scriptPath).Directoryname

to get the string path or if you want the Directory type use:

(get-item $scriptPath).Directory

CSS/HTML: Create a glowing border around an Input Field

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript onclick redirect

Doing this fixed my issue

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value;
        window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
    }
</script>

I changed .value(); to .value; taking out the ()

I did not change anything in my text field or submit button

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

Works like a charm.

How do I use IValidatableObject?

I liked cocogza's answer except that calling base.IsValid resulted in a stack overflow exception as it would re-enter the IsValid method again and again. So I modified it to be for a specific type of validation, in my case it was for an e-mail address.

[AttributeUsage(AttributeTargets.Property)]
class ValidEmailAddressIfTrueAttribute : ValidationAttribute
{
    private readonly string _nameOfBoolProp;

    public ValidEmailAddressIfTrueAttribute(string nameOfBoolProp)
    {
        _nameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            return null;
        }

        var property = validationContext.ObjectType.GetProperty(_nameOfBoolProp);
        if (property == null)
        {
            return new ValidationResult($"{_nameOfBoolProp} not found");
        }

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
        {
            return new ValidationResult($"{_nameOfBoolProp} not boolean");
        }

        if ((bool)boolVal)
        {
            var attribute = new EmailAddressAttribute {ErrorMessage = $"{value} is not a valid e-mail address."};
            return attribute.GetValidationResult(value, validationContext);
        }
        return null;
    }
}

This works much better! It doesn't crash and produces a nice error message. Hope this helps someone!

Entity framework self referencing loop detected

I'm aware that question is quite old, but it's still popular and I can't see any solution for ASP.net Core.

I case of ASP.net Core, you need to add new JsonOutputFormatter in Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });

        //...
    }

After implementing it, JSON serializer will simply ignore loop references. What it means is: it will return null instead of infinitely loading objects referencing each other.

Without above solution using:

var employees = db.Employees.ToList();

Would load Employees and related to them Departments.

After setting ReferenceLoopHandling to Ignore, Departments will be set to null unless you include it in your query:

var employees = db.Employees.Include(e => e.Department);

Also, keep in mind that it will clear all OutputFormatters, if you don't want that you can try removing this line:

options.OutputFormatters.Clear();

But removing it causes again self referencing loop exception in my case for some reason.

How do I spool to a CSV formatted file using SQLPLUS?

I use this command for scripts which extracts data for dimensional tables (DW). So, I use the following syntax:

set colsep '|'
set echo off
set feedback off
set linesize 1000
set pagesize 0
set sqlprompt ''
set trimspool on
set headsep off

spool output.dat

select '|', <table>.*, '|'
  from <table>
where <conditions>

spool off

And works. I don't use sed for format the output file.

How do you check if a variable is an array in JavaScript?

Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).

_.isArray(object) 

Returns true if object is an Array.

How do I match any character across multiple lines in a regular expression?

In many regex dialects, /[\S\s]*<Foobar>/ will do just what you want. Source

Find unused code

It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.

One great tool come to mind:

NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).

Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.

How to reduce the space between <p> tags?

Reduce space between paragraphs. If you are using blogger, you'd go to template, 'customize' then find 'add css' and paste this: p {margin:.7em 0 .7em 0} /*Reduces space between

from full line to approx. 1/2 line */ If you are just tagging your webpage, that's still what you would use, just put it into your css file(s).

I was an sgml template designer in the late 70s/early 80s and all this tagging is just a dtd within sgml (even if they are now trying to say that html5/css3 is 'not', YES IT STILL IS.) :)

You can find all this basic info at w3schools too you know. Really if you are learning how to do layout using tagging or even javascript, etc. you should start with w3schools. Some people say it is 'not always' right, but folks, I've been in IT since 1960 (age 12) and w3schools is best for beginners. Are some things wrong there? Ah, I dunno, I haven't found any mistake, although sometimes if you are a beginner you might need to read two viewpoints to truly grasp the sense of something. But do remember that you are NOT programming when you code a webpage, you are simply doing layout work. (Yell all you want folks, that's the truth of it.)

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

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

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

How to remove the querystring and get only the url?

Try this

$url_with_querystring = 'www.mydomian.com/myurl.html?unwantedthngs';
$url_data = parse_url($url_with_querystring);
$url_without_querystring = str_replace('?'.$url_data['query'], '', $url_with_querystring);

How do I parse JSON with Ruby on Rails?

You can try something like this:

def details_to_json
{
  :id                    => self.id, 
  :credit_period_type    => self.credit_period_type,
  :credit_payment_period => self.credit_payment_period,

 }.to_json
end

Why can't I center with margin: 0 auto?

We can set the width for ul tag then it will align center.

#header ul {
    display: block;
    margin: 0 auto;
    width: 420px;
    max-width: 100%;
}

Check existence of directory and create if doesn't exist

I had an issue with R 2.15.3 whereby while trying to create a tree structure recursively on a shared network drive I would get a permission error.

To get around this oddity I manually create the structure;

mkdirs <- function(fp) {
    if(!file.exists(fp)) {
        mkdirs(dirname(fp))
        dir.create(fp)
    }
} 

mkdirs("H:/foo/bar")

Return multiple values to a method caller

In C# 4, you will be able to use built-in support for tuples to handle this easily.

In the meantime, there are two options.

First, you can use ref or out parameters to assign values to your parameters, which get passed back to the calling routine.

This looks like:

void myFunction(ref int setMe, out int youMustSetMe);

Second, you can wrap up your return values into a structure or class, and pass them back as members of that structure. KeyValuePair works well for 2 - for more than 2 you would need a custom class or struct.

How to add 10 minutes to my (String) time?

I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

HTML list-style-type dash

Let me add my version too, mostly for me to find my own preferred solution again:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
  /*use padding to move list item from left to right*/_x000D_
  padding-left: 1em;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: "–";_x000D_
  position: absolute;_x000D_
  /*change margin to move dash around*/_x000D_
  margin-left: -1em;_x000D_
}
_x000D_
<!-- _x000D_
Just use the following CSS to turn your_x000D_
common disc lists into a list-style-type: 'dash' _x000D_
Give credit and enjoy!_x000D_
-->_x000D_
Some text_x000D_
<ul>_x000D_
  <li>One</li>_x000D_
  <li>Very</li>_x000D_
  <li>Simple Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</li>_x000D_
  <li>Approach!</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

https://codepen.io/burningTyger/pen/dNzgrQ

How to use FormData for AJAX file upload?

$('#form-withdraw').submit(function(event) {

    //prevent the form from submitting by default
    event.preventDefault();



    var formData = new FormData($(this)[0]);

    $.ajax({
        url: 'function/ajax/topup.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          if(returndata == 'success')
          {
            swal({
              title: "Great",
              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
              type: "success",
              showCancelButton: false,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "OK",
              closeOnConfirm: false
            },
            function(){
              window.location.href = '/transaction.php';
            });
          }

          else if(returndata == 'Offline')
          {
              sweetAlert("Offline", "Please use other payment method", "error");
          }
        }
    });



}); 

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

How to use Global Variables in C#?

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

phpmailer - The following SMTP Error: Data not accepted

your server dosen't allow different sender and username you should config: $mail->From like $mail->Username

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

Entity Framework select distinct name

In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT error, the best should be

var results = (
    from ta in DBContext.TestAddresses
    select ta.Name
)
.Distinct()
.OrderBy( x => 1);

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How to delete a selected DataGridViewRow and update a connected database table?

private: System::Void button9_Click(System::Object^  sender, System::EventArgs^  e)
{
    String^ constring = L"datasource=localhost;port=3306;username=root;password=password";
    MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
    conDataBase->Open();
    try 
    {
        if (MessageBox::Show("Sure you wanna delete?", "Warning", MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes)
        {
            for each(DataGridViewCell^ oneCell in dataGridView1->SelectedCells)
            {
                if (oneCell->Selected) {
                    dataGridView1->Rows->RemoveAt(oneCell->RowIndex);
                    MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory='ORG 6400H'");
                    cmdDataBase1->ExecuteNonQuery();
                    //sda->Update(dbdataset);
                }   
            }           
        }
    }
    catch (Exception^ex)
    {
        MessageBox::Show(ex->ToString());
    }
}

How to get the Facebook user id using the access token

Check out this answer, which describes, how to get ID response. First, you need to create method get data:

const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
    const options = {
        host: 'graph.facebook.com',
        port: 443,
        path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
        method: 'GET'
    };

    let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
    const request = https.get(options, (result) => {
        result.setEncoding('utf8');
        result.on('data', (chunk) => {
            buffer += chunk;
        });

        result.on('end', () => {
            callback(buffer);
        });
    });

    request.on('error', (e) => {
        console.log(`error from facebook.getFbData: ${e.message}`)
    });

    request.end();
}

Then simply use your method whenever you want, like this:

getFbData(access_token, '/me?fields=id&', (result) => {
      console.log(result);
});

Reset ID autoincrement ? phpmyadmin

ALTER TABLE `table_name` AUTO_INCREMENT=1

How can I create an MSI setup?

In my opinion you should use Wix#, which nicely hides most of the complexity of building an MSI installation pacakge.

It allows you to perform all possible kinds of customization using a more easier language compared to WiX.

Pandas DataFrame column to list

I'd like to clarify a few things:

  1. As other answers have pointed out, the simplest thing to do is use pandas.Series.tolist(). I'm not sure why the top voted answer leads off with using pandas.Series.values.tolist() since as far as I can tell, it adds syntax/confusion with no added benefit.
  2. tst[lookupValue][['SomeCol']] is a dataframe (as stated in the question), not a series (as stated in a comment to the question). This is because tst[lookupValue] is a dataframe, and slicing it with [['SomeCol']] asks for a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you remove the extra set of brackets, as in tst[lookupValue]['SomeCol'], then you are asking for just that one column rather than a list of columns, and thus you get a series back.
  3. You need a series to use pandas.Series.tolist(), so you should definitely skip the second set of brackets in this case. FYI, if you ever end up with a one-column dataframe that isn't easily avoidable like this, you can use pandas.DataFrame.squeeze() to convert it to a series.
  4. tst[lookupValue]['SomeCol'] is getting a subset of a particular column via chained slicing. It slices once to get a dataframe with only certain rows left, and then it slices again to get a certain column. You can get away with it here since you are just reading, not writing, but the proper way to do it is tst.loc[lookupValue, 'SomeCol'] (which returns a series).
  5. Using the syntax from #4, you could reasonably do everything in one line: ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()

Demo Code:

import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
                   'colB':[4,5,6]})
filter_value = 1

print "df"
print df
print type(df)

rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)

result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)

result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)

result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)

result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)

result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)

ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)

ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)

Result:

df
   colA  colB
0     1     4
1     2     5
2     1     6
<class 'pandas.core.frame.DataFrame'>

df['colA'] == filter_value
0     True
1    False
2     True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>

df[rows_to_keep]['colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df[rows_to_keep][['colB']]
   colB
0     4
2     6
<class 'pandas.core.frame.DataFrame'>

df[rows_to_keep][['colB']].squeeze()
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[df['colA'] == filter_value, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>

df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>

What is the best way to add options to a select from a JavaScript object with jQuery?

  1. $.each is slower than a for loop
  2. Each time, a DOM selection is not the best practice in loop $("#mySelect").append();

So the best solution is the following

If JSON data resp is

[
    {"id":"0001", "name":"Mr. P"},
    {"id":"0003", "name":"Mr. Q"},
    {"id":"0054", "name":"Mr. R"},
    {"id":"0061", "name":"Mr. S"}
]

use it as

var option = "";
for (i=0; i<resp.length; i++) {
    option += "<option value='" + resp[i].id + "'>" + resp[i].name + "</option>";
}
$('#mySelect').html(option);

How to pass data from Javascript to PHP and vice versa?

I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:

My simple client side code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
   <title>Test Page</title>
   <script>
    function passVal(){
        var data = {
            fn: "filename",
            str: "this_is_a_dummy_test_string"
        };

        $.post("test.php", data);
    }
    passVal();
   </script>

</head>
<body>
</body>
</html>

And php code on server side:

<?php 
   $fn  = $_POST['fn'];
   $str = $_POST['str'];
   $file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
   echo fwrite($file,$str);
   fclose($file);
?>

Hope this works for you and future readers!

Plugin with id 'com.google.gms.google-services' not found

Had the same problem.

Fixed by adding the dependency

classpath 'com.google.gms:google-services:3.0.0'

to the root build.gradle.

https://firebase.google.com/docs/android/setup#manually_add_firebase

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

Redirect after Login on WordPress

This should solve your problem. Adapted from an answer found here.

Add the following snippet of code in the functions.php file of your theme:

function admin_default_page() {
  return '/new-dashboard-url';
}

add_filter('login_redirect', 'admin_default_page');

Hive: Convert String to Integer

If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work

    hive> select cast('2147483647' as int);
    OK
    2147483647
    
    hive> select cast('2147483648' as int);
    OK
    NULL
    
    hive> select cast('2147483648' as bigint);
    OK
    2147483648

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

In my own case I have the following error

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='

$this->db->select("users.username as matric_no, CONCAT(users.surname, ' ', users.first_name, ' ', users.last_name) as fullname") ->join('users', 'users.username=classroom_students.matric_no', 'left') ->where('classroom_students.session_id', $session) ->where('classroom_students.level_id', $level) ->where('classroom_students.dept_id', $dept);

After weeks of google searching I noticed that the two fields I am comparing consists of different collation name. The first one i.e username is of utf8_general_ci while the second one is of utf8_unicode_ci so I went back to the structure of the second table and changed the second field (matric_no) to utf8_general_ci and it worked like a charm.

Using colors with printf

You're mixing the parts together instead of separating them cleanly.

printf '\e[1;34m%-6s\e[m' "This is text"

Basically, put the fixed stuff in the format and the variable stuff in the parameters.

gcloud command not found - while installing Google Cloud SDK

The cause of my installation failure:

  • I am running a zsh terminal and the install.sh inserts path.bash.inc into my .bash_profile

fix:

  1. cd [whereever]/google-cloud-sdk && ./install.sh
  2. vi ~/.bash_profile
  3. replace all instances of path.bash.inc with path.zsh.inc

os config:

  • macOS Catalina
  • zsh

ref:

error: use of deleted function

You are using a function, which is marked as deleted.
Eg:

int doSomething( int ) = delete;

The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function.

If you see this error, you should check the function declaration for =delete.

To know more about this new feature introduced in C++0x, check this out.

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

How to exit git log or git diff

Actually, there are three ways to do it, precisely.

Type any of the following 3 commands.

  1. :q
  2. :z or
  3. Ctrl + z

P.S.: Sometimes, for someone, one of these options doesn't seem to work and for others it works.

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had the same problem, changing my gmail password fixed the issue, and also don't forget to enable less secure app on on your gmail account

How do I make a request using HTTP basic authentication with PHP curl?

CURLOPT_USERPWD basically sends the base64 of the user:password string with http header like below:

Authorization: Basic dXNlcjpwYXNzd29yZA==

So apart from the CURLOPT_USERPWD you can also use the HTTP-Request header option as well like below with other headers:

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("user:password") // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
print "Please choose what you'd like to do:"

print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"



#Capture the menu choice.
choice = raw_input()    

if choice == "0":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

Difference between break and continue in PHP?

BREAK:

break ends execution of the current for, foreach, while, do-while or switch structure.

CONTINUE:

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

So depending on your need, you can reset the position currently being executed in your code to a different level of the current nesting.

Also, see here for an artical detailing Break vs Continue with a number of examples

Dynamic SQL results into temp table in SQL Stored procedure

INSERT INTO #TempTable
EXEC(@SelectStatement)

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {  
        if (requestCode == CAMERE_REQUEST && resultCode == RESULT_OK && data != null) 
        {  
           Bitmap photo = (Bitmap) data.getExtras().get("data"); 
           imageView.setImageBitmap(photo);
        } 
}

You can check if the resultCode equals RESULT_OK this will only be the case if a picture is taken and selected and everything worked. This if clause here should check every condition.

AWS : The config profile (MyName) could not be found

Use as follows

[profilename]
region=us-east-1
output=text

Example cmd

aws --profile myname CMD opts

Add Keypair to existing EC2 instance

You can't apply a keypair to a running instance. You can only use the new keypair to launch a new instance.

For recovery, if it's an EBS boot AMI, you can stop it, make a snapshot of the volume. Create a new volume based on it. And be able to use it back to start the old instance, create a new image, or recover data.

Though data at ephemeral storage will be lost.


Due to the popularity of this question and answer, I wanted to capture the information in the link that Rodney posted on his comment.

Credit goes to Eric Hammond for this information.

Fixing Files on the Root EBS Volume of an EC2 Instance

You can examine and edit files on the root EBS volume on an EC2 instance even if you are in what you considered a disastrous situation like:

  • You lost your ssh key or forgot your password
  • You made a mistake editing the /etc/sudoers file and can no longer gain root access with sudo to fix it
  • Your long running instance is hung for some reason, cannot be contacted, and fails to boot properly
  • You need to recover files off of the instance but cannot get to it

On a physical computer sitting at your desk, you could simply boot the system with a CD or USB stick, mount the hard drive, check out and fix the files, then reboot the computer to be back in business.

A remote EC2 instance, however, seems distant and inaccessible when you are in one of these situations. Fortunately, AWS provides us with the power and flexibility to be able to recover a system like this, provided that we are running EBS boot instances and not instance-store.

The approach on EC2 is somewhat similar to the physical solution, but we’re going to move and mount the faulty “hard drive” (root EBS volume) to a different instance, fix it, then move it back.

In some situations, it might simply be easier to start a new EC2 instance and throw away the bad one, but if you really want to fix your files, here is the approach that has worked for many:

Setup

Identify the original instance (A) and volume that contains the broken root EBS volume with the files you want to view and edit.

instance_a=i-XXXXXXXX

volume=$(ec2-describe-instances $instance_a |
  egrep '^BLOCKDEVICE./dev/sda1' | cut -f3)

Identify the second EC2 instance (B) that you will use to fix the files on the original EBS volume. This instance must be running in the same availability zone as instance A so that it can have the EBS volume attached to it. If you don’t have an instance already running, start a temporary one.

instance_b=i-YYYYYYYY

Stop the broken instance A (waiting for it to come to a complete stop), detach the root EBS volume from the instance (waiting for it to be detached), then attach the volume to instance B on an unused device.

ec2-stop-instances $instance_a
ec2-detach-volume $volume
ec2-attach-volume --instance $instance_b --device /dev/sdj $volume

ssh to instance B and mount the volume so that you can access its file system.

ssh ...instance b...

sudo mkdir -p 000 /vol-a
sudo mount /dev/sdj /vol-a

Fix It

At this point your entire root file system from instance A is available for viewing and editing under /vol-a on instance B. For example, you may want to:

  • Put the correct ssh keys in /vol-a/home/ubuntu/.ssh/authorized_keys
  • Edit and fix /vol-a/etc/sudoers
  • Look for error messages in /vol-a/var/log/syslog
  • Copy important files out of /vol-a/…

Note: The uids on the two instances may not be identical, so take care if you are creating, editing, or copying files that belong to non-root users. For example, your mysql user on instance A may have the same UID as your postfix user on instance B which could cause problems if you chown files with one name and then move the volume back to A.

Wrap Up

After you are done and you are happy with the files under /vol-a, unmount the file system (still on instance-B):

sudo umount /vol-a
sudo rmdir /vol-a

Now, back on your system with ec2-api-tools, continue moving the EBS volume back to it’s home on the original instance A and start the instance again:

ec2-detach-volume $volume
ec2-attach-volume --instance $instance_a --device /dev/sda1 $volume
ec2-start-instances $instance_a

Hopefully, you fixed the problem, instance A comes up just fine, and you can accomplish what you originally set out to do. If not, you may need to continue repeating these steps until you have it working.

Note: If you had an Elastic IP address assigned to instance A when you stopped it, you’ll need to reassociate it after starting it up again.

Remember! If your instance B was temporarily started just for this process, don’t forget to terminate it now.

How to SUM and SUBTRACT using SQL?

I'm not sure exactly what you want, but I think it's along the lines of:

SELECT `Item`, `qty`-`BAL_QTY` as `qty` FROM ((SELECT Item, SUM(`QTY`) as qty FROM `master_table` GROUP BY `ITEM`) as A NATURAL JOIN `stock_table`) as B

How to remove a package in sublime text 2

There are several answers, First IF you are using Package Control simply use Package Control's Remove Package command...

Ctrl+Shift+P

Package Control: Remove Package

If you installed the package manually, and are on a Windows machine...have no fear; Just modify the files manually.

First navigate to

C:\users\[Name]\AppData\Roaming\Sublime Text [version]\

There will be 4 directories:

  1. Installed Packages (Holds the Package Control config file, ignore)
  2. Packages (Holds Package source)
  3. Pristine Packages (Holds the versioning info, ignore)
  4. Settings (Sublime Setting Info, ignore)

First open ..\Packages folder and locate the folder named the same as your package; Delete it.

Secondly, open Sublime and navigate to the Preferences > Package Settings > Package Control > Settings-user

Third, locate the line where the package name you want to "uninstall"

{
    "installed_packages":
    [
        "Alignment",
        "All Autocomplete",
        "AngularJS",
        "AutoFileName",
        "BracketHighlighter",
        "Browser Support",
        "Case Conversion",
        "ColorPicker",
        "Emmet",
        "FileDiffs",
        "Format SQL",
        "Git",
        "Github Tools",
        "HTML-CSS-JS Prettify",
        "HTML5",
        "HTMLBeautify",
        "jQuery",
        "JsFormat",
        "JSHint",
        "JsMinifier",
        "LiveReload",
        "LoremIpsum",
        "LoremPixel",
        "Oracle PL SQL",
        "Package Control",
        "Placehold.it Image Tag Generator",
        "Placeholders",
        "Prefixr",
        "Search Stack Overflow",
        "SublimeAStyleFormatter",
        "SublimeCodeIntel",
        "Tag",
        "Theme - Centurion",
        "TortoiseSVN",
        "Zen Tabs"
    ]
}

NOTE Say the package you are removing is "Zen Tabs", you MUST also remove the , after "TortoiseSVN" or it will error.

Thus concludes the easiest way to remove or Install a Sublime Text Package.

How can I get all a form's values that would be submitted without submitting

Depending on the type of input types you're using on your form, you should be able to grab them using standard jQuery expressions.

Example:

// change forms[0] to the form you're trying to collect elements from...  or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);

Check out the documentation for jQuery expressions on their site for more info: http://docs.jquery.com/Core/jQuery#expressioncontext

Convert a Python int into a big-endian string of bytes

def tost(i):
  result = []
  while i:
    result.append(chr(i&0xFF))
    i >>= 8
  result.reverse()
  return ''.join(result)

Android Studio installation on Windows 7 fails, no JDK found

On Windows 10, restarting the installer and running as admin worked for me.

How to get file's last modified date on Windows command line?

Change % to %% for use in batch file, for %~ta syntax enter call /?

for %a in (MyFile.txt) do set FileDate=%~ta

Sample output:

for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM

for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=

Set multiple system properties Java command line

Instead of passing the properties as an argument, you may use a .properties for storing them.

Does Git Add have a verbose switch

For some git-commands you can specify --verbose,

git 'command' --verbose

or

git 'command' -v.

Make sure the switch is after the actual git command. Otherwise - it won't work!

Also useful:

git 'command' --dry-run 

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

What is base 64 encoding used for?

“Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport”(Wiki, 2017)

Example could be the following: you have a web service that accept only ASCII chars. You want to save and then transfer user’s data to some other location (API) but recipient want receive untouched data. Base64 is for that. . . The only downside is that base64 encoding will require around 33% more space than regular strings.

Another Example:: uenc = url encoded = aHR0cDovL2xvYy5tYWdlbnRvLmNvbS9hc2ljcy1tZW4tcy1nZWwta2F5YW5vLXhpaS5odG1s = http://loc.querytip.com/asics-men-s-gel-kayano-xii.html.

As you can see we can’t put char “/” in URL if we want to send last visited URL as parameter because we would break attribute/value rule for “MOD rewrite” – GET parameter.

A full example would be: “http://loc.querytip.com/checkout/cart/add/uenc/http://loc.magento.com/asics-men-s-gel-kayano-xii.html/product/93/

Oracle SQL Developer - tables cannot be seen

grant select on sys.external_tab$ to [myUser]; worked for me. thanx Codo

Check array position for null/empty

You can use boost::optional (or std::optional for newer versions), which was developed in particular for decision of your problem:

boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
   if(y[i]) { //check for null
      p[i].SetPoint(Recto.Height()-x,*y[i]);
      ....
   }
}

P.S. Do not use C-type array -> use std::array or std::vector:

std::array<int, 50> y;   //not int y[50] !!!

How can I generate Javadoc comments in Eclipse?

For me the /**<NEWLINE> or Shift-Alt-J (or ?-?-J on a Mac) approach works best.

I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.

IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.

How to drop all tables from a database with one SQL query?

Not quite 1 query, still quite short and sweet:

-- Disable all referential integrity constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO

-- Drop all tables
EXEC sp_msforeachtable 'DROP TABLE ?'
GO

Spring Boot - How to get the running port

Please make sure you have imported the correct package

import org.springframework.core.env.Environment;

and then use the Environment object

@Autowired
private Environment env;    // Environment Object containts the port number

 @GetMapping("/status")
  public String status()
    {
   return "it is runing on"+(env.getProperty("local.server.port"));
    }

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I used this tutorial to create my maven web project http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and eclipse did not create src/main/java folder for me. When i tired to create the source folder src/main/java eclipse did not let me. So i created the folder outside eclipse in the project directly and then src/main/java appeared in eclipse.

%matplotlib line magic causes SyntaxError in Python script

There are several reasons as to why this wouldn't work.

It is possible that matplotlib is not properly installed. have you tried running:

conda install matplotlib

If that doesn't work, look at your %PATH% environment variable, does it contain your libraries and python paths?

Similar problem on github anaconda

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Apache Commons Lang (probably useful enough to be on the classpath of any non-trivial project) has StringUtils.repeat():

String filled = StringUtils.repeat("*", 10);

Easy!

Getting JSONObject from JSONArray

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x

With Bootstrap 4 (and Font Awesome), we still can use the input-group wrapper around our form-control element, and now we can use an input-group-append (or input-group-prepend) wrapper with an input-group-text to get the job done:

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
  <div class="input-group-append">
    <span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
  </div>
</div>

It will look something like this (thanks to KyleMit for the screenshot):

enter image description here

Learn more by visiting the Input group documentation.

GDB: Listing all mapped memory regions for a crashed process

If you have the program and the core file, you can do the following steps.

1) Run the gdb on the program along with core file

 $gdb ./test core

2) type info files and see what different segments are there in the core file.

    (gdb)info files

A sample output:

    (gdb)info files 

    Symbols from "/home/emntech/debugging/test".
    Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
  0x0055f000 - 0x0055f000 is load1
  0x0057b000 - 0x0057c000 is load2
  0x0057c000 - 0x0057d000 is load3
  0x00746000 - 0x00747000 is load4
  0x00c86000 - 0x00c86000 is load5
  0x00de0000 - 0x00de0000 is load6
  0x00de1000 - 0x00de3000 is load7
  0x00de3000 - 0x00de4000 is load8
  0x00de4000 - 0x00de7000 is load9
  0x08048000 - 0x08048000 is load10
  0x08049000 - 0x0804a000 is load11
  0x0804a000 - 0x0804b000 is load12
  0xb77b9000 - 0xb77ba000 is load13
  0xb77cc000 - 0xb77ce000 is load14
  0xbf91d000 - 0xbf93f000 is load15

In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.

3) Search for a pattern in the segment.

(gdb) find /w 0x08049000 0x0804a000 0x8048034
 0x804903c
 0x8049040
 2 patterns found

If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.

 http://emntech.com/programs/printseg.c

How can I get a process handle by its name in C++?

The following code shows how you can use toolhelp and OpenProcess to get a handle to the process. Error handling removed for brevity.

HANDLE GetProcessByName(PCSTR name)
{
    DWORD pid = 0;

    // Create toolhelp snapshot.
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

    // Walkthrough all processes.
    if (Process32First(snapshot, &process))
    {
        do
        {
            // Compare process.szExeFile based on format of name, i.e., trim file path
            // trim .exe if necessary, etc.
            if (string(process.szExeFile) == string(name))
            {
               pid = process.th32ProcessID;
               break;
            }
        } while (Process32Next(snapshot, &process));
    }

    CloseHandle(snapshot);

    if (pid != 0)
    {
         return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    }

    // Not found


       return NULL;
}

Instantiating a generic class in Java

I really need to instantiate a T in Foo using a parameter-less constructor

Simple answer is "you cant do that" java uses type erasure to implment generics which would prevent you from doing this.

How can one work around Java's limitation?

One way (there could be others) is to pass the object that you would pass the instance of T to the constructor of Foo<T>. Or you could have a method setBar(T theInstanceofT); to get your T instead of instantiating in the class it self.

case statement in SQL, how to return multiple variables?

A CASE statement can return only one value.

You may be able to turn this into a subquery and then JOIN it to whatever other relations you're working with. For example (using SQL Server 2K5+ CTEs):

WITH C1 AS (
  SELECT a1 AS value1, b1 AS value2
  FROM table
  WHERE condition1
), C2 AS (
  SELECT a2 AS value1, b2 AS value2
  FROM table
  WHERE condition2
), C3 AS (
  SELECT a3 AS value1, b3 AS value2
  FROM table
  WHERE condition3
)
SELECT value1, value2
FROM -- some table, joining C1, C2, C3 CTEs to get the cased values
;

How to embed a PDF?

FlexPaper is probably still the best viewer out there to be used for this kind of stuff. It has a traditional viewer and a more turn page / flip book style viewer both in flash and html5

http://flexpaper.devaldi.com

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

How to vertically center a <span> inside a div?

At your parent DIV add

display:table;

and at your child element add

 display:table-cell;
 vertical-align:middle;

How to start MySQL server on windows xp

Type

C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console

to start the sql server and then test the client connection.

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How to stop C# console applications from closing automatically?

Ctrl + F5 is better, because you don't need additional lines. And you can, in the end, hit enter and exit running mode.

But, when you start a program with F5 and put a break-point, you can debug your application and that gives you other advantages.

How to skip the OPTIONS preflight request?

I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.

express.use('*',(req,res,next) =>{
      if (req.method == "OPTIONS") {
        res.status(200);
        res.send();
      }else{
        next();
      }
    });

SQL Query with Join, Count and Where

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name

How to write a caption under an image?

<div style="margin: 0 auto; text-align: center; overflow: hidden;">
  <div style="float: left;">
    <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
    caption 1
  </div>
 <div style="float: left;">
   <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
   caption 2                      
 </div>
</div>

How to add MVC5 to Visual Studio 2013?

Go File -> New Project.

Select Web under Visual C#.

Select ASP.NET Web Application

select mvc

when solution is created, you will find resources getting added in solution in status bar of vs 2013.

Check property of Dll file --> system.web.mvc, it shows latest version (5.2.2.0)

but depending on your OS runtime version will be decided.

How to set specific Java version to Maven

One simple solution to the problem -

JAVA_HOME=/usr/lib/jvm/java-6-sun/ mvn clean install

On Mac, it would look something like -

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home/ mvn clean install

PS: One special case that i found is the above given command does not work on 'fish' shell. I also had bash shell available and it worked fine there. just use command 'bash' to switch to bash shell.

Notepad++ cached files location

I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.

C:\Users\USER\AppData\Roaming\Notepad++\backup

or

%AppData%\Notepad++\backup

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

You don't need to call $.toJSON and add traditional = true

data: { sendInfo: array },
traditional: true

would do.

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>