Programs & Examples On #Injectable

TS1086: An accessor cannot be declared in ambient context

I got the same issue when adding @angular/flex-layout to my Angular 8 project now with

`npm install @angular/flex-layout --save`.

This since now that command installed the major 9th version of the flex-layout package. Instead of upgrading everything else to the last version, I solved it by installing the last 8th major version of the package instead.

 npm install @angular/[email protected] --save

Angular 6: How to set response type as text while making http call

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

Angular - "has no exported member 'Observable'"

You are using RxJS 6. Just replace

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

by

import { Observable, of } from 'rxjs';

No provider for Http StaticInjectorError

I am on an angular project that (unfortunately) uses source code inclusion via tsconfig.json to connect different collections of code. I came across a similar StaticInjector error for a service (e.g.RestService in the top example) and I was able to fix it by listing the service dependencies in the deps array when providing the affected service in the module, for example:

import { HttpClient } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RestService } from 'mylib/src/rest/rest.service';
...
@NgModule({
  imports: [
    ...
    HttpModule,
    ...
  ],
  providers: [
    {
      provide: RestService,
      useClass: RestService,
      deps: [HttpClient] /* the injected services in the constructor for RestService */
    },
  ]
  ...

Angular 5 Service to read local .json file

Using Typescript 3.6.3, and Angular 6, none of these solutions worked for me.

What did work was to follow the tutorial here which says you need to add a small file called njson-typings.d.ts to your project, containing this:

declare module "*.json" {
  const value: any;
  export default value;
}

Once this was done, I could simply import my hardcoded json data:

import employeeData from '../../assets/employees.json';

and use it in my component:

export class FetchDataComponent implements OnInit {
  public employees: Employee[];

  constructor() {
    //  Load the data from a hardcoded .json file
    this.employees = employeeData;
    . . . .
  }

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Catching errors in Angular HttpClient

You have some options, depending on your needs. If you want to handle errors on a per-request basis, add a catch to your request. If you want to add a global solution, use HttpInterceptor.

Open here the working demo plunker for the solutions below.

tl;dr

In the simplest case, you'll just need to add a .catch() or a .subscribe(), like:

import 'rxjs/add/operator/catch'; // don't forget this, or you'll get a runtime error
this.httpClient
      .get("data-url")
      .catch((err: HttpErrorResponse) => {
        // simple logging, but you can do a lot more, see below
        console.error('An error occurred:', err.error);
      });

// or
this.httpClient
      .get("data-url")
      .subscribe(
        data => console.log('success', data),
        error => console.log('oops', error)
      );

But there are more details to this, see below.


Method (local) solution: log error and return fallback response

If you need to handle errors in only one place, you can use catch and return a default value (or empty response) instead of failing completely. You also don't need the .map just to cast, you can use a generic function. Source: Angular.io - Getting Error Details.

So, a generic .get() method, would be like:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class DataService {
    baseUrl = 'http://localhost';
    constructor(private httpClient: HttpClient) { }

    // notice the <T>, making the method generic
    get<T>(url, params): Observable<T> {
      return this.httpClient
          .get<T>(this.baseUrl + url, {params})
          .retry(3) // optionally add the retry
          .catch((err: HttpErrorResponse) => {

            if (err.error instanceof Error) {
              // A client-side or network error occurred. Handle it accordingly.
              console.error('An error occurred:', err.error.message);
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
            }

            // ...optionally return a default fallback value so app can continue (pick one)
            // which could be a default value
            // return Observable.of<any>({my: "default value..."});
            // or simply an empty observable
            return Observable.empty<T>();
          });
     }
}

Handling the error will allow you app to continue even when the service at the URL is in bad condition.

This per-request solution is good mostly when you want to return a specific default response to each method. But if you only care about error displaying (or have a global default response), the better solution is to use an interceptor, as described below.

Run the working demo plunker here.


Advanced usage: Intercepting all requests or responses

Once again, Angular.io guide shows:

A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

Which, of course, can be used to handle errors in a very simple way (demo plunker here):

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
         HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .catch((err: HttpErrorResponse) => {

        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
        }

        // ...optionally return a default fallback value so app can continue (pick one)
        // which could be a default value (which has to be a HttpResponse here)
        // return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));
        // or simply an empty observable
        return Observable.empty<HttpEvent<any>>();
      });
  }
}

Providing your interceptor: Simply declaring the HttpErrorInterceptor above doesn't cause your app to use it. You need to wire it up in your app module by providing it as an interceptor, as follows:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './path/http-error.interceptor';

@NgModule({
  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true,
  }],
  ...
})
export class AppModule {}

Note: If you have both an error interceptor and some local error handling, naturally, it is likely that no local error handling will ever be triggered, since the error will always be handled by the interceptor before it reaches the local error handling.

Run the working demo plunker here.

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

Cannot find the '@angular/common/http' module

Important: HttpClientModule is for Angular 4.3.0 and above. Check @Maximus' comments and @Pengyy's answer for more info.


Original answer:

You need to inject HttpClient in your component/service not the module. If you import HttpClientModule in your @NgModule

// app.module.ts:
 
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
 
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
 
@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

So change

constructor(private httpClient: HttpModule) {}

to

constructor(private httpClient: HttpClient) {}

as it's been written in the documentation


However, since you imported the HttpModule

you need to inject constructor(private httpClient: Http) as @Maximus stated in the comments and @Pengyy in this answer.

And for more info on differences between HttpModule and HttpClientModule, check this answer

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

async is used for binding to Observables and Promises, but it seems like you're binding to a regular object. You can just remove both async keywords and it should probably work.

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

App.settings - the Angular way?

It's not advisable to use the environment.*.ts files for your API URL configuration. It seems like you should because this mentions the word "environment".

Using this is actually compile-time configuration. If you want to change the API URL, you will need to re-build. That's something you don't want to have to do ... just ask your friendly QA department :)

What you need is runtime configuration, i.e. the app loads its configuration when it starts up.

Some other answers touch on this, but the difference is that the configuration needs to be loaded as soon as the app starts, so that it can be used by a normal service whenever it needs it.

To implement runtime configuration:

  1. Add a JSON config file to the /src/assets/ folder (so that is copied on build)
  2. Create an AppConfigService to load and distribute the config
  3. Load the configuration using an APP_INITIALIZER

1. Add Config file to /src/assets

You could add it to another folder, but you'd need to tell the CLI that it is an asset in the angular.json. Start off using the assets folder:

{
  "apiBaseUrl": "https://development.local/apiUrl"
}

2. Create AppConfigService

This is the service which will be injected whenever you need the config value:

@Injectable({
  providedIn: 'root'
})
export class AppConfigService {

  private appConfig: any;

  constructor(private http: HttpClient) { }

  loadAppConfig() {
    return this.http.get('/assets/config.json')
      .toPromise()
      .then(data => {
        this.appConfig = data;
      });
  }

  // This is an example property ... you can make it however you want.
  get apiBaseUrl() {

    if (!this.appConfig) {
      throw Error('Config file not loaded!');
    }

    return this.appConfig.apiBaseUrl;
  }
}

3. Load the configuration using an APP_INITIALIZER

To allow the AppConfigService to be injected safely, with config fully loaded, we need to load the config at app startup time. Importantly, the initialisation factory function needs to return a Promise so that Angular knows to wait until it finishes resolving before finishing startup:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      multi: true,
      deps: [AppConfigService],
      useFactory: (appConfigService: AppConfigService) => {
        return () => {
          //Make sure to return a promise!
          return appConfigService.loadAppConfig();
        };
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now you can inject it wherever you need to and all the config will be ready to read:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  apiBaseUrl: string;

  constructor(private appConfigService: AppConfigService) {}

  ngOnInit(): void {
    this.apiBaseUrl = this.appConfigService.apiBaseUrl;
  }

}

I can't say it strongly enough, configuring your API urls as compile-time configuration is an anti-pattern. Use runtime configuration.

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

How to convert an object to JSON correctly in Angular 2 with TypeScript

You'll have to parse again if you want it in actual JSON:

JSON.parse(JSON.stringify(object))

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

For me, it was because I had an empty line between my @Component decorator and my Component class. This caused the decorator not to get applied to the class.

Angular 2 TypeScript how to find element in Array

You could combine .find with arrow functions and destructuring. Take this example from MDN.

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

Using an array from Observable Object with ngFor and Async Pipe Angular 2

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

How to get current value of RxJS Subject or Observable?

I encountered the same problem in child components where initially it would have to have the current value of the Subject, then subscribe to the Subject to listen to changes. I just maintain the current value in the Service so it is available for components to access, e.g. :

import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class SessionStorage extends Storage {

  isLoggedIn: boolean;

  private _isLoggedInSource = new Subject<boolean>();
  isLoggedIn = this._isLoggedInSource.asObservable();
  constructor() {
    super('session');
    this.currIsLoggedIn = false;
  }
  setIsLoggedIn(value: boolean) {
    this.setItem('_isLoggedIn', value, () => {
      this._isLoggedInSource.next(value);
    });
    this.isLoggedIn = value;
  }
}

A component that needs the current value could just then access it from the service, i.e,:

sessionStorage.isLoggedIn

Not sure if this is the right practice :)

How to get data from observable in angular2

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

Dynamic tabs with user-click chosen components

there is component ready to use (rc5 compatible) ng2-steps which uses Compiler to inject component to step container and service for wiring everything together (data sync)

    import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';

import { StepsService } from './ng2-steps';

@Directive({
  selector:'[ng2-step]'
})
export class StepDirective implements OnInit{

  @Input('content') content:any;
  @Input('index') index:string;
  public instance;

  constructor(
    private compiler:Compiler,
    private viewContainerRef:ViewContainerRef,
    private sds:StepsService
  ){}

  ngOnInit(){
    //Magic!
    this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
      const injector = this.viewContainerRef.injector;
      this.viewContainerRef.createComponent(cmpFactory, 0,  injector);
    });
  }

}

No 'Access-Control-Allow-Origin' header in Angular 2 app

If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request

 Access-Control-Allow-Origin :  *

I add two images for helping your insert. The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).

First image

The second image shows the insert the *. The value * permits to accept all the request from different hosts.

Second image

After this work my Angular application removed this annoying error in my console.

error inside console

A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

How to catch exception correctly from http.request()?

in the latest version of angular4 use

import { Observable } from 'rxjs/Rx'

it will import all the required things.

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:
    parentComponentInjectionObject.thePropertyYouWantToAccess;
}

ngOnInit not being called when Injectable class is Instantiated

Adding to answer by @Sasxa,

In Injectables you can use class normally that is putting initial code in constructor instead of using ngOnInit(), it works fine.

Angular 2 @ViewChild annotation returns undefined

In my case, I had an input variable setter using the ViewChild, and the ViewChild was inside of an *ngIf directive, so the setter was trying to access it before the *ngIf rendered (it would work fine without the *ngIf, but would not work if it was always set to true with *ngIf="true").

To solve, I used Rxjs to make sure any reference to the ViewChild waited until the view was initiated. First, create a Subject that completes when after view init.

export class MyComponent implements AfterViewInit {
  private _viewInitWaiter$ = new Subject();

  ngAfterViewInit(): void {
    this._viewInitWaiter$.complete();
  }
}

Then, create a function that takes and executes a lambda after the subject completes.

private _executeAfterViewInit(func: () => any): any {
  this._viewInitWaiter$.subscribe(null, null, () => {
    return func();
  })
}

Finally, make sure references to the ViewChild use this function.

@Input()
set myInput(val: any) {
    this._executeAfterViewInit(() => {
        const viewChildProperty = this.viewChild.someProperty;
        ...
    });
}

@ViewChild('viewChildRefName', {read: MyViewChildComponent}) viewChild: MyViewChildComponent;

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

From rxjs 5.5 onwards, you can use the pipeable operators

import { map } from 'rxjs/operators';

What is wrong with the import 'rxjs/add/operator/map';

When we use this approach map operator will be patched to observable.prototype and becomes a part of this object.

If later on, you decide to remove map operator from the code that handles the observable stream but fail to remove the corresponding import statement, the code that implements map remains a part of the Observable.prototype.

When the bundlers tries to eliminate the unused code (a.k.a. tree shaking), they may decide to keep the code of the map operator in the Observable even though it’s not being used in the application.

Solution - Pipeable operators

Pipeable operators are pure functions and do not patch the Observable. You can import operators using the ES6 import syntax import { map } from "rxjs/operators" and then wrap them into a function pipe() that takes a variable number of parameters, i.e. chainable operators.

Something like this:

getHalls() {
    return this.http.get(HallService.PATH + 'hall.json')
    .pipe(
        map((res: Response) => res.json())
    );
}

Angular EXCEPTION: No provider for Http

All you need to do is to include the following libraries in tour app.module.ts and also include it in your imports:

import { HttpModule } from '@angular/http';

@NgModule({
  imports:    [ HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Angular no provider for NameService

The error No provider for NameService is a common issue that many Angular2 beginners face.

Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:

Solution:

@NgModule({
    imports: [...],
    providers: [CustomServiceName]
})

What is javax.inject.Named annotation supposed to be used for?

The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

If you're using a database-first approach:

Before uninstalling / reinstalling Entity Framework, first try simply adding another table / stored procedure to your model (assuming there are any currently unmapped). That fixed the issue for me. Of course if you don't need the resource mapped then just delete it from the model afterwards. But it looks like a force-regeneration of the edmx did the trick.

how to configure apache server to talk to HTTPS backend server?

Your server tells you exactly what you need : [Hint: SSLProxyEngine]

You need to add that directive to your VirtualHost before the Proxy directives :

SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/

See the doc for more detail.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Required attribute HTML5

Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute

Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.

What is :: (double colon) in Python when subscripting sequences?

Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3] is every third element of the sequence.

What is Android keystore file, and what is it used for?

The whole idea of a keytool is to sign your apk with a unique identifier indicating the source of that apk. A keystore file (from what I understand) is used for debuging so your apk has the functionality of a keytool without signing your apk for production. So yes, for debugging purposes you should be able to sign multiple apk's with a single keystore. But understand that, upon pushing to production you'll need unique keytools as identifiers for each apk you create.

How to tell a Mockito mock object to return something different the next time it is called?

For Anyone using spy() and the doReturn() instead of the when() method:

what you need to return different object on different calls is this:

doReturn(obj1).doReturn(obj2).when(this.spyFoo).someMethod();

.

For classic mocks:

when(this.mockFoo.someMethod()).thenReturn(obj1, obj2);

or with an exception being thrown:

when(mockFoo.someMethod())
        .thenReturn(obj1)
        .thenThrow(new IllegalArgumentException())
        .thenReturn(obj2, obj3);

Get dates from a week number in T-SQL

I just incorporated the SELECT with a CASE statement (For my situation Monday marked the first day of the week, and didn't want to deal with the SET DATEFIRST command:

CASE DATEPART(dw,<YourDateTimeField>)
   WHEN 1 THEN CONVERT(char(10), DATEADD(DD, -6, <YourDateTimeField>),126) +  ' to ' + CONVERT(char(10), <YourDateTimeField>,126)
   WHEN 2 THEN CONVERT(char(10), <YourDateTimeField>,126) +  ' to ' + CONVERT(char(10), DATEADD(DD, 6, <YourDateTimeField>),126)
   WHEN 3 THEN CONVERT(char(10), DATEADD(DD, -1, <YourDateTimeField>),126) +  ' to ' + CONVERT(char(10), DATEADD(DD, 5, <YourDateTimeField>),126)
   WHEN 4 THEN CONVERT(char(10), DATEADD(DD, -2, <YourDateTimeField>),126) +  ' to ' + CONVERT(char(10), DATEADD(DD, 4, <YourDateTimeField>),126)
   WHEN 5 THEN CONVERT(char(10), DATEADD(DD, -3, <YourDateTimeField>),126) +  ' to ' + CONVERT(char(10), DATEADD(DD, 3, <YourDateTimeField>),126)
   WHEN 6 THEN CONVERT(char(10), DATEADD(DD, -4, <YourDateTimeField>),126) +  ' to ' + CONVERT(char(10), DATEADD(DD, 2, <YourDateTimeField>),126)
   WHEN 7 THEN CONVERT(char(10), DATEADD(DD, -5, <YourDateTimeField>),126) +  ' to ' + CONVERT(char(10), DATEADD(DD, 1, <YourDateTimeField>),126)
   ELSE 'UNK'
END AS Week_Range

Is it possible to set an object to null?

An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.

Example of what you can't do which you are asking:

Cat c;
c = NULL;//Compiling error

Example of what you can do:

Cat c;
//Set p to hold the memory address of the object c
Cat *p = &c;
//Set p to hold NULL
p = NULL;

What is the documents directory (NSDocumentDirectory)?

Swift 3 and 4 as global var:

var documentsDirectory: URL {
    return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}

As FileManager extension:

extension FileManager {
    static var documentsDirectory: URL {
        return `default`.urls(for: .documentDirectory, in: .userDomainMask).last!
    }

    var documentsDirectory: URL {
        return urls(for: .documentDirectory, in: .userDomainMask).last!
    }
}

google chrome extension :: console.log() from background page?

Any extension page (except content scripts) has direct access to the background page via chrome.extension.getBackgroundPage().

That means, within the popup page, you can just do:

chrome.extension.getBackgroundPage().console.log('foo');

To make it easier to use:

var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');

Now if you want to do the same within content scripts you have to use Message Passing to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the Message Passing page for you to check out.

Hope that clears everything.

What are enums and why are they useful?

There are many answers here, just want to point two specific ones:

1) Using as constants in Switch-case statement. Switch case won't allow you to use String objects for case. Enums come in handy. More: http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/

2) Implementing Singleton Design Pattern - Enum again, comes to rescue. Usage, here: What is the best approach for using an Enum as a singleton in Java?

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

_x000D_
_x000D_
function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
_x000D_
_x000D_

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

Change bootstrap navbar background color and font color

I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #000; /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
        a:hover, .navbar-default .navbar-nav > .active > a:focus {
    color: white; /*BACKGROUND color for active*/
    background-color: #030033;
}

.navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
    color: #262626;
    text-decoration: none;
    background-color: #66CCFF; /*change color of links in drop down here*/
}

.nav > li > a:hover,
.nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
}

.navbar-default .navbar-nav > li > a {
    color: white; /*Change active text color here*/
}

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

Check the site's Application Pool in IIS / Application Pools / YourPool / Advanced Settings :

  • Advanced / Enable 32-Bit Applications: True

There's some anecdotal evidence to suggest you do this too:

  • Managed Pipeline Mode : Classic

Another Repeated column in mapping for entity error

The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:

@Column(nullable=false)
private Long customerId;

and also:

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;

(and the same goes for productId/product).

You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId field, it's useless. And do the same for productId. If you want the customer ID of a sale, you just need to do this:

sale.getCustomer().getId()

How to Change Margin of TextView

TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);     
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);

I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.

Error: 'int' object is not subscriptable - Python

name1 = input("What's your name? ")
age1 = int(input ("how old are you? "))
twentyone = str(21 - int(age1))

if age1<21:
    print ("Hi, " + name1+ " you will be 21 in: " + twentyone + " years.")

else:
    print("You are over the age of 21")

Convert a number into a Roman Numeral in javaScript

Here's my solution:

var roman = "MX";

function solution(roman) {
  var val = 0;
  for (let i = 0; i < roman.length; i++) {
    if (roman.charAt(i) == 'I') {
      if (roman.charAt(i + 1) == 'V') {
        val += 4;   // IV
      } else if (roman.charAt(i + 1) == 'X') {
        val += 9;   // IX
      } else {
        val += 1;   // I
      }
    } else if (roman.charAt(i) == 'V') {
      if (roman.charAt(i - 1) == 'I') {
        val = val;
      } else {
        val += 5;   // V
      }
    } else if (roman.charAt(i) == 'X') {
      if (roman.charAt(i - 1) == 'I') {   // Check if there is I before X
        val = val;
      }else if (roman.charAt(i + 1) == 'L') {
        val += 40;  // XL
      } else if (roman.charAt(i + 1) == 'C') {
        val += 90;  // XC
      } else {
        val += 10;  // X
      }
    } else if (roman.charAt(i) == 'L') {
      if (roman.charAt(i - 1) == 'X') {   // Check if there is X before L
        val = val;
      } else {
        val += 50;  // L
      }
    } else if (roman.charAt(i) == 'C') {
      if (roman.charAt(i - 1) == 'X') {
        val = val;  // XC
      }else if (roman.charAt(i + 1) == 'D') {
        val += 400;  // CD
      } else if (roman.charAt(i + 1) == 'M') {
        val += 900;  // CM
      } else {
        val += 100;  // C
      }
    } else if (roman.charAt(i) == 'D') {
      if (roman.charAt(i - 1) == 'C') {
        val = val;  // CD
      } else {
        val += 500; // D
      }
    } else if (roman.charAt(i) == 'M') {
      if (roman.charAt(i - 1) == 'C') {
        val = val;  // CM
      } else {
        val += 1000; // M
      }
    }
  }
  return val;
}
console.log(solution(roman));  // The answer is: 1010

Javascript Image Resize

okay it solved, here is my final code

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}

Thanks guys

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

Unable to find velocity template resources

The following code helped me resolve the issue. The path to the template needs to be provided as part of file.resource.loader path. By default it comes as "." . So setting the property explicitly will be required.

Print getClass().getClassLoader().getResource("resources") or getClass().getClassLoader().getResource("") to see where your template comes and based on that set it in the velocity template engine.

URL url = getClass().getClassLoader().getResource("resources");
//URL url = getClass().getClassLoader().getResource("");
File folder= new File(url.getFile());   
VelocityEngine ve = new VelocityEngine();
       
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, folder.getAbsolutePath());
ve.init();

Template template = ve.getTemplate( "MyTemplate.vm" );

Swift how to sort array of custom objects by property value

Swift 4.0, 4.1 & 4.2 First, I created mutable array of type imageFile() as shown below

var arr = [imageFile]()

Create mutable object image of type imageFile() and assign value to properties as shown below

   var image = imageFile()
   image.fileId = 14
   image.fileName = "A"

Now, append this object to array arr

    arr.append(image)

Now, assign the different properties to same mutable object i.e image

   image = imageFile()
   image.fileId = 13
   image.fileName = "B"

Now, again append image object to array arr

    arr.append(image)

Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order

 arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
 print("sorted array is",arr[0].fileId)// sorted array is 13
 print("sorted array is",arr[1].fileId)//sorted array is 14

Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order

 arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
 print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
 print("Unsorted array is",arr[1].fileId)// Unsorted array is 13

In Swift 4.1. & 4.2 For sorted order use

let sortedArr = arr.sorted { (id1, id2) -> Bool in
  return id1.fileId < id2.fileId // Use > for Descending order
}

How to open a specific port such as 9090 in Google Compute Engine

You need to:

  1. Go to cloud.google.com

  2. Go to my Console

  3. Choose your Project

  4. Choose Networking > VPC network

  5. Choose "Firewalls rules"

  6. Choose "Create Firewall Rule"

  7. To apply the rule to select VM instances, select Targets > "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like. Then, make sure the instances have the network tag applied.

  8. To allow incoming TCP connections to port 9090, in "Protocols and Ports" enter tcp:9090

  9. Click Create

I hope this helps you.

Update Please refer to docs to customize your rules.

jQuery: print_r() display equivalent?

console.log is what I most often use when debugging.

I was able to find this jQuery extension though.

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

How do you run a .exe with parameters using vba's shell()?

The below code will help you to auto open the .exe file from excel...

Sub Auto_Open()


    Dim x As Variant
    Dim Path As String

    ' Set the Path variable equal to the path of your program's installation
    Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
    x = Shell(Path, vbNormalFocus)

End Sub

Tar a directory, but don't store full absolute paths in the archive

One minor detail:

tar -cjf site1.tar.bz2 -C /var/www/site1 .

adds the files as

tar -tf site1.tar.bz2
./style.css
./index.html
./page2.html
./page3.html
./images/img1.png
./images/img2.png
./subdir/index.html

If you really want

tar -tf site1.tar.bz2
style.css
index.html
page2.html
page3.html
images/img1.png
images/img2.png
subdir/index.html

You should either cd into the directory first or run

tar -cjf site1.tar.bz2 -C /var/www/site1 $(ls /var/www/site1)

How to round double to nearest whole number and then convert to a float?

Here is a quick example:

public class One {

    /**
     * @param args
     */
    public static void main(String[] args) {

        double a = 4.56777;
        System.out.println( new Float( Math.round(a)) );

    }

}

the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double values and provides whole long values

Regards

sending mail from Batch file

There are multiple methods for handling this problem.

My advice is to use the powerful Windows freeware console application SendEmail.

sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

SQL Sum Multiple rows into one

If you don't want to group your result, use a window function.

You didn't state your DBMS, but this is ANSI SQL:

SELECT AccountNumber, 
       Bill, 
       BillDate, 
       SUM(Bill) over (partition by accountNumber) as account_total
FROM Table1
order by AccountNumber, BillDate;

Here is an SQLFiddle: http://sqlfiddle.com/#!15/2c35e/1

You can even add a running sum, by adding:

sum(bill) over (partition by account_number order by bill_date) as sum_to_date

which will give you the total up to the current's row date.

How to properly ignore exceptions

try:
    doSomething()
except: 
    pass

or

try:
    doSomething()
except Exception: 
    pass

The difference is that the first one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from exceptions.BaseException, not exceptions.Exception.

See documentation for details:

What is the difference between res.end() and res.send()?

res is an HttpResponse object which extends from OutgoingMessage. res.send calls res.end which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here

Activate tabpage of TabControl

Use SelectTab like this:

TabPage t = tabControl1.TabPages[2];
tabControl1.SelectTab(t); //go to tab

Use SelectedTab like this:

TabPage t = tabControl1.TabPages[2];
tabControl1.SelectedTab = t; //go to tab

Adding click event listener to elements with the same class

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

AngularJS ui-router login authentication

I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.

$urlRouterProvider.rule(function ($injector, $location) {
   var UserService = $injector.get('UserService');
   var path = $location.path(), normalized = path.toLowerCase();

   if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
     $location.path('/login/signin');
   }
});

In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following

/login/signup // registering new user
/login/signin // login to app

so i have instant access to this two routes and every other route will be checked if you are online.

Here is my whole routing file for the login module

export default (
  $stateProvider,
  $locationProvider,
  $urlRouterProvider
) => {

  $stateProvider.state('login', {
    parent: 'app',
    url: '/login',
    abstract: true,
    template: '<ui-view></ui-view>'
  })

  $stateProvider.state('signin', {
    parent: 'login',
    url: '/signin',
    template: '<login-signin-directive></login-signin-directive>'
  });

  $stateProvider.state('lock', {
    parent: 'login',
    url: '/lock',
    template: '<login-lock-directive></login-lock-directive>'
  });

  $stateProvider.state('signup', {
    parent: 'login',
    url: '/signup',
    template: '<login-signup-directive></login-signup-directive>'
  });

  $urlRouterProvider.rule(function ($injector, $location) {
    var UserService = $injector.get('UserService');
    var path = $location.path();

    if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
         $location.path('/login/signin');
    }
  });

  $urlRouterProvider.otherwise('/error/not-found');
}

() => { /* code */ } is ES6 syntax, use instead function() { /* code */ }

Date object to Calendar [Java]

Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);

date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).

Count number of records returned by group by

Can you execute the following code below. It worked in Oracle.

SELECT COUNT(COUNT(*))
FROM temptable
GROUP BY column_1, column_2, column_3, column_4

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

How to create and add users to a group in Jenkins for authentication?

I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.

I didn't have high hopes, as that plugin was last updated in 2011

SQL Server - Return value after INSERT

The best and most sure solution is using SCOPE_IDENTITY().

Just you have to get the scope identity after every insert and save it in a variable because you can call two insert in the same scope.

ident_current and @@identity may be they work but they are not safe scope. You can have issues in a big application

  declare @duplicataId int
  select @duplicataId =   (SELECT SCOPE_IDENTITY())

More detail is here Microsoft docs

Use of document.getElementById in JavaScript

You're correct in that the document.getElementById("demo") call gets you the element by the specified ID. But you have to look at the rest of the statement to figure out what exactly the code is doing with that element:

.innerHTML=voteable;

You can see here that it's setting the innerHTML of that element to the value of voteable.

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

Check synchronously if file/directory exists in Node.js

The path module does not provide a synchronous version of path.exists so you have to trick around with the fs module.

Fastest thing I can imagine is using fs.realpathSync which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

Saving results with headers in Sql Server Management Studio

Another possibility is to use the clipboard to copy and paste the results directly into Excel. Just be careful with General type Excel columns, as they can sometimes have unpredictable results, depending on your data. CTL-A anywhere in the result grid, and then right-click:

enter image description here

If you have trouble with Excel's General format doing undesired conversions, select the blank columns in Excel before you paste and change the format to "text".

What's the difference between xsd:include and xsd:import?

I'm interested in this as well. The only explanation I've found is that xsd:include is used for intra-namespace inclusions, while xsd:import is for inter-namespace inclusion.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

How do you use bcrypt for hashing passwords in PHP?

bcrypt is a hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.

bcrypt uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds and key (password). [Source]

How to use bcrypt:

Using PHP >= 5.5-DEV

Password hashing functions have now been built directly into PHP >= 5.5. You may now use password_hash() to create a bcrypt hash of any password:

<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

// Usage 2:
$options = [
  'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C

To verify a user provided password against an existing hash, you may use the password_verify() as such:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Using PHP >= 5.3.7, < 5.5-DEV (also RedHat PHP >= 5.3.3)

There is a compatibility library on GitHub created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).

Using PHP < 5.3.7 (DEPRECATED)

You can use crypt() function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library. This alternative is provided only for historical purposes.

class Bcrypt{
  private $rounds;

  public function __construct($rounds = 12) {
    if (CRYPT_BLOWFISH != 1) {
      throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
    }

    $this->rounds = $rounds;
  }

  public function hash($input){
    $hash = crypt($input, $this->getSalt());

    if (strlen($hash) > 13)
      return $hash;

    return false;
  }

  public function verify($input, $existingHash){
    $hash = crypt($input, $existingHash);

    return $hash === $existingHash;
  }

  private function getSalt(){
    $salt = sprintf('$2a$%02d$', $this->rounds);

    $bytes = $this->getRandomBytes(16);

    $salt .= $this->encodeBytes($bytes);

    return $salt;
  }

  private $randomState;
  private function getRandomBytes($count){
    $bytes = '';

    if (function_exists('openssl_random_pseudo_bytes') &&
        (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
      $bytes = openssl_random_pseudo_bytes($count);
    }

    if ($bytes === '' && is_readable('/dev/urandom') &&
       ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
      $bytes = fread($hRand, $count);
      fclose($hRand);
    }

    if (strlen($bytes) < $count) {
      $bytes = '';

      if ($this->randomState === null) {
        $this->randomState = microtime();
        if (function_exists('getmypid')) {
          $this->randomState .= getmypid();
        }
      }

      for ($i = 0; $i < $count; $i += 16) {
        $this->randomState = md5(microtime() . $this->randomState);

        if (PHP_VERSION >= '5') {
          $bytes .= md5($this->randomState, true);
        } else {
          $bytes .= pack('H*', md5($this->randomState));
        }
      }

      $bytes = substr($bytes, 0, $count);
    }

    return $bytes;
  }

  private function encodeBytes($input){
    // The following is code from the PHP Password Hashing Framework
    $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    $output = '';
    $i = 0;
    do {
      $c1 = ord($input[$i++]);
      $output .= $itoa64[$c1 >> 2];
      $c1 = ($c1 & 0x03) << 4;
      if ($i >= 16) {
        $output .= $itoa64[$c1];
        break;
      }

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 4;
      $output .= $itoa64[$c1];
      $c1 = ($c2 & 0x0f) << 2;

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 6;
      $output .= $itoa64[$c1];
      $output .= $itoa64[$c2 & 0x3f];
    } while (true);

    return $output;
  }
}

You can use this code like this:

$bcrypt = new Bcrypt(15);

$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);

Alternatively, you may also use the Portable PHP Hashing Framework.

How can I slice an ArrayList out of an ArrayList in Java?

In Java, it is good practice to use interface types rather than concrete classes in APIs.

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);

Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

  1. It would be a lot of work to design, implement and test.
  2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
  3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

Can you get a Windows (AD) username in PHP?

You can say getenv('USERNAME')

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
}

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}

jQuery first child of "this"

I've added jsperf test to see the speed difference for different approaches to get the first child (total 1000+ children)

given, notif = $('#foo')

jQuery ways:

  1. $(":first-child", notif) - 4,304 ops/sec - fastest
  2. notif.children(":first") - 653 ops/sec - 85% slower
  3. notif.children()[0] - 1,416 ops/sec - 67% slower

Native ways:

  1. JavaScript native' ele.firstChild - 4,934,323 ops/sec (all the above approaches are 100% slower compared to firstChild)
  2. Native DOM ele from jQery: notif[0].firstChild - 4,913,658 ops/sec

So, first 3 jQuery approaches are not recommended, at least for first-child (I doubt that would be the case with many other too). If you have a jQuery object and need to get the first-child, then get the native DOM element from the jQuery object, using array reference [0] (recommended) or .get(0) and use the ele.firstChild. This gives the same identical results as regular JavaScript usage.

all tests are done in Chrome Canary build v15.0.854.0

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

How to auto-size an iFrame?

This solution worked best for me. It uses jQuery and the iframe's ".load" event.

What does the 'standalone' directive mean in XML?

Markup declarations can affect the content of the document, as passed from an XML processor to an application; examples are attribute defaults and entity declarations. The standalone document declaration, which may appear as a component of the XML declaration, signals whether or not there are such declarations which appear external to the document entity or in parameter entities. [Definition: An external markup declaration is defined as a markup declaration occurring in the external subset or in a parameter entity (external or internal, the latter being included because non-validating processors are not required to read them).]

http://www.w3.org/TR/xml/#sec-rmd

Setup a Git server with msysgit on Windows

There is a nice open source Git stack called Git Blit. It is available for different platform and in different packages. You can also easily deploy it to your existing Tomcat or any other servlet container. Take a look at Setup git server on windows in few clicks tutorial for more details, it will take you around 10 minutes to get basic setup.

Different names of JSON property during serialization and deserialization

Annotating with @JsonAlias which got introduced with Jackson 2.9+, without mentioning @JsonProperty on the item to be deserialized with more than one alias(different names for a json property) works fine.

I used com.fasterxml.jackson.annotation.JsonAlias for package consistency with com.fasterxml.jackson.databind.ObjectMapper for my use-case.

For e.g.:

@Data
@Builder
public class Chair {

    @JsonAlias({"woodenChair", "steelChair"})
    private String entityType;

}


@Test
public void test1() {

   String str1 = "{\"woodenChair\":\"chair made of wood\"}";
   System.out.println( mapper.readValue(str1, Chair.class));
   String str2 = "{\"steelChair\":\"chair made of steel\"}";
   System.out.println( mapper.readValue(str2, Chair.class));

}

just works fine.

(SC) DeleteService FAILED 1072

Logging-out and logging-in again close all blocking apps thus resolves the problem.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

Hey I had the same issue.
You can find all the packages in the link below:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn
And choose the package you need for your version of windows and python.

You have to download the file with whl extension. After that, you will copy the file into your python directory then run the following command:
py -3.6 -m pip install matplotlib-2.1.0-cp36-cp36m-win_amd64.whl

Here is an example when I wanted to install matplolib for my python 3.6 https://www.youtube.com/watch?v=MzV4N4XUvYc
and this is the video I followed.

How do I dump an object's fields to the console?

puts foo.to_json

might come in handy since the json module is loaded by default

Determine if a cell (value) is used in any formula

Have you tried Tools > Formula Auditing?

When to use window.opener / window.parent / window.top

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a <frame> or <iframe>
  • window.top refers to the top-most window from a window nested in one or more layers of <iframe> sub-windows

Those will be null (or maybe undefined) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)

PostgreSQL next value of the sequences?

I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:

SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id; 

Hope it helps :)

How to detect scroll position of page using jQuery

$(window).scroll( function() { 
 var scrolled_val = $(document).scrollTop().valueOf();
 alert(scrolled_val+ ' = scroll value');
});

This is another way of getting the value of scroll.

how to get selected row value in the KendoUI

I think it needs to be checked if any row is selected or not? The below code would check it:

var entityGrid = $("#EntitesGrid").data("kendoGrid");
            var selectedItem = entityGrid.dataItem(entityGrid.select());
            if (selectedItem != undefined)
                alert("The Row Is SELECTED");
            else
                alert("NO Row Is SELECTED")

Webpack.config how to just copy the index.html to the dist folder

I will add an option to VitalyB's answer:

Option 3

Via npm. If you run your commands via npm, then you could add this setup to your package.json (check out also the webpack.config.js there too). For developing run npm start, no need to copy index.html in this case because the web server will be run from the source files directory, and the bundle.js will be available from the same place (the bundle.js will live in memory only but will available as if it was located together with index.html). For production run npm run build and a dist folder will contain your bundle.js and index.html gets copied with good old cp-command, as you can see below:

"scripts": {
    "test": "NODE_ENV=test karma start",
    "start": "node node_modules/.bin/webpack-dev-server --content-base app",
    "build": "NODE_ENV=production node node_modules/.bin/webpack && cp app/index.html dist/index.html"
  }

Update: Option 4

There is a copy-webpack-plugin, as described in this Stackoverflow answer

But generally, except for the very "first" file (like index.html) and larger assets (like large images or video), include the css, html, images and so on directly in your app via require and webpack will include it for you (well, after you set it up correctly with loaders and possibly plugins).

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

.Cells(.Rows.Count,"A").End(xlUp).row

I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

.Cells(Rows.Count,"A").End(xlUp).row

Before the Cells, you can write your worksheet name, for example:

Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row

The worksheet name is not necessary when you operate on the same worksheet.

npm install hangs

When your ssh key is password protected run ssh-add. npm probably hangs somewhere asking for your password.

Scala check if element is present in a list

And if you didn't want to use strict equality, you could use exists:


myFunction(strings.exists { x => customPredicate(x) })

How to make a website secured with https

What should I do to prepare my website for https. (Do I need to alter the code / Config)

You should keep best practices for secure coding in mind (here is a good intro: http://www.owasp.org/index.php/Secure_Coding_Principles ), otherwise all you need is a correctly set up SSL certificate.

Is SSL and https one and the same..

Pretty much, yes.

Do I need to apply with someone to get some license or something.

You can buy an SSL certificate from a certificate authority or use a self-signed certificate. The ones you can purchase vary wildly in price - from $10 to hundreds of dollars a year. You would need one of those if you set up an online shop, for example. Self-signed certificates are a viable option for an internal application. You can also use one of those for development. Here's a good tutorial on how to set up a self-signed certificate for IIS: Enabling SSL on IIS 7.0 Using Self-Signed Certificates

Do I need to make all my pages secured or only the login page..

Use HTTPS for everything, not just the initial user login. It's not going to be too much of an overhead and it will mean the data that the users send/receive from your remotely hosted application cannot be read by outside parties if it is intercepted. Even Gmail now turns on HTTPS by default.

How to check if a radiobutton is checked in a radiogroup in Android?

try to use this

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"       
    android:orientation="horizontal"
>    
    <RadioButton
        android:id="@+id/standard_delivery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Standard_delivery"
        android:checked="true"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="15dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"   
    />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Midnight_delivery"
        android:checked="false"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"
        android:id="@+id/midnight_delivery"
    />    
</RadioGroup>

this is java class

public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.standard_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
                    break;
            case R.id.midnight_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
                    break;
        }
    }

Case insensitive comparison NSString

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString

How to turn off page breaks in Google Docs?

A long-term solution: userscript

You can use a userscript like Tampermonkey (if you are using Chrome or Edge-Chromium, here is the extension)

Then create a script and paste this in it:

// ==UserScript==
// @name         Google docs
// @include      https://*docs.google.*/document/*
// @grant    GM_addStyle
// ==/UserScript==

GM_addStyle ( `
    .kix-page-compact::before {
        border-top: none;
    }
` );

A temporary fix: developer console

You can use the developper console. In Chrome:
1. open your document on google docs
2. click in the url field and press ctrl+shift+I (or right click just above help and select "view page source)

Then modify the css (cf the steps on the printscreen below) :
1. once the console is loaded press ctrl+F and paste this : kix-page kix-page-compact
2. click on the div just below the one that is highlighted in yellow
3. in the right part, paste this in the filter box : .kix-page-compact::before
4. click on 1px dotted #aaa next to border-top and replace it by none
enter image description here

Export P7b file with all the certificate chain into CER file

I had similar problem extracting certificates from a file. This might not be the most best way to do it but it worked for me.

openssl pkcs7 -inform DER -print_certs -in <path of the file> | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'

Import and Export Excel - What is the best library?

You can use Microsoft.Jet.OLEDB.4.0

Remove all special characters except space from a string using JavaScript

dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:

function isNumber (text) {
      reg = new RegExp('[0-9]+$');
      if(text) {
        return reg.test(text);
      }
      return false;
    }

function removeSpecial (text) {
  if(text) {
    var lower = text.toLowerCase();
    var upper = text.toUpperCase();
    var result = "";
    for(var i=0; i<lower.length; ++i) {
      if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
        result += text[i];
      }
    }
    return result;
  }
  return '';
}

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Difference between "enqueue" and "dequeue"

Enqueue means to add an element, dequeue to remove an element.

var stackInput= []; // First stack
var stackOutput= []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

What is best tool to compare two SQL Server databases (schema and data)?

Try dbForge Data Compare for SQL Server. It can compare and sync any databases, even very large ones. Quick, easy, always delivers a correct result. Try it on your database and comment upon the product.

We can recommend you a reliable SQL comparison tool that offer 3 time’s faster comparison and synchronization of table data in your SQL Server databases. It's dbForge Data Compare for SQL Server and dbForge Schema Compare for SQL Server

Main advantages:

  • Speedier comparison and synchronization of large databases
  • Support of native SQL Server backups
  • Custom mapping of tables, columns, and schemas
  • Multiple options to tune your comparison and synchronization
  • Generating comparison and synchronization reports

Plus free 30-day trial and risk-free purchase with 30-day money back guarantee.

How to save a plot into a PDF file without a large margin around

What do you mean by "the proper size"? MATLAB figures are like vector graphics, so you can basically choose the size you want on your plot.

You can set the size of the paper and the position of the figure with the function set.

Example:

plot(epx(1:5));
set(gcf, 'PaperPosition', [0 0 5 5]); %Position plot at left hand corner with width 5 and height 5.
set(gcf, 'PaperSize', [5 5]); %Set the paper to have width 5 and height 5.
saveas(gcf, 'test', 'pdf') %Save figure

Enter image description here

The above code will remove most of the borders, but not all. This is because the left-hand corner ([0 0] in the position vector) is not the "true" left-hand corner. To remove more of the borders, you can adjust the PaperPosition and PaperSize vectors.

Example:

plot(exp(1:5))
set(gcf, 'PaperPosition', [-0.5 -0.25 6 5.5]); %Position the plot further to the left and down. Extend the plot to fill entire paper.
set(gcf, 'PaperSize', [5 5]); %Keep the same paper size
saveas(gcf, 'test', 'pdf')

Enter image description here

std::vector versus std::array in C++

A vector is a container class while an array is an allocated memory.

How do I expand the output display to see more columns of a pandas DataFrame?

Only using these 3 lines worked for me:

pd.set_option('display.max_columns', None)  
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', -1)

Anaconda / Python 3.6.5 / pandas: 0.23.0 / Visual Studio Code 1.26

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

How to display custom view in ActionBar?

For example, you can define a layout file which contains a EditText element.

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

</EditText> 

you can do

public class MainActivity extends Activity {

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

    ActionBar actionBar = getActionBar();
    // add the custom view to the action bar
    actionBar.setCustomView(R.layout.actionbar_view);
    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
    search.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId,
          KeyEvent event) {
        Toast.makeText(MainActivity.this, "Search triggered",
            Toast.LENGTH_LONG).show();
        return false;
      }
    });
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
        | ActionBar.DISPLAY_SHOW_HOME);


    }

Why does Git treat this text file as a binary file?

I had this same problem after editing one of my files in a new editor. Turns out the new editor used a different encoding (Unicode) than my old editor (UTF-8). So I simply told my new editor to save my files with UTF-8 and then git showed my changes properly again and didn't see it as a binary file.

I think the problem was simply that git doesn't know how to compare files of different encoding types. So the encoding type that you use really doesn't matter, as long as it remains consistent.

I didn't test it, but I'm sure if I would have just committed my file with the new Unicode encoding, the next time I made changes to that file it would have shown the changes properly and not detected it as binary, since then it would have been comparing two Unicode encoded files, and not a UTF-8 file to a Unicode file.

You can use an app like Notepad++ to easily see and change the encoding type of a text file; Open the file in Notepad++ and use the Encoding menu in the toolbar.

Entity Framework The underlying provider failed on Open

I had this error and it was caused by a typo in the connection string in App.config.

Go / golang time.Now().UnixNano() convert to milliseconds?

Just divide it:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}

Here is an example that you can compile and run to see the output

package main

import (
    "time"
    "fmt"
)

func main() {
    a := makeTimestamp()

    fmt.Printf("%d \n", a)
}

func makeTimestamp() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

I solved this issue to update .htaccess file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess in my case).

Just update or add this php_value max_execution_time 300 line before # END WordPress. Then save the file and try to install again.

If the error occurs again, you can maximize the value from 300 to 600.

macro run-time error '9': subscript out of range

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

How to check whether Kafka Server is running?

Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.

I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch sentence.

  def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
    val props = new Properties()
    props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
    props.put("group.id", kafkaParams.get("group.id").get.toString)
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    val simpleConsumer = new KafkaConsumer[String, String](props)
    simpleConsumer.listTopics()
  }

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

Java keytool easy way to add server cert from url/port

There were a few ways I found to do this:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert

Split page vertically using CSS

Here is the flex-box approach:

CSS

 .parent {
  display:flex;
  height:100vh;
  }
  .child{
    flex-grow:1;
  }
  .left{
    background:#ddd;
  }
  .center{
    background:#666;
  }

  .right{
    background:#999;
  }

HTML

<div class="parent">
    <div class="child left">Left</div>
    <div class="child center">Center</div>
    <div class="child right">Right</div>
</div>

You can try the same in js fiddle.

Decimal values in SQL for dividing results

Just another approach:

SELECT col1 * 1.0 / col2 FROM tbl1

Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.

A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:

SELECT col1 * 1. / col2 FROM tbl1

The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).

Principal advantage: less wordy than other approaches.

UDP vs TCP, how much faster is it?

Keep in mind that TCP usually keeps multiple messages on wire. If you want to implement this in UDP you'll have quite a lot of work if you want to do it reliably. Your solution is either going to be less reliable, less fast or an incredible amount of work. There are valid applications of UDP, but if you're asking this question yours probably is not.

How to output (to a log) a multi-level array in a format that is human-readable?

Drupal's Devel module has other useful functions including ones that can print formatted arrays and objects to log files. See the guide at http://ratatosk.net/drupal/tutorials/debugging-drupal.html

dd()

Logs any variable to a file named “drupal_debug.txt” in the site’s temp directory. All output from this function is appended to the log file, making it easy to see how the contents of a variable change as you modify your code.

If you’re using Mac OS X you can use the Logging Console to monitor the contents of the log file.

If you’re using a flavor of Linux you can use the command “tail -f drupal_debug.txt” to watch the data being logged to the file.

How do I perform the SQL Join equivalent in MongoDB?

Here's an example of a "join" * Actors and Movies collections:

https://github.com/mongodb/cookbook/blob/master/content/patterns/pivot.txt

It makes use of .mapReduce() method

* join - an alternative to join in document-oriented databases

jquery change button color onclick

$('input[type="submit"]').click(function(){
$(this).css('color','red');
});

Use class, Demo:- http://jsfiddle.net/BX6Df/

   $('input[type="submit"]').click(function(){
          $(this).addClass('red');
});

if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/

$('input[type="submit"]').click(function(){
  $(this).toggleClass('red');
});


.red
{
    background-color:red;
}

Updated answer for your comment.

http://jsfiddle.net/H2Xhw/

$('input[type="submit"]').click(function(){
    $('input[type="submit"].red').removeClass('red')
        $(this).addClass('red');
});

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I find this at google: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

It mentiones that we need to

  1. Update Gradle version to gradle-4.1-all ( changegradle-wrapper.properties by distributionUrl=\https\://services.gradle.org/distributions/gradle-4.1-all.zip
  2. Add google() to repositories repositories { google() } and dependencies { classpath 'com.android.tools.build:gradle:3.0.0-beta7' }

You may require to have Android Studio 3

Last element in .each() set

A shorter answer from here, adapted to this question:

var arr = $('.requiredText');
arr.each(function(index, item) {
   var is_last_item = (index == (arr.length - 1));
});

Just for completeness.

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

First, create the derived value:

df.loc[0, 'C'] = df.loc[0, 'D']

Then iterate through the remaining rows and fill the calculated values:

for i in range(1, len(df)):
    df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']


  Index_Date   A   B    C    D
0 2015-01-31  10  10   10   10
1 2015-02-01   2   3   23   22
2 2015-02-02  10  60  290  280

How to hide the soft keyboard from inside a fragment?

Exception for DialogFragment though, focus of the embedded Dialog must be hidden, instead only the first EditText within the embedded Dialog

this.getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

How can I get the domain name of my site within a Django template?

I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.

def myview(request):
    domain = request.build_absolute_uri('/')[:-1]
    # that will build the complete domain: http://foobar.com

Uninstall / remove a Homebrew package including all its dependencies

A More-Complete Bourne Shell Function

There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.

Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.

unbrew () {
    local formula
    for formula in "$@"; do
        brew deps "$formula" |
        xargs brew uninstall --ignore-dependencies --force
        brew uninstall --force "$formula"
    done
    brew missing | cut -f2 -d: | sort -u | xargs brew install
}

It was tested on Homebrew 1.7.4.

Caveats

This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).

How to list all installed packages and their versions in Python?

Here's a way to do it using PYTHONPATH instead of the absolute path of your python libs dir:

for d in `echo "${PYTHONPATH}" | tr ':' '\n'`; do ls "${d}"; done

[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' '\n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig          python2.7
BaseHTTPServer.py      _pyio.pyc              cgitb.pyo              doctest.pyo            htmlentitydefs.pyc     mimetools.pyc          plat-mac               runpy.py               stringold.pyc          traceback.pyo
BaseHTTPServer.pyc     _pyio.pyo              chunk.py               dumbdbm.py             htmlentitydefs.pyo     mimetools.pyo          platform.py            runpy.pyc              stringold.pyo          tty.py
BaseHTTPServer.pyo     _strptime.py           chunk.pyc              dumbdbm.pyc            htmllib.py             mimetypes.py           platform.pyc           runpy.pyo              stringprep.py          tty.pyc
Bastion.py             _strptime.pyc          chunk.pyo              dumbdbm.pyo            htmllib.pyc            mimetypes.pyc          platform.pyo           sched.py               stringprep.pyc         tty.pyo
Bastion.pyc            _strptime.pyo          cmd.py
....

Java: how to import a jar file from command line

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

PHP foreach with Nested Array?

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

C++ Matrix Class

You could use a template like :

#include <iostream>
using std::cerr;
using std::endl;

//qt4type
typedef unsigned int quint32;

template <typename T>
void deletep(T &) {}
template <typename T>
void deletep(T* & ptr) {
    delete ptr;
    ptr = 0;
}
template<typename T>
class Matrix {
    public:
        typedef T value_type;
        Matrix() : _cols(0), _rows(0), _data(new T[0]), auto_delete(true) {};
        Matrix(quint32 rows, quint32 cols, bool auto_del = true);

        bool exists(quint32 row, quint32 col) const;
        T & operator()(quint32 row, quint32 col);
        T operator()(quint32 row, quint32 col) const;
        virtual ~Matrix();

        int size() const { return _rows * _cols; }
        int rows() const { return _rows; }
        int cols() const { return _cols; }
    private:
        Matrix(const Matrix &);
        quint32 _rows, _cols;
        mutable T * _data;
        const bool auto_delete;
};
template<typename T>
Matrix<T>::Matrix(quint32 rows, quint32 cols, bool auto_del) : _rows(rows), _cols(cols), auto_delete(auto_del) {
    _data = new T[rows * cols];
}
template<typename T>
inline T & Matrix<T>::operator()(quint32 row, quint32 col) {
    return _data[_cols * row + col];
}
template<typename T>
inline T Matrix<T>::operator()(quint32 row, quint32 col) const {
    return _data[_cols * row + col];
}

template<typename T>
bool Matrix<T>::exists(quint32 row, quint32 col) const {
    return (row < _rows && col < _cols);
}

template<typename T>
Matrix<T>::~Matrix() {
    if(auto_delete){
        for(int i = 0, c = size(); i < c; ++i){
            //will do nothing if T isn't a pointer
            deletep(_data[i]);
        }
    }
    delete [] _data;
}

int main() {
    Matrix< int > m(10,10);
    quint32 i = 0;
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 10; ++y, ++i) {
            m(x, y) = i;
        }
    }
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 10; ++y) {
            cerr << "@(" << x << ", " << y << ") : " << m(x,y) << endl;
        }
    }
}

*edit, fixed a typo.

Where does Jenkins store configuration files for the jobs it runs?

Jenkins stores some of the related builds data like the following:

  • The working directory is stored in the directory {JENKINS_HOME}/workspace/.

    • Each job store its related temporal workspace folder in the directory {JENKINS_HOME}/workspace/{JOBNAME}
  • The configuration for all jobs stored in the directory {JENKINS_HOME}/jobs/.

    • Each job store its related builds data in the directory {JENKINS_HOME}/jobs/{JOBNAME}

    • Each job folder contains:

      • The job configuration file is {JENKINS_HOME}/jobs/{JOBNAME}/config.xml

      • The job builds are stored in {JENKINS_HOME}/jobs/{JOBNAME}/builds/

See the Jenkins documentation for a visual representation and further details.

JENKINS_HOME
 +- config.xml     (jenkins root configuration)
 +- *.xml          (other site-wide configuration files)
 +- userContent    (files in this directory will be served under your http://server/userContent/)
 +- fingerprints   (stores fingerprint records)
 +- nodes          (slave configurations)
 +- plugins        (stores plugins)
 +- secrets        (secretes needed when migrating credentials to other servers)
 +- workspace (working directory for the version control system)
     +- [JOBNAME] (sub directory for each job)
 +- jobs
     +- [JOBNAME]      (sub directory for each job)
         +- config.xml     (job configuration file)
         +- latest         (symbolic link to the last successful build)
         +- builds
             +- [BUILD_ID]     (for each build)
                 +- build.xml      (build result summary)
                 +- log            (log file)
                 +- changelog.xml  (change log)

MySQL DELETE FROM with subquery as condition

For others that find this question looking to delete while using a subquery, I leave you this example for outsmarting MySQL (even if some people seem to think it cannot be done):

DELETE e.*
FROM tableE e
WHERE id IN (SELECT id
             FROM tableE
             WHERE arg = 1 AND foo = 'bar');

will give you an error:

ERROR 1093 (HY000): You can't specify target table 'e' for update in FROM clause

However this query:

DELETE e.*
FROM tableE e
WHERE id IN (SELECT id
             FROM (SELECT id
                   FROM tableE
                   WHERE arg = 1 AND foo = 'bar') x);

will work just fine:

Query OK, 1 row affected (3.91 sec)

Wrap your subquery up in an additional subquery (here named x) and MySQL will happily do what you ask.

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

is soft link of

/etc/ssl/openssl.cnf

You can see that using long list (ls -l) on the /usr/local/ssl/ directory where you will find

lrwxrwxrwx 1 root root 20 Mar 1 05:15 openssl.cnf -> /etc/ssl/openssl.cnf

Unable to copy file - access to the path is denied

I was able to resolve the problem by removing the target file which is complaining(in your example "Bin\Debug\test.Resources.xml") from bin folder of target web site and re build it.That fixed it for me.

MSSQL Select statement with incremental integer column... not from a table

You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:

select @StartChequeNumber = 3446;
SELECT 
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable

will give the correct cheque number for each row.

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

Oracle 'Partition By' and 'Row_Number' keyword

I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.

When is each sorting algorithm used?

The Wikipedia page on sorting algorithms has a great comparison chart.

http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms

Oracle SELECT TOP 10 records

If you are using Oracle 12c, use:

FETCH NEXT N ROWS ONLY

SELECT DISTINCT 
  APP_ID, 
  NAME, 
  STORAGE_GB, 
  HISTORY_CREATED, 
  TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE  
  FROM HISTORY WHERE 
    STORAGE_GB IS NOT NULL AND 
      APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
  ORDER BY STORAGE_GB DESC
FETCH NEXT 10 ROWS ONLY

More info: http://docs.oracle.com/javadb/10.5.3.0/ref/rrefsqljoffsetfetch.html

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

How to run stored procedures in Entity Framework Core?

I'm using Entity Framework Core with my ASP.Net Core 3.x WebAPI. I wanted one of my end points just to execute a particular Stored Procedure, and this is the code I needed:

namespace MikesBank.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ResetController : ControllerBase
    {
        private readonly MikesBankContext _context;

        public ResetController(MikesBankContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            try
            {
                using (DbConnection conn = _context.Database.GetDbConnection())
                {
                    if (conn.State != System.Data.ConnectionState.Open)
                        conn.Open();
                    var cmd = conn.CreateCommand();
                    cmd.CommandText = "Reset_Data";
                    await cmd.ExecuteNonQueryAsync();
                }
                return new OkObjectResult(1);
            }
            catch (Exception ex)
            {
                return new BadRequestObjectResult(ex.Message);
            }
        }
    }
}

Notice how I need to get my DbContext which has been injected, but I also need to Open() this connection.

C++ int float casting

You should be aware that in evaluating an expression containing integers, the temporary results from each stage of evaluation are also rounded to be integers. In your assignment to float m, the value is only converted to the real-number capable float type after the integer arithmetic. This means that, for example, 3 / 4 would already be a "0" value before becoming 0.0. You need to force the conversion to float to happen earlier. You can do this by using the syntax float(value) on any of a.y, b.y, a.x, b.x, a.y - b.y, or a.x - b.x: it doesn't matter when it's done as long as one of the terms is a float before the division happens, e.g.

float m = float(a.y - b.y) / (a.x - b.x); 
float m = (float(a.y) - b.y) / (a.x - b.x); 
...etc...

Using jQuery To Get Size of Viewport

Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.

How to use a WSDL file to create a WCF service (not make a call)

There are good resources out there if you know what to search for. Try "Contract First" and WCF. or "WSDL First" and WCF.

Here is a selection:

How to make a Java Generic method static?

public static <E> E[] appendToArray(E[] array, E item) { ...

Note the <E>.

Static generic methods need their own generic declaration (public static <E>) separate from the class's generic declaration (public class ArrayUtils<E>).

If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_):

String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");

This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.

Use Awk to extract substring

I am asking in general, how to write a compatible awk script that performs the same functionality ...

To solve the problem in your quesiton is easy. (check others' answer).

If you want to write an awk script, which portable to any awk implementations and versions (gawk/nawk/mawk...) it is really hard, even if with --posix (gawk)

for example:

  • some awk works on string in terms of characters, some with bytes
  • some supports \x escape, some not
  • FS interpreter works differently
  • keywords/reserved words abbreviation restriction
  • some operator restriction e.g. **
  • even same awk impl. (gawk for example), the version 4.0 and 3.x have difference too.
  • the implementation of certain functions are also different. (your problem is one example, see below)

well all the points above are just spoken in general. Back to your problem, you problem is only related to fundamental feature of awk. awk '{print $x}' the line like that will work all awks.

There are two reasons why your awk line behaves differently on gawk and mawk:

  • your used substr() function wrongly. this is the main cause. you have substr($0, 0, RSTART - 1) the 0 should be 1, no matter which awk do you use. awk array, string idx etc are 1-based.

  • gawk and mawk implemented substr() differently.

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

Safely turning a JSON string into an object

Use the simple code example in "JSON.parse()":

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);

and reversing it:

var str = JSON.stringify(arr);

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

Flutter does not find android sdk

I spent a lot of time solving this.

Eventually what worked was going to project settings in android studio, sdk tools, uncheck hide obsolete packages and install sdk tools obsolete package.

Then run flutter doctor --android-licenses and then flutter doctor showed a green tick on my android toolchain.

Hope this helps someone.

make *** no targets specified and no makefile found. stop

make takes a makefile as input. Makefile usually is named makefile or Makefile. The configure command should generate a makefile, so that make could be in turn executed. Check if a makefile has been generated under your working directory.

How to Lock the data in a cell in excel using vba

You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...

Private Sub Worksheet_Change(ByVal Target As Range)

    'set your criteria here
    If Target.Column = 1 Then

        'must disable events if you change the sheet as it will
        'continually trigger the change event
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True

        MsgBox "You cannot do that!"
    End If
End Sub

Android check internet connection

This method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}

in manifest,

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com"); 
        //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
    }
}

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

Importing Maven project into Eclipse

Using mvn eclipse:eclipse will just generate general eclipse configuration files, this is fine if you have a simple project; but in case of a web-based project such as servlet/jsp you need to manually add Java EE features to eclipse (WTP).

To make the project runnable via eclipse servers portion, Configure Apache for Eclipse: Download and unzip Apache Tomcat somewhere. In Eclipse Windows -> Preferences -> Servers -> Runtime Environments add (Create local server), select your version of Tomcat, Next, Browse to the directory of the Tomcat you unzipped, click Finish.

Window -> Show View -> Servers Add the project to the server list

Mean per group in a data.frame

Here are a variety of ways to do this in base R including an alternative aggregate approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:

Using ave:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))

my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data

Using by:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)

my.data <- merge(my.data, by.month, by = 'Month')
my.data

Using lapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)

my.data <- merge(my.data, ly.mean, by = 'Month')
my.data

Using sapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data

sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data

Using aggregate:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month), 
                   FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))

my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary

my.data <- merge(my.data, my.summary, by = 'Month')
my.data

EDIT: June 28, 2020

Here I use aggregate to obtain the column means of an entire matrix by group where group is defined in an external vector:

my.group <- c(1,2,1,2,2,3,1,2,3,3)

my.data <- matrix(c(   1,    2,    3,    4,    5,
                      10,   20,   30,   40,   50,
                       2,    4,    6,    8,   10,
                      20,   30,   40,   50,   60,
                      20,   18,   16,   14,   12,
                    1000, 1100, 1200, 1300, 1400,
                       2,    3,    4,    3,    2,
                      50,   40,   30,   20,   10,
                    1001, 2001, 3001, 4001, 5001,
                    1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data

my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
#  Group.1          X1       X2          X3       X4          X5
#1       1    1.666667    3.000    4.333333    5.000    5.666667
#2       2   25.000000   27.000   29.000000   31.000   33.000000
#3       3 1000.333333 1700.333 2400.333333 3100.333 3800.333333

How to change Toolbar home icon color

I solved it by editing styles.xml:

<style name="ToolbarColoredBackArrow" parent="AppTheme">
    <item name="android:textColorSecondary">INSERT_COLOR_HERE</item>
</style>

...then referencing the style in the Toolbar definition in the activity:

<LinearLayout
    android:id="@+id/main_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        app:theme="@style/ToolbarColoredBackArrow"
        app:popupTheme="@style/AppTheme"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"/>

Drop rows with all zeros in pandas data frame

You can use a quick lambda function to check if all the values in a given row are 0. Then you can use the result of applying that lambda as a way to choose only the rows that match or don't match that condition:

import pandas as pd
import numpy as np

np.random.seed(0)

df = pd.DataFrame(np.random.randn(5,3), 
                  index=['one', 'two', 'three', 'four', 'five'],
                  columns=list('abc'))

df.loc[['one', 'three']] = 0

print df
print df.loc[~df.apply(lambda row: (row==0).all(), axis=1)]

Yields:

              a         b         c
one    0.000000  0.000000  0.000000
two    2.240893  1.867558 -0.977278
three  0.000000  0.000000  0.000000
four   0.410599  0.144044  1.454274
five   0.761038  0.121675  0.443863

[5 rows x 3 columns]
             a         b         c
two   2.240893  1.867558 -0.977278
four  0.410599  0.144044  1.454274
five  0.761038  0.121675  0.443863

[3 rows x 3 columns]

CSS Margin: 0 is not setting to 0

It seems that nobody actually read your question and looked at your source code. Here's the answer you all have been waiting for:

#header_content p {
    margin-top: 0;
}

jsFiddle

Spring MVC: Complex object as GET @RequestParam

I will add some short example from me.

The DTO class:

public class SearchDTO {
    private Long id[];

    public Long[] getId() {
        return id;
    }

    public void setId(Long[] id) {
        this.id = id;
    }
    // reflection toString from apache commons
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}

Request mapping inside controller class:

@RequestMapping(value="/handle", method=RequestMethod.GET)
@ResponseBody
public String handleRequest(SearchDTO search) {
    LOG.info("criteria: {}", search);
    return "OK";
}

Query:

http://localhost:8080/app/handle?id=353,234

Result:

[http-apr-8080-exec-7] INFO  c.g.g.r.f.w.ExampleController.handleRequest:59 - criteria: SearchDTO[id={353,234}]

I hope it helps :)

UPDATE / KOTLIN

Because currently I'm working a lot of with Kotlin if someone wants to define similar DTO the class in Kotlin should have the following form:

class SearchDTO {
    var id: Array<Long>? = arrayOf()

    override fun toString(): String {
        // to string implementation
    }
}

With the data class like this one:

data class SearchDTO(var id: Array<Long> = arrayOf())

the Spring (tested in Boot) returns the following error for request mentioned in answer:

"Failed to convert value of type 'java.lang.String[]' to required type 'java.lang.Long[]'; nested exception is java.lang.NumberFormatException: For input string: \"353,234\""

The data class will work only for the following request params form:

http://localhost:8080/handle?id=353&id=234

Be aware of this!

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

CSS: borders between table columns only

Take a table with class name column-bordered-table then add this below css.This will work with bootstrap table too

.column-bordered-table thead td {
    border-left: 1px solid #c3c3c3;
    border-right: 1px solid #c3c3c3;
}

.column-bordered-table td {
    border-left: 1px solid #c3c3c3;
    border-right: 1px solid #c3c3c3;
}

.column-bordered-table tfoot tr {
    border-top: 1px solid #c3c3c3;
    border-bottom: 1px solid #c3c3c3;
}

see the output below
N:B You have to add table header backgorund color as per you requirement

enter image description here

Static link of shared library function in gcc

Refer to:

http://www.linuxquestions.org/questions/linux-newbie-8/forcing-static-linking-of-shared-libraries-696714/

http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.apps/2004-05/0436.html

You need the static version of the library to link it.

A shared library is actually an executable in a special format with entry points specified (and some sticky addressing issues included). It does not have all the information needed to link statically.

You can't statically link a shared library (or dynamically link a static one).

The flag -static will force the linker to use static libraries (.a) instead of shared (.so) ones. But static libraries aren't always installed by default, so you may have to install the static library yourself.

Another possible approach is to use statifier or Ermine. Both tools take as input a dynamically linked executable and as output create a self-contained executable with all shared libraries embedded.

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

ApiNotActivatedMapError for simple html page using google-places-api

Have you tried following the advice on the linked help page? The help page at http://g.co/mapsJSApiErrors says:

ApiNotActivatedMapError

The Google Maps JavaScript API is not activated on your API project. You may need to enable the Google Maps JavaScript API under APIs in the Google Developers Console.

See Obtaining an API key.

So check that the key you are using has Google Maps JavaScript API enabled.

How to remove the default link color of the html hyperlink 'a' tag?

I had this challenge when I was working on a Rails 6 application using Bootstrap 4.

My challenge was that I didn't want this styling to override the default link styling in the application.

So I created a CSS file called custom.css or custom.scss.

And then defined a new CSS rule with the following properties:

.remove_link_colour {
  a, a:hover, a:focus, a:active {
      color: inherit;
      text-decoration: none;
  }
}

Then I called this rule wherever I needed to override the default link styling.

<div class="product-card__buttons">
  <button class="btn btn-success remove_link_colour" type="button"><%= link_to 'Edit', edit_product_path(product) %></button>
  <button class="btn btn-danger remove_link_colour" type="button"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></button>
</div>

This solves the issue of overriding the default link styling and removes the default colour, hover, focus, and active styling in the buttons only in places where I call the CSS rule.

That's all.

I hope this helps

What is a .pid file and what does it contain?

To understand pid files, refer this DOC

Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.

That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

Import jquery first before bootstrap:

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

Allowed memory size of 536870912 bytes exhausted in Laravel

I had the same problem. No matter how much I was increasing memory_limit (even tried 4GB) I was getting the same error, until I figured out it was because of wrong database credentials setted up in .env file

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

'M' (Capital) represent month & 'm' (Simple) represent minutes

Some example for months

'M' -> 7  (without prefix 0 if it is single digit)
'M' -> 12

'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12

'MMM' -> Jul (display with 3 character)

'MMMM' -> December (display with full name)

Some example for minutes

'm' -> 3  (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19

Access camera from a browser

The HTML5 spec does allow accessing the webcamera, but last I checked, it is far from finalized, and has very, very little browser support.

This is a link to get you started: http://www.html5rocks.com/en/tutorials/getusermedia/intro/

You'll probably have to use flash if you want it to work cross-browser.

W3 draft

SQL ROWNUM how to return rows between a specific range

I was looking for a solution for this and found this great article explaining the solution Relevant excerpt

My all-time-favorite use of ROWNUM is pagination. In this case, I use ROWNUM to get rows N through M of a result set. The general form is as follows:

select * enter code here
  from ( select /*+ FIRST_ROWS(n) */ 
  a.*, ROWNUM rnum 
      from ( your_query_goes_here, 
      with order by ) a 
      where ROWNUM <= 
      :MAX_ROW_TO_FETCH ) 
where rnum  >= :MIN_ROW_TO_FETCH;

Now with a real example (gets rows 148, 149 and 150):

select *
    from
  (select a.*, rownum rnum
     from
  (select id, data
     from t
   order by id, rowid) a
   where rownum <= 150
  )
   where rnum >= 148;

Get text from DataGridView selected cells

or, we can use something like this

dim i = dgv1.CurrentCellAddress.X
dim j = dgv1.CurrentCellAddress.Y
MsgBox(dgv1.Item(i,j).Value.ToString())

CSS container div not getting height

The best and the most bulletproof solution is to add ::before and ::after pseudoelements to the container. So if you have for example a list like:

<ul class="clearfix">
    <li></li>
    <li></li>
    <li></li>
</ul>

And every elements in the list has float:left property, then you should add to your css:

.clearfix::after, .clearfix::before {
     content: '';
     clear: both;
     display: table;
}

Or you could try display:inline-block; property, then you don't need to add any clearfix.

Using relative URL in CSS file, what location is it relative to?

One issue that can occur, and seemingly break this is when using auto minimization of css. The request path for the minified bundle can have a different path than the original css. This may happen automatically so it can cause confusion.

The mapped request path for the minified bundle should be "/originalcssfolder/minifiedbundlename" not just "minifiedbundlename".

In other words, name your bundles to have same path (with the /) as the original folder structure, this way any external resources like fonts, images will map to correct URIs by the browser. The alternative is to use absolute url( refs in your css but that isn't usually desirable.

Maven project.build.directory

You can find the most up to date answer for the value in your project just execute the

mvn3 help:effective-pom

command and find the <build> ... <directory> tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.

Fixed footer in Bootstrap

To get a footer that sticks to the bottom of your viewport, give it a fixed position like this:

footer {
    position: fixed;
    height: 100px;
    bottom: 0;
    width: 100%;
}

Bootstrap includes this CSS in the Navbar > Placement section with the class fixed-bottom. Just add this class to your footer element:

<footer class="fixed-bottom">

Bootstrap docs: https://getbootstrap.com/docs/4.4/utilities/position/#fixed-bottom

How to find longest string in the table column data

For Postgres:

SELECT column
FROM table
WHERE char_length(column) = (SELECT max(char_length(column)) FROM table )

This will give you the string itself,modified for postgres from @Thorsten Kettner answer

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

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

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

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

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

Visual Studio: How to break on handled exceptions?

Took me a while to find the new place for expection settings, therefore a new answer.

Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.

The simplest way to handle custom exceptions is selecting "all exceptions not in this list".

Here is a screenshot from the english version:

enter image description here

Here is a screenshot from the german version:

enter image description here

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

How to get HTTP Response Code using Selenium WebDriver

It is possible to get the response code of a http request using Selenium and Chrome or Firefox. All you have to do is start either Chrome or Firefox in logging mode. I will show you some examples below.

java + Selenium + Chrome Here is an example of java + Selenium + Chrome, but I guess that it can be done in any language (python, c#, ...).

All you need to do is tell chromedriver to do "Network.enable". This can be done by enabling Performance logging.

LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

After the request is done, all you have to do is get and iterate the Perfomance logs and find "Network.responseReceived" for the requested url:

LogEntries logs = driver.manage().logs().get("performance");

Here is the code:

import java.util.Iterator;
import java.util.logging.Level;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class TestResponseCode
{
    public static void main(String[] args)
    {
        // simple page (without many resources so that the output is
        // easy to understand
        String url = "http://www.york.ac.uk/teaching/cws/wws/webpage1.html";

        DownloadPage(url);
    }

    private static void DownloadPage(String url)
    {
        ChromeDriver driver = null;

        try
        {
            ChromeOptions options = new ChromeOptions();
            // add whatever extensions you need
            // for example I needed one of adding proxy, and one for blocking
            // images
            // options.addExtensions(new File(file, "proxy.zip"));
            // options.addExtensions(new File("extensions",
            // "Block-image_v1.1.crx"));

            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(ChromeOptions.CAPABILITY, options);

            // set performance logger
            // this sends Network.enable to chromedriver
            LoggingPreferences logPrefs = new LoggingPreferences();
            logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
            cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

            driver = new ChromeDriver(cap);

            // navigate to the page
            System.out.println("Navigate to " + url);
            driver.navigate().to(url);

            // and capture the last recorded url (it may be a redirect, or the
            // original url)
            String currentURL = driver.getCurrentUrl();

            // then ask for all the performance logs from this request
            // one of them will contain the Network.responseReceived method
            // and we shall find the "last recorded url" response
            LogEntries logs = driver.manage().logs().get("performance");

            int status = -1;

            System.out.println("\nList of log entries:\n");

            for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();)
            {
                LogEntry entry = it.next();

                try
                {
                    JSONObject json = new JSONObject(entry.getMessage());

                    System.out.println(json.toString());

                    JSONObject message = json.getJSONObject("message");
                    String method = message.getString("method");

                    if (method != null
                            && "Network.responseReceived".equals(method))
                    {
                        JSONObject params = message.getJSONObject("params");

                        JSONObject response = params.getJSONObject("response");
                        String messageUrl = response.getString("url");

                        if (currentURL.equals(messageUrl))
                        {
                            status = response.getInt("status");

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! returned response for "
                                            + messageUrl + ": " + status);

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! headers: "
                                            + response.get("headers"));
                        }
                    }
                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            System.out.println("\nstatus code: " + status);
        } finally
        {
            if (driver != null)
            {
                driver.quit();
            }
        }
    }
}

The output looks like this:

    Navigate to http://www.york.ac.uk/teaching/cws/wws/webpage1.html

    List of log entries:

    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameAttached","params":{"parentFrameId":"172.1","frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"://","loaderId":"172.1","name":"chromedriver dummy frame","id":"172.2","mimeType":"text/html","parentId":"172.1","url":"about:blank"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"VeryHigh","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"},"frameId":"3928.1","requestId":"3928.1","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492749007E9,"type":"Document","timestamp":20226.652971}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.responseReceived","params":{"frameId":"3928.1","requestId":"3928.1","response":{"headers":{"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"},"connectionReused":false,"timing":{"pushEnd":0,"workerStart":-1,"proxyEnd":-1,"workerReady":-1,"sslEnd":-1,"pushStart":0,"requestTime":20226.65335,"sslStart":-1,"dnsStart":0,"sendEnd":31.6569999995409,"connectEnd":31.4990000006219,"connectStart":0,"sendStart":31.5860000009707,"dnsEnd":0,"receiveHeadersEnd":115.645999998378,"proxyStart":-1},"encodedDataLength":-1,"remotePort":80,"mimeType":"text/html","headersText":"HTTP/1.1 200 OK\r\nDate: Tue, 11 Oct 2016 14:08:47 GMT\r\nServer: Apache/2.2.22 (Ubuntu)\r\nAccept-Ranges: bytes\r\nCache-Control: max-age=300\r\nExpires: Tue, 11 Oct 2016 14:13:47 GMT\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 1957\r\nKeep-Alive: timeout=4, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n","securityState":"neutral","requestHeadersText":"GET /teaching/cws/wws/webpage1.html HTTP/1.1\r\nHost: www.york.ac.uk\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, sdch\r\nAccept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n\r\n","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","protocol":"http/1.1","fromDiskCache":false,"fromServiceWorker":false,"requestHeaders":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Upgrade-Insecure-Requests":"1","Connection":"keep-alive","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36","Host":"www.york.ac.uk","Accept-Encoding":"gzip, deflate, sdch","Accept-Language":"en-GB,en-US;q=0.8,en;q=0.6"},"remoteIPAddress":"144.32.128.84","statusText":"OK","connectionId":11,"status":200},"loaderId":"3928.1","type":"Document","timestamp":20226.770012}}}
    ---------- bingo !!!!!!!!!!!!!! returned response for http://www.york.ac.uk/teaching/cws/wws/webpage1.html: 200
    ---------- bingo !!!!!!!!!!!!!! headers: {"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":2111,"requestId":"3928.1","encodedDataLength":1460,"timestamp":20226.770425}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"http://www.york.ac.uk","loaderId":"3928.1","id":"3928.1","mimeType":"text/html","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":1943,"requestId":"3928.1","encodedDataLength":825,"timestamp":20226.782673}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.loadingFinished","params":{"requestId":"3928.1","encodedDataLength":2285,"timestamp":20226.770199}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.loadEventFired","params":{"timestamp":20226.799391}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.domContentEventFired","params":{"timestamp":20226.845769}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Referer":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"High","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/favicon.ico"},"frameId":"3928.1","requestId":"3928.2","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492768527E9,"type":"Other","timestamp":20226.848174}}}

    status code: 200

java + Selenium + Firefox I have finally found the trick for Firefox too. You need to start firefox using MOZ_LOG and MOZ_LOG_FILE environment variables, and log http requests at debug level (4 = PR_LOG_DEBUG) - map.put("MOZ_LOG", "timestamp,sync,nsHttp:4"). Save the log in a temporary file. After that, get the content of the saved log file and parse it for the response code (using some simple regular expressions). First detect the start of the request, identifying its id (nsHttpChannel::BeginConnect [this=000000CED8094000]), then at the second step, find the response code for that request id (nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]).

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;

public class TestFirefoxResponse
{
  public static void main(String[] args)
      throws InterruptedException, IOException
  {
    GeckoDriverService service = null;

    // tell firefox to log http requests
    // at level 4 = PR_LOG_DEBUG: debug messages, notices
    // you could log everything at level 5, but the log file will 
    // be larger. 
    // create a temporary log file that will be parsed for
    // response code
    Map<String, String> map = new HashMap<String, String>();
    map.put("MOZ_LOG", "timestamp,sync,nsHttp:4");
    File tempFile = File.createTempFile("mozLog", ".txt");    
    map.put("MOZ_LOG_FILE", tempFile.getAbsolutePath());      

    GeckoDriverService.Builder builder = new GeckoDriverService.Builder();
    service = builder.usingAnyFreePort()
      .withEnvironment(map)
      .build();

    service.start();      

    WebDriver driver = new FirefoxDriver(service);

    // test 200
     String url = "https://api.ipify.org/?format=text";
    // test 404
    // String url = "https://www.advancedwebranking.com/lsdkjflksdjfldksfj";
    driver.get(url);

    driver.quit();

    String logContent = FileUtils.readFileToString(tempFile);

    ParseLog(logContent, url);
  }

  private static void ParseLog(String logContent, String url) throws MalformedURLException
  {
    // this is how the log looks like when the request starts
    // I have to get the id of the request using a regular expression
    // and use that id later to get the response
    //
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::BeginConnect [this=000000BFF27A5000]
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp host=api.ipify.org port=-1
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp uri=https://api.ipify.org/?format=text
    String pattern = "BeginConnect \\[this=(.*?)\\](?:.*?)uri=(.*?)\\s";

    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(logContent);

    String urlID = null;
    while (m.find())
    {
      String id = m.group(1);
      String uri = m.group(2);

      if (uri.equals(url))
      {
        urlID = id;
        break;
      }      
    }

    System.out.println("request id = " + urlID);

    // this is how the response looks like in the log file
    // ProcessResponse [this=000000CED8094000 httpStatus=200]
    // I will use another regular espression to get the httpStatus
    //
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=000000CED8094000 request=000000CED8014BB0 status=0]
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]    

    pattern = "ProcessResponse \\[this=" + urlID + " httpStatus=(.*?)\\]";

    p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    m = p.matcher(logContent);

    if (m.find())
    {
      String responseCode = m.group(1);
      System.out.println("response code found " + responseCode);
    }
    else
    {
      System.out.println("response code not found");
    }
  }
}

The output for this will be

request id = 0000007653D67000 response code found 200

The response headers can also be found in the log file. You can get them if you want.

    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp http response [
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   HTTP/1.1 404 Not Found
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp     OriginalHeaders
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp ]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=0000008A65D85000 request=0000008A65D1F900 status=0]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=0000008A65D85000 httpStatus=404]

Read Numeric Data from a Text File in C++

you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    double data[size of your data];

    std::ifstream input("file.txt");

    for (int i = 0; i < size of your data; i++) {
        input >> data[i];
        std::cout<< data[i]<<std::endl;
        }

}

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

CLI commands for github API v3 (replace all CAPS keywords):

curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
# Remember replace USER with your username and REPO with your repository/application name!
git remote add origin [email protected]:USER/REPO.git
git push origin master

How to store Node.js deployment settings/configuration files?

For long, I used to use the approach mentioned in the solution here. There is a concern however, about security of the secrets in clear text. You can use another package on top of config so that the security bits are taken care of.

Check this out: https://www.attosol.com/secure-application-secrets-using-masterkey-in-azure-key-vault/

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

i had the same problem and besides the above posts' configurations putting

            <plugin>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>1.9.32</version>
            <configuration>
                <enableJarClasses>false</enableJarClasses>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>endpoints_get_discovery_doc</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

in the plugins element in pom.xml. i think the problem was absence of execution -> goal "endpoints_get_discovery_doc" in some cases like mine, so this worked for me.

No module named 'openpyxl' - Python 3.4 - Ubuntu

I had the same problem solved using instead of pip install :

sudo apt-get install python-openpyxl
sudo apt-get install python3-openpyxl

The sudo command also works better for other packages.

Line continue character in C#

@"string here
that is long you mean"

But be careful, because

@"string here
           and space before this text
     means the space is also a part of the string"

It also escapes things in the string

@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder

Related

How do I initialize the base (super) class?

As of python 3.5.2, you can use:

class C(B):
def method(self, arg):
    super().method(arg)    # This does the same thing as:
                           # super(C, self).method(arg)

https://docs.python.org/3/library/functions.html#super

Where can I find a list of escape characters required for my JSON ajax return type?

Take a look at http://json.org/. It claims a bit different list of escaped characters than Chris proposed.

\"
\\
\/
\b
\f
\n
\r
\t
\u four-hex-digits

git switch branch without discarding local changes

Use git stash

git stash

It pushes changes to a stack. When you want to pull them back use

git stash apply

You can even pull individual items out. To completely blow away the stash:

git stash clear

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you are just visiting a webpage that you trust and you want to move forward fast, just:

1- Click the shield icon in the far right of the address bar.

Allow mixed content in Google Chrome

2- In the pop-up window, click "Load anyway" or "Load unsafe script" (depending on your Chrome version).


If you want to set your Chrome browser to ALWAYS(in all webpages) allow mixed content:

1- In an open Chrome browser, press Ctrl+Shift+Q on your keyboard to force close Chrome. Chrome must be fully closed before the next steps.

2- Right-click the Google Chrome desktop icon (or Start Menu link). Select Properties.

3- At the end of the existing information in the Target field, add: " --allow-running-insecure-content" (There is a space before the first dash.)

4- Click OK.

5- Open Chrome and try to launch the content that was blocked earlier. It should work now.

Python: Differentiating between row and column vectors

row vectors are (1,0) tensor, vectors are (0, 1) tensor. if using v = np.array([[1,2,3]]), v become (0,2) tensor. Sorry, i am confused.

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

VirtualBox error "Failed to open a session for the virtual machine"

Normally this error occurs when it try to load the previous state. This happened in Mac Virtual box. I tried after restarting the virtual box but again also i've encountered this issue. Right Click on the operating system in the virtual box and then Click on the Discard Saved State.. .This fixed the issue.

Can I call a constructor from another constructor (do constructor chaining) in C++?

C++11: Yes!

C++11 and onwards has this same feature (called delegating constructors).

The syntax is slightly different from C#:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};

C++03: No

It is worth pointing out that you can call the constructor of a parent class in your constructor e.g.:

 class A { /* ... */ };
    
    class B : public A
    {
        B() : A()
        {
            // ...
        }
    };

But, no, you can't call another constructor of the same class upto C++03.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

To share my experience :

Git (my own install) was looking for the key named 'id_rsa'.

So I tried to rename my keys to 'id_rsa' and 'id_rsa.pub' and it worked.

Btw, I'm sure there is an other way to do it but I didn't look deeper yet.

Keep SSH session alive

I wanted a one-time solution:

ssh -o ServerAliveInterval=60 [email protected]

Stored it in an alias:

alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'

Now can connect like this:

me@MyMachine:~$ sshprod

Reverse Contents in Array

You can use the following example to reverse the contents in an array:

#include <iostream>

int main()
{
    int n, x;

    // order value for var x
    cin >> x;  

    // create array and the value for array is value var x
    int arr[x];

    // loop for insert values for array by reverse  
    for(int i=x; i > 0; i--) {

        // var i is number of elements in array 
        cin >> n;
        arr[i - 1] = n;
    }

    // show element in array
    for(int l = 0; l < x; l++) {
        cout<<arr[l]<<endl;
    }

    return 0;        
}

Drop multiple tables in one shot in MySQL

declare @sql1 nvarchar(max) 
SELECT @sql1 =
  STUFF(
         (
           select ' drop table dbo.[' + name + ']'

           FROM sys.sysobjects AS sobjects
           WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
           for xml path('')
        ),
     1, 1, '')

  execute sp_executesql @sql1

Converting string to date in mongodb

How about using a library like momentjs by writing a script like this:

[install_moment.js]
function get_moment(){
    // shim to get UMD module to load as CommonJS
    var module = {exports:{}};

    /* 
    copy your favorite UMD module (i.e. moment.js) here
    */

    return module.exports
}
//load the module generator into the stored procedures: 
db.system.js.save( {
        _id:"get_moment",
        value: get_moment,
    });

Then load the script at the command line like so:

> mongo install_moment.js

Finally, in your next mongo session, use it like so:

// LOAD STORED PROCEDURES
db.loadServerScripts();

// GET THE MOMENT MODULE
var moment = get_moment();

// parse a date-time string
var a = moment("23 Feb 1997 at 3:23 pm","DD MMM YYYY [at] hh:mm a");

// reformat the string as you wish:
a.format("[The] DDD['th day of] YYYY"): //"The 54'th day of 1997"

Can't Load URL: The domain of this URL isn't included in the app's domains

Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.

I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.

Does bootstrap 4 have a built in horizontal divider?

I am using this example in my project:

html:

 <hr class="my-3 dividerClass"/>

css:

.dividerClass{
  border-top-color: #999
 }

JavaScript string and number conversion

You want to become familiar with parseInt() and toString().

And useful in your toolkit will be to look at a variable to find out what type it is—typeof:

<script type="text/javascript">
    /**
     * print out the value and the type of the variable passed in
     */

    function printWithType(val) {
        document.write('<pre>');
        document.write(val);
        document.write(' ');
        document.writeln(typeof val);
        document.write('</pre>');
    }

    var a = "1", b = "2", c = "3", result;

    // Step (1) Concatenate "1", "2", "3" into "123"
    // - concatenation operator is just "+", as long
    //   as all the items are strings, this works
    result = a + b + c;
    printWithType(result); //123 string

    // - If they were not strings you could do
    result = a.toString() + b.toString() + c.toString();
    printWithType(result); // 123 string

    // Step (2) Convert "123" into 123
    result = parseInt(result,10);
    printWithType(result); // 123 number

    // Step (3) Add 123 + 100 = 223
    result = result + 100;
    printWithType(result); // 223 number

    // Step (4) Convert 223 into "223"
    result = result.toString(); //
    printWithType(result); // 223 string

    // If you concatenate a number with a 
    // blank string, you get a string    
    result = result + "";
    printWithType(result); //223 string
</script>

Getting the textarea value of a ckeditor textarea with javascript

Simply execute

CKEDITOR.instances[elementId].getData();

with element id = id of element assigned the editor.

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How do I match any character across multiple lines in a regular expression?

In the context of use within languages, regular expressions act on strings, not lines. So you should be able to use the regex normally, assuming that the input string has multiple lines.

In this case, the given regex will match the entire string, since "<FooBar>" is present. Depending on the specifics of the regex implementation, the $1 value (obtained from the "(.*)") will either be "fghij" or "abcde\nfghij". As others have said, some implementations allow you to control whether the "." will match the newline, giving you the choice.

Line-based regular expression use is usually for command line things like egrep.

How to pass arguments to a Button command in Tkinter?

Use a lambda to pass the entry data to the command function if you have more actions to carry out, like this (I've tried to make it generic, so just adapt):

event1 = Entry(master)
button1 = Button(master, text="OK", command=lambda: test_event(event1.get()))

def test_event(event_text):
    if not event_text:
        print("Nothing entered")
    else:
        print(str(event_text))
        #  do stuff

This will pass the information in the event to the button function. There may be more Pythonesque ways of writing this, but it works for me.