Programs & Examples On #Gina

The graphical identification and authentication (GINA) library is a component of some Microsoft Windows operating systems that provides secure authentication and interactive logon services.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Instantiating a generic type

No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

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

I made a mistake by adding a service into imports array instead of providers array.

@NgModule({
  imports: [
    MyService // wrong here
  ],
  providers: [
    MyService // should add here
  ]
})
export class AppModule { }

Angular says you need to add Injectables into providers array.

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

I am not sure exactly what errors the request might return, you may want to return something like.

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch = emailFetch.data
      res.send(emailFetch)
   } catch(error) {
      res.status(error.response.status)
      return res.send(error.message);
    })

})

This code will need to be adapted to match the errors that you get from the axios call.

I have also converted the code to use the try and catch syntax since you are already using async.

How to set width of mat-table column in angular?

As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"

for example :

<mat-table #table [dataSource]="dataSource" matSortDisableClear>
    <ng-container matColumnDef="productId">
        <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="productName">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let product">
            <button (click)="view(product)">
                <mat-icon>visibility</mat-icon>
            </button>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

here matColumnDef is productId, productName and action

now we apply width by matColumnDef

styling

.mat-column-productId {
    flex: 0 0 10%;
}
.mat-column-productName {
    flex: 0 0 50%;
}

and remaining width is equally allocated to other columns

Select Specific Columns from Spark DataFrame

Just by using select select you can select particular columns, give them readable names and cast them. For example like this:

spark.read.csv(path).select(
          '_c0.alias("stn").cast(StringType),
          '_c1.alias("wban").cast(StringType),
          '_c2.alias("lat").cast(DoubleType),
          '_c3.alias("lon").cast(DoubleType)
        )
          .where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

How to resolve TypeError: can only concatenate str (not "int") to str

Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...

So for example the code below throw an error:

print( "Alireza" + 1980)

like this:

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str

To solve the issue, just add str to your number or value like:

print( "Alireza" + str(1980))

And the result as:

Alireza1980

Google Maps shows "For development purposes only"

For me, Error has been fixed when activated Billing in google console. (I got 1-year developer trial)

Button Width Match Parent

You can set match parent of the widget by

1) set width to double.infinity :

new Container(
          width: double.infinity,
          padding: const EdgeInsets.only(top: 16.0),
          child: new RaisedButton(
            child: new Text(
                "Submit",
                style: new TextStyle(
                  color: Colors.white,
                )
            ),
            colorBrightness: Brightness.dark,
            onPressed: () {
              _loginAttempt(context);
            },
            color: Colors.blue,
          ),
        ),

2) Use MediaQuery:

new Container(
          width: MedialQuery.of(context).size.width,
          padding: const EdgeInsets.only(top: 16.0),
          child: new RaisedButton(
            child: new Text(
                "Submit",
                style: new TextStyle(
                  color: Colors.white,
                )
            ),
            colorBrightness: Brightness.dark,
            onPressed: () {
              _loginAttempt(context);
            },
            color: Colors.blue,
          ),
        ),

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

In my case I tried to run npm i [email protected] and got the error because the dev server was running in another terminal on vsc. Hit ctrl+c, y to stop it in that terminal, and then installation works.

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

Numpy Resize/Rescale Image

Are there any libraries to do this in numpy/SciPy

Sure. You can do this without OpenCV, scikit-image or PIL.

Image resizing is basically mapping the coordinates of each pixel from the original image to its resized position.

Since the coordinates of an image must be integers (think of it as a matrix), if the mapped coordinate has decimal values, you should interpolate the pixel value to approximate it to the integer position (e.g. getting the nearest pixel to that position is known as Nearest neighbor interpolation).

All you need is a function that does this interpolation for you. SciPy has interpolate.interp2d.

You can use it to resize an image in numpy array, say arr, as follows:

W, H = arr.shape[:2]
new_W, new_H = (600,300)
xrange = lambda x: np.linspace(0, 1, x)

f = interp2d(xrange(W), xrange(H), arr, kind="linear")
new_arr = f(xrange(new_W), xrange(new_H))

Of course, if your image is RGB, you have to perform the interpolation for each channel.

If you would like to understand more, I suggest watching Resizing Images - Computerphile.

No provider for HttpClient

I found slimier problem. Please import the HttpClientModule in your app.module.ts file as follow:

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

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
],

imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

This worked for me:

refreshTableSorce() {
    this.dataSource = new MatTableDataSource<Element>(this.newSource);
}

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

Using ffmpeg to change framerate

In general, to set a video's FPS to 24, almost always you can do:

With Audio and without re-encoding:

# Extract video stream
ffmpeg -y -i input_video.mp4 -c copy -f h264 output_raw_bitstream.h264
# Extract audio stream
ffmpeg -y -i input_video.mp4 -vn -acodec copy output_audio.aac
# Remux with new FPS 
ffmpeg -y -r 24 -i output_raw_bitstream.h264 -i output-audio.aac -c copy output.mp4

If you want to find the video format (H264 in this case), you can use FFprobe, like this

ffprobe -loglevel error -select_streams v -show_entries stream=codec_name -of default=nw=1:nk=1 input_video.mp4

which will output:

h264

Read more in How can I analyze file and detect if the file is in H.264 video format?


With re-encoding:

ffmpeg -y -i input_video.mp4 -vf -r 24 output.mp4

How to use paginator from material angular?

Another way to link Angular Paginator with the data table using Slice Pipe.Here data is fetched only once from server.

View:

 <div class="col-md-3" *ngFor="let productObj of productListData | 
     slice: lowValue : highValue">
       //actual data dispaly  
 </div>

<mat-paginator [length]="productListData.length" [pageSize]="pageSize" 
   (page)="pageEvent = getPaginatorData($event)">
</mat-paginator> 

Component

    pageIndex:number = 0;
    pageSize:number = 50;
    lowValue:number = 0;
    highValue:number = 50;       

  getPaginatorData(event){
     console.log(event);
     if(event.pageIndex === this.pageIndex + 1){
        this.lowValue = this.lowValue + this.pageSize;
        this.highValue =  this.highValue + this.pageSize;
       }
    else if(event.pageIndex === this.pageIndex - 1){
       this.lowValue = this.lowValue - this.pageSize;
       this.highValue =  this.highValue - this.pageSize;
      }   
       this.pageIndex = event.pageIndex;
 }

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.

Select row on click react-table

There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.


enter image description here



After importing the HOC you can then use it like this with the necessary methods:

/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);

    // check to see if the key exists
    if (keyIndex >= 0) {
        // it does exist so we will remove it using destructing
        selection = [
            ...selection.slice(0, keyIndex),
            ...selection.slice(keyIndex + 1)
        ];
    } else {
        // it does not exist so add it
        selection.push(key);
    }
    // update the state
    this.setState({ selection });
}

/**
* Toggle all checkboxes for select table
*/
toggleAll() {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
        // we need to get at the internals of ReactTable
        const wrappedInstance = this.checkboxTable.getWrappedInstance();
        // the 'sortedData' property contains the currently accessible records based on the filter and sort
        const currentRecords = wrappedInstance.getResolvedState().sortedData;
        // we just push all the IDs onto the selection array
        currentRecords.forEach(item => {
            selection.push(item._original._id);
        });
    }
    this.setState({ selectAll, selection });
}

/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
    return this.state.selection.includes(key);
}

<CheckboxTable
    ref={r => (this.checkboxTable = r)}
    toggleSelection={this.toggleSelection}
    selectAll={this.state.selectAll}
    toggleAll={this.toggleAll}
    selectType="checkbox"
    isSelected={this.isSelected}
    data={data}
    columns={columns}
/>

See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable

Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw

How to enable Google Play App Signing

Do the following :

"CREATE APPLICATION" having the same name which you want to upload before.
Click create.
After creation of the app now click on the "App releases"
Click on the "MANAGE PRODUCTION"
Click on the "CREATE RELEASE"
Here you see "Google Play App Signing" dialog.
Just click on the "OPT-OUT" button.
It will ask you to confirm it. Just click on the "confirm" button

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

PHP7 : install ext-dom issue

sudo apt install php-xml will work but the thing is it will download the plugin for the latest PHP version.

If your PHP version is not the latest, then you can add version in it:

# PHP 7.1
sudo apt install php7.1-xml

# PHP 7.2:
sudo apt install php7.2-xml

# PHP 7.3
sudo apt install php7.3-xml


# PHP 7.4
sudo apt install php7.4-xml

# PHP 8
sudo apt install php-xml

Export result set on Dbeaver to CSV

The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.

Trying to use fetch and pass in mode: no-cors

Solution for me was to just do it server side

I used the C# WebClient library to get the data (in my case it was image data) and send it back to the client. There's probably something very similar in your chosen server-side language.

//Server side, api controller

[Route("api/ItemImage/GetItemImageFromURL")]
public IActionResult GetItemImageFromURL([FromQuery] string url)
{
    ItemImage image = new ItemImage();

    using(WebClient client = new WebClient()){

        image.Bytes = client.DownloadData(url);

        return Ok(image);
    }
}

You can tweak it to whatever your own use case is. The main point is client.DownloadData() worked without any CORS errors. Typically CORS issues are only between websites, hence it being okay to make 'cross-site' requests from your server.

Then the React fetch call is as simple as:

//React component

fetch(`api/ItemImage/GetItemImageFromURL?url=${imageURL}`, {            
        method: 'GET',
    })
    .then(resp => resp.json() as Promise<ItemImage>)
    .then(imgResponse => {

       // Do more stuff....
    )}

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

Cannot find module '@angular/compiler'

Try to delete that "angular/cli": "1.0.0-beta.28.3", in the devDependencies it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1", (since it is the current version, else add it by npm i --save-dev @angular/compiler-cli ), then in your root app folder run those commands:

  1. rm -r node_modules (or delete your node_modules folder manually)
  2. npm cache clean (npm > v5 add --force so: npm cache clean --force)
  3. npm install

How to reject in async/await syntax?

I have a suggestion to properly handle rejects in a novel approach, without having multiple try-catch blocks.

import to from './to';

async foo(id: string): Promise<A> {
    let err, result;
    [err, result] = await to(someAsyncPromise()); // notice the to() here
    if (err) {
        return 400;
    }
    return 200;
}

Where the to.ts function should be imported from:

export default function to(promise: Promise<any>): Promise<any> {
    return promise.then(data => {
        return [null, data];
    }).catch(err => [err]);
}

Credits go to Dima Grossman in the following link.

All com.android.support libraries must use the exact same version specification

After spending about 5 hours, this solution worked for me..

First add this line to your manifest tag if you do not have yet:

xmlns:tools="http://schemas.android.com/tools"

Example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.winanainc"
    android:versionCode="3"
    android:versionName="1.2"
    xmlns:tools="http://schemas.android.com/tools">

Then Add this meta tag inside your application to overwrite you build tools version, in this case for example I choosed the version 25.3.1

<application>
   ...
   ..
    <meta-data
        tools:replace="android:value"
        android:name="android.support.VERSION"
        android:value="25.3.1" />
</application>

How to save a new sheet in an existing excel file, using Pandas?

Another fairly simple way to go about this is to make a method like this:

def _write_frame_to_new_sheet(path_to_file=None, sheet_name='sheet', data_frame=None):
    book = None
    try:
        book = load_workbook(path_to_file)
    except Exception:
        logging.debug('Creating new workbook at %s', path_to_file)
    with pd.ExcelWriter(path_to_file, engine='openpyxl') as writer:
        if book is not None:
            writer.book = book
        data_frame.to_excel(writer, sheet_name, index=False)

The idea here is to load the workbook at path_to_file if it exists and then append the data_frame as a new sheet with sheet_name. If the workbook does not exist, it is created. It seems that neither openpyxl or xlsxwriter append, so as in the example by @Stefano above, you really have to load and then rewrite to append.

How to uninstall Anaconda completely from macOS

In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.

https://docs.anaconda.com/anaconda/install/uninstall/

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

Set height of chart in Chart.js

You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options

//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>

<script>
new Chart(somechart, {
options: {
    responsive: true,
    maintainAspectRatio: false

/*, your other options*/

}
});
</script>

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

While integrating material dialog is possible, I found that the complexity for such a trivial feature is pretty high. The code gets more complex if you are trying to achieve a non-trivial features.

For that reason, I ended up using PrimeNG Dialog, which I found pretty straightforward to use:

m-dialog.component.html:

<p-dialog header="Title">
  Content
</p-dialog>

m-dialog.component.ts:

@Component({
  selector: 'm-dialog',
  templateUrl: 'm-dialog.component.html',
  styleUrls: ['./m-dialog.component.css']
})
export class MDialogComponent {
  // dialog logic here
}

m-dialog.module.ts:

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { DialogModule } from "primeng/primeng";
import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    DialogModule
  ], 
  exports: [
    MDialogComponent,
  ], 
  declarations: [
    MDialogComponent
  ]
})
export class MDialogModule {}

Simply add your dialog into your component's html:

<m-dialog [isVisible]="true"> </m-dialog>

PrimeNG PrimeFaces documentation is easy to follow and very precise.

How to upgrade Angular CLI project?

JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.

Solution Details

I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install angular-cli was broken. Even trying to do ng version would produce an error. So I couldn't do the ng init command. See error below:

$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
    at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    ...

To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install.

After this I was able to do ng init. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts

This error is tied to the following factory provider in my AppModule

{ provide: Http, useFactory: 
    (backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
    return new HttpRerouteProvider(backend, options, router, navigationService, errorService);  
  }, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}

To address this error, I had use an exported function and made the following change to the provider.

    { 
      provide: Http, 
      useFactory: httpFactory, 
      deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
    }

... // elsewhere in AppModule

export function httpFactory(backend: XHRBackend, 
                            options: RequestOptions, 
                            router: Router, 
                            navigationService: NavigationService, 
                            errorService: ErrorService) {
  return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}

Summary

To summarize what I understand to be the most important details, the following changes were required:

  1. Update angular-cli version using the steps detailed in JJB's answer (and on their github page).

  2. Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24

  3. With the assistance of angular-cli and the ng init command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.

  4. Make code changes to export functions before I reference them, as captured in the solution details.

Key Configuration Changes

angular-cli.json changes

{
  "project": {
    "version": "1.0.0-beta.16",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
...

changed to...

{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
...

My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build",
    "buildProd": "ng build --env=prod"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "@angular/material": "^2.0.0-beta.1",
    "@types/google-libphonenumber": "^7.4.8",
    "angular2-datatable": "^0.4.2",
    "apollo-client": "^0.4.22",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2",
    "google-libphonenumber": "^2.0.4",
    "graphql-tag": "^0.1.15",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.1.16"
  },
  "devDependencies": {
    "@types/hammerjs": "^2.0.33",
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "^4.14.39",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3",
    "typings": "1.4.0"
  }
}

Get first row of dataframe in Python Pandas based on criteria

you can take care of the first 3 items with slicing and head:

  1. df[df.A>=4].head(1)
  2. df[(df.A>=4)&(df.B>=3)].head(1)
  3. df[(df.A>=4)&((df.B>=3) * (df.C>=2))].head(1)

The condition in case nothing comes back you can handle with a try or an if...

try:
    output = df[df.A>=6].head(1)
    assert len(output) == 1
except: 
    output = df.sort_values('A',ascending=False).head(1)

How to create a fixed sidebar layout with Bootstrap 4?

I used this in my code:

<div class="sticky-top h-100">
    <nav id="sidebar" class="vh-100">
        ....

this cause your sidebar height become 100% and fixed at top.

Reading file using relative path in python project

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
    test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]

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

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

how to implement Pagination in reactJs

I've recently created library which helps to cope with pagination cases like:

  • storing normalized data in Redux
  • caching pages based on search filters
  • simplified react-virtualized list usage
  • refreshing results in background
  • storing last visited page and used filters

DEMO page implements all above features.

Source code you can find on Github

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

Deep-Learning Nan loss reasons

I'd like to plug in some (shallow) reasons I have experienced as follows:

  1. we may have updated our dictionary(for NLP tasks) but the model and the prepared data used a different one.
  2. we may have reprocessed our data(binary tf_record) but we loaded the old model. The reprocessed data may conflict with the previous one.
  3. we may should train the model from scratch but we forgot to delete the checkpoints and the model loaded the latest parameters automatically.

Hope that helps.

Are dictionaries ordered in Python 3.6+?

To fully answer this question in 2020, let me quote several statements from official Python docs:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

Changed in version 3.8: Dictionaries are now reversible.

Dictionaries and dictionary views are reversible.

A statement regarding OrderedDict vs Dict:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

How can I set a cookie in react?

I set cookies in React using the react-cookie library, it has options you can pass in options to set expiration time.

Check it out here

An example of its use for your case:

import cookie from "react-cookie";

setCookie() => {
  let d = new Date();
  d.setTime(d.getTime() + (minutes*60*1000));

  cookie.set("onboarded", true, {path: "/", expires: d});
};

Is this a good way to clone an object in ES6?

If the methods you used isn't working well with objects involving data types like Date, try this

Import _

import * as _ from 'lodash';

Deep clone object

myObjCopy = _.cloneDeep(myObj);

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

First check the type of compression using the file command:

file name_name.tgz

O/P- If output is " XZ compressed data"

Then use tar xf <archive name> to unzip the file, e.g.

  • tar xf archive.tar.xz

  • tar xf archive.tar.gz

  • tar xf archive.tar

  • tar xf archive.tgz

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

Split Spark Dataframe string column into multiple columns

Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect, or using udfs. Unfortunately this only works for spark version 2.1 and above, because it requires the posexplode function.

Suppose you had the following DataFrame:

df = spark.createDataFrame(
    [
        [1, 'A, B, C, D'], 
        [2, 'E, F, G'], 
        [3, 'H, I'], 
        [4, 'J']
    ]
    , ["num", "letters"]
)
df.show()
#+---+----------+
#|num|   letters|
#+---+----------+
#|  1|A, B, C, D|
#|  2|   E, F, G|
#|  3|      H, I|
#|  4|         J|
#+---+----------+

Split the letters column and then use posexplode to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr to grab the element at index pos in this array.

import pyspark.sql.functions as f

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .show()
#+---+------------+---+---+
#|num|     letters|pos|val|
#+---+------------+---+---+
#|  1|[A, B, C, D]|  0|  A|
#|  1|[A, B, C, D]|  1|  B|
#|  1|[A, B, C, D]|  2|  C|
#|  1|[A, B, C, D]|  3|  D|
#|  2|   [E, F, G]|  0|  E|
#|  2|   [E, F, G]|  1|  F|
#|  2|   [E, F, G]|  2|  G|
#|  3|      [H, I]|  0|  H|
#|  3|      [H, I]|  1|  I|
#|  4|         [J]|  0|  J|
#+---+------------+---+---+

Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr which allows us use column values as parameters.

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .show()
#+---+-------+---+
#|num|   name|val|
#+---+-------+---+
#|  1|letter0|  A|
#|  1|letter1|  B|
#|  1|letter2|  C|
#|  1|letter3|  D|
#|  2|letter0|  E|
#|  2|letter1|  F|
#|  2|letter2|  G|
#|  3|letter0|  H|
#|  3|letter1|  I|
#|  4|letter0|  J|
#+---+-------+---+

Now we can just groupBy the num and pivot the DataFrame. Putting that all together, we get:

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .groupBy("num").pivot("name").agg(f.first("val"))\
    .show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#|  1|      A|      B|      C|      D|
#|  3|      H|      I|   null|   null|
#|  2|      E|      F|      G|   null|
#|  4|      J|   null|   null|   null|
#+---+-------+-------+-------+-------+

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

There are multiple possible causes for this error:

1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input() decorator

Your html file:

<body [x]="...">

Your class file:

export class YourComponentClass {

  @Input()
  x: string;
  ...
}

(make sure you also have the parentheses)

2) Make sure you registered your component/directive/pipe classes in NgModule:

@NgModule({
  ...
  declarations: [
    ...,
    YourComponentClass
  ],
  ...
})

See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.

3) Also happens if you have a typo in your angular directive. For example:

<div *ngif="...">
     ^^^^^

Instead of:

<div *ngIf="...">

This happens because under the hood angular converts the asterisk syntax to:

<div [ngIf]="...">

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I'm using jQuery 3.3.1 and I received the same error, in my case, the URL was an Object vs a string.

What happened was, that I took URL = window.location - which returned an object. Once I've changed it into window.location.href - it worked w/o the e.indexOf error.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = true;
      return $status;
}

Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type

as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = "true";
      return $status;
}

ImportError: No module named google.protobuf

I also have this issue and have been looking into it for a long time. It seems that there is no such problem on python 3+. The problem is actually on google.protobuf

Solution 1:

pip uninstall protobuf
pip uninstall google
pip install google
pip install protobuf
pip install google-cloud

Solution 2:

create an __init__.py in "google" folder.

cd /path/to/your/env/lib/python2.7/site-packages/google
touch __init__.py

Hopefully it will work.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

There's also another way to do this-

select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;

formGroup expects a FormGroup instance

I was using reactive forms and ran into similar problems. What helped me was to make sure that I set up a corresponding FormGroup in the class. Something like this:

myFormGroup: FormGroup = this.builder.group({
    dob: ['', Validators.required]
});

Get an image extension from an uploaded file in Laravel

You can use the pathinfo() function built into PHP for that:

$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];

Or more concisely, you can pass an option get get it directly;

$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);

How do I declare a model class in my Angular 2 component using TypeScript?

export class Car {
  id: number;
  make: string;
  model: string;
  color: string;
  year: Date;

  constructor(car) {
      {
        this.id = car.id;
        this.make = car.make || '';
        this.model = car.model || '';
        this.color = car.color || '';
        this.year = new Date(car.year).getYear();
      }
  }
}

The || can become super useful for very complex data objects to default data that doesn't exist.

. .

In your component.ts or service.ts file you can deserialize response data into the model:

// Import the car model
import { Car } from './car.model.ts';

// If single object
car = new Car(someObject);

// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

Spring Data and Native Query with pagination

I use oracle database and I did not get the result but an error with generated comma which d-man speak about above.

Then my solution was:

Pageable pageable = new PageRequest(current, rowCount);

As you can see without order by when create Pagable.

And the method in the DAO:

public interface UserRepository extends JpaRepository<User, Long> {
  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 /*#pageable*/ ORDER BY LASTNAME",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
 }

error TS2339: Property 'x' does not exist on type 'Y'

I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images interface, you can define any key as a String.

When accessing a property, the "dot" syntax (images.main) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:

return json.property[0].index

where index was a variable. But it interpreted index, resulting in a:

cannot find property "index" of json.property[0]

And I had to find a workaround using your syntax:

return json.property[0][index]

It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

CR has changed the Version No of Assemblies. The Old Version is 13.0.2000.0 (this is a incompatible version problem). The New Version is 13.0.3500.0 or 13.0.4000.0 - this is for my test case of Visual Studio 2019 and .net 4.7.2 and Window Server 2019. You need to open all your projects, Remove the old dll reference and add the new references. Then build the application again.

I learnt from source:

enter image description here

TO remove: Right click on an assembly under references to remove it.

enter image description here

This is where the error comes from - it is exactly what the error message outputs:

error message:

Could not load file or assembly ... The located assembly's manifest definition does not match the assembly reference ...

location error message referring to:

"C:\Visual-Studio-2019-Proj\Proj Windows Inventory\Proj Windows Inventory\obj\x86\Debug\Press HDL Windows Inventory.exe.manifest"

And it looks like this:

-The older version of .net 3.5 and CReports version="13.0.2000.0" and VS2012:

<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="372736">
      <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.2000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />

-The newer version of .net 4.7.2 and CReport version="13.0.4000.0" and VS2019:

<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="373248">
      <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.4000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />

How to sort dates from Oldest to Newest in Excel?

Convert text to date format via the "Data" tab.

Highlight the relevant section and then select from the top menu Data> Datat Tools > Text to Column (depending on your version).

Choose the "Delimited" option.

Toggle through the Delimiter options until the entry appears in the desired format, and select "Next".

Under the Data format, select Date (DMY)

Select "finish" and the issue should be resolved.

<img>: Unsafe value used in a resource URL context

Use Safe Pipe to fix it.

  • Create a safe pipe if u haven't any.

    ng g pipe safe

  • add Safe pipe in app.module.ts

    declarations: [SafePipe]

  • declare safe pipe in your ts

Import Dom Sanitizer and Safe Pipe to access url safely

import { Pipe, PipeTransform} from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' })

export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) { }
transform(url) {
 return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
  • Add safe with src url

    <img width="900" height="500" [src]="link | safe"/>

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

Who ever also stumbles over this post.

I belive is the correct way:

  <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
    <div>{{ appointment }}</div>
  </div>

Set initially selected item in Select list in Angular2

The easiest way to solve this problem in Angular is to do:

In Template:

<select [ngModel]="selectedObjectIndex">
  <option [value]="i" *ngFor="let object of objects; let i = index;">{{object.name}}</option>
</select>

In your class:

this.selectedObjectIndex = 1/0/your number wich item should be selected

Static image src in Vue.js template

This solution is for Vue-2 users:

  1. In vue-2 if you don't like to keep your files in static folder (relevant info), or
  2. In vue-2 & vue-cli-3 if you don't like to keep your files in public folder (static folder is renamed to public):

The simple solution is :)

<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}

If you like to keep your static images in static/assets/img or public/assets/img folder, then just do:

<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./

Use virtualenv with Python with Visual Studio Code in Ubuntu

I was able to use the workspace setting that other people on this page have been asking for.

In Preferences, ?+P, search for python.pythonPath in the search bar.

You should see something like:

// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
"python.pythonPath": "python"

Then click on the WORKSPACE SETTINGS tab on the right side of the window. This will make it so the setting is only applicable to the workspace you're in.

Afterwards, click on the pencil icon next to "python.pythonPath". This should copy the setting over the workspace settings.

Change the value to something like:

"python.pythonPath": "${workspaceFolder}/venv"

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

How to remove specific substrings from a set of strings in Python?

I did the test (but it is not your example) and the data does not return them orderly or complete

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}

I proved that this works:

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']

or

>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
...     newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']

Firebase cloud messaging notification not received by device

I faced the same problem but I had still had some debris in my manifest from the old GCM. When I took the following permission out of my manifest it fixed the error. com.google.android.c2dm.permission.RECEIVE

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

For those situations where you need a bit more customisation of the output (separator or decimal symbol), or who have large dataset (over 65k rows), I wrote the following:

Option Explicit

Sub rng2csv(rng As Range, fileName As String, Optional sep As String = ";", Optional decimalSign As String)
'export range data to a CSV file, allowing to chose the separator and decimal symbol
'can export using rng number formatting!
'by Patrick Honorez --- www.idevlop.com
    Dim f As Integer, i As Long, c As Long, r
    Dim ar, rowAr, sOut As String
    Dim replaceDecimal As Boolean, oldDec As String

    Dim a As Application:   Set a = Application

    ar = rng
    f = FreeFile()
    Open fileName For Output As #f

    oldDec = Format(0, ".")     'current client's decimal symbol
    replaceDecimal = (decimalSign <> "") And (decimalSign <> oldDec)

    For Each r In rng.Rows
        rowAr = a.Transpose(a.Transpose(r.Value))
        If replaceDecimal Then
            For c = 1 To UBound(rowAr)
                'use isnumber() to avoid cells with numbers formatted as strings
                If a.IsNumber(rowAr(c)) Then
                    'uncomment the next 3 lines to export numbers using source number formatting
'                    If r.cells(1, c).NumberFormat <> "General" Then
'                        rowAr(c) = Format$(rowAr(c), r.cells(1, c).NumberFormat)
'                    End If
                    rowAr(c) = Replace(rowAr(c), oldDec, decimalSign, 1, 1)
                End If
            Next c
        End If
        sOut = Join(rowAr, sep)
        Print #f, sOut
    Next r
    Close #f

End Sub

Sub export()
    Debug.Print Now, "Start export"
    rng2csv shOutput.Range("a1").CurrentRegion, RemoveExt(ThisWorkbook.FullName) & ".csv", ";", "."
    Debug.Print Now, "Export done"
End Sub

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I faced the same problem but the issue was very silly, By mistake I have given wrong relationship I have given relationship between 2 Ids.

Execution failed for task ':app:processDebugResources' even with latest build tools

Set your compileSdkVersion to 23 in your module's build.gradle file.

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

How to import local packages in go?

If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like

myapp/
--vendor/
----common/
----routers/
------middleware/
--main.go

and import it like this

import (
    "common"
    "routers"
    "routers/middleware"
)

This will work because Go will try to lookup your package starting at your project’s vendor directory (if it has at least one .go file) instead of $GOPATH/src.

FYI: You can do more with vendor, because this feature allows you to put "all your dependency’s code" for a package inside your own project's directory so it will be able to always get the same dependencies versions for all builds. It's like npm or pip in python, but you need to manually copy your dependencies to you project, or if you want to make it easy, try to look govendor by Daniel Theophanes

For more learning about this feature, try to look up here

Understanding and Using Vendor Folder by Daniel Theophanes

Understanding Go Dependency Management by Lucas Fernandes da Costa

I hope you or someone else find it helpfully

What are the differences between normal and slim package of jquery?

As noted the Ajax and effects modules have been excluded from jQuery slim the size difference as of 3.3.1 for the minified version unzipped is 85k vs 69k (16k saving for slim) or 30vs24 for zipped, it is important to note that bootstrap 4 uses the slim jQuery so if someone wants the full version they need to call that instead

TypeError: tuple indices must be integers, not str

Just adding a parameter like the below worked for me.

cursor=conn.cursor(dictionary=True)

I hope this would be helpful either.

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

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

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



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}

Angular2 - Http POST request parameters

I landed here when I was trying to do a similar thing. For a application/x-www-form-urlencoded content type, you could try to use this for the body:

var body = 'username' =myusername & 'password'=mypassword;

with what you tried doing the value assigned to body will be a string.

Javascript ES6/ES5 find in array and change

Given a changed object and an array:

const item = {...}
let items = [{id:2}, {id:3}, {id:4}];

Update the array with the new object by iterating over the array:

items = items.map(x => (x.id === item.id) ? item : x)

How to save .xlsx data to file as a blob

This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

How to get user's high resolution profile picture on Twitter?

for me the "workaround" solution was to remove the "_normal" from the end of the string

Check it out below:

In Flask, What is request.args and how is it used?

@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...

... the request.args is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question

And how many parameters request.args.get() takes.

It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).

Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.

Docker is in volume in use, but there aren't any Docker containers

Volume can be in use by one of stopped containers. You can remove such containers by command:

docker container prune

then you can remove not used volumes

docker volume prune

Angular 2 router no base href set

it is just that add below code in the index.html head tag

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

that worked like a charm for me.

Passing data to components in vue.js

I access main properties using $root.

Vue.component("example", { 
    template: `<div>$root.message</div>`
});
...
<example></example>

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.

My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:

import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
    sys.path.append(module_path)

This allows you to import the desired function from the module hierarchy:

from project1.lib.module import function
# use the function normally
function(...)

Note that it is necessary to add empty __init__.py files to project1/ and lib/ folders if you don't have them already.

JavaScript: Difference between .forEach() and .map()

  • Array.forEach “executes a provided function once per array element.”

  • Array.map “creates a new array with the results of calling a provided function on every element in this array.”

So, forEach doesn’t actually return anything. It just calls the function for each array element and then it’s done. So whatever you return within that called function is simply discarded.

On the other hand, map will similarly call the function for each array element but instead of discarding its return value, it will capture it and build a new array of those return values.

This also means that you could use map wherever you are using forEach but you still shouldn’t do that so you don’t collect the return values without any purpose. It’s just more efficient to not collect them if you don’t need them.

Pandas: Convert Timestamp to datetime.date

You can convert a datetime.date object into a pandas Timestamp like this:

#!/usr/bin/env python3
# coding: utf-8

import pandas as pd
import datetime

# create a datetime data object
d_time = datetime.date(2010, 11, 12)

# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')

# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)

# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)

# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)

Angular 2 optional route parameter

With angular4 we just need to organise routes together in hierarchy

const appRoutes: Routes = [
  { 
    path: '', 
    component: MainPageComponent 
  },
  { 
    path: 'car/details', 
    component: CarDetailsComponent 
  },
  { 
    path: 'car/details/platforms-products', 
    component: CarProductsComponent 
  },
  { 
    path: 'car/details/:id', 
    component: CadDetailsComponent 
  },
  { 
    path: 'car/details/:id/platforms-products', 
    component: CarProductsComponent 
  }
];

This works for me . This way router know what is the next route based on option id parameters.

golang why don't we have a set datastructure

Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Different use case, but set your session as the default session did the trick for me:

with sess.as_default():
    result = compute_fn([seed_input,1])

This is one of these mistakes that is so obvious, once you have solved it.

My use-case is the following:
1) store keras VGG16 as tensorflow graph
2) load kers VGG16 as a graph
3) run tf function on the graph and get:

FailedPreconditionError: Attempting to use uninitialized value block1_conv2/bias
     [[Node: block1_conv2/bias/read = Identity[T=DT_FLOAT, _class=["loc:@block1_conv2/bias"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](block1_conv2/bias)]]
     [[Node: predictions/Softmax/_7 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_168_predictions/Softmax", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Angular2 handling http response

The service :

import 'rxjs/add/operator/map';

import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';

@Injectable()
export class ItemService {
  private api = "your_api_url";

  constructor(private http: Http) {

  }

  toSaveItem(item) {
    return new Promise((resolve, reject) => {
      this.http
        .post(this.api + '/items', { item: item })
        .map(res => res.json())
        // This catch is very powerfull, it can catch all errors
        .catch((err: Response) => {
          // The err.statusText is empty if server down (err.type === 3)
          console.log((err.statusText || "Can't join the server."));
          // Really usefull. The app can't catch this in "(err)" closure
          reject((err.statusText || "Can't join the server."));
          // This return is required to compile but unuseable in your app
          return Observable.throw(err);
        })
        // The (err) => {} param on subscribe can't catch server down error so I keep only the catch
        .subscribe(data => { resolve(data) })
    })
  }
}

In the app :

this.itemService.toSaveItem(item).then(
  (res) => { console.log('success', res) },
  (err) => { console.log('error', err) }
)

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))

RecyclerView - Get view at particular position

You can use use both

recyclerViewInstance.findViewHolderForAdapterPosition(adapterPosition) and recyclerViewInstance.findViewHolderForLayoutPosition(layoutPosition). Be sure that RecyclerView view uses two type of positions

Adapter position : Position of an item in the adapter. This is the position from the Adapter's perspective. Layout position : Position of an item in the latest layout calculation. This is the position from the LayoutManager's perspective. You should use getAdapterPosition() for findViewHolderForAdapterPosition(adapterPosition) and getLayoutPosition() for findViewHolderForLayoutPosition(layoutPosition).

Take a member variable to hold previously selected item position in recyclerview adapter and other member variable to check whether user is clicking for first time or not.

Sample code and screen shots are attached for more information at the bottom.

public class MainActivity extends AppCompatActivity {     

private RecyclerView mRecyclerList = null;    
private RecyclerAdapter adapter = null;    

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

    mRecyclerList = (RecyclerView) findViewById(R.id.recyclerList);    
}    

@Override    
protected void onStart() {    
    RecyclerView.LayoutManager layoutManager = null;    
    String[] daysArray = new String[15];    
    String[] datesArray = new String[15];    

    super.onStart();    
    for (int i = 0; i < daysArray.length; i++){    
        daysArray[i] = "Sunday";    
        datesArray[i] = "12 Feb 2017";    
    }    

    adapter = new RecyclerAdapter(mRecyclerList, daysArray, datesArray);    
    layoutManager = new LinearLayoutManager(MainActivity.this);    
    mRecyclerList.setAdapter(adapter);    
    mRecyclerList.setLayoutManager(layoutManager);    
}    
}    


public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyCardViewHolder>{          

private final String TAG = "RecyclerAdapter";        
private Context mContext = null;        
private TextView mDaysTxt = null, mDateTxt = null;    
private LinearLayout mDateContainerLayout = null;    
private String[] daysArray = null, datesArray = null;    
private RecyclerView mRecyclerList = null;    
private int previousPosition = 0;    
private boolean flagFirstItemSelected = false;    

public RecyclerAdapter(RecyclerView mRecyclerList, String[] daysArray, String[] datesArray){    
    this.mRecyclerList = mRecyclerList;    
    this.daysArray = daysArray;    
    this.datesArray = datesArray;    
}    

@Override    
public MyCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    
    LayoutInflater layoutInflater = null;    
    View view = null;    
    MyCardViewHolder cardViewHolder = null;    
    mContext = parent.getContext();    
    layoutInflater = LayoutInflater.from(mContext);    
    view = layoutInflater.inflate(R.layout.date_card_row, parent, false);    
    cardViewHolder = new MyCardViewHolder(view);    
    return cardViewHolder;    
}    

@Override    
public void onBindViewHolder(MyCardViewHolder holder, final int position) {    
    mDaysTxt = holder.mDaysTxt;    
    mDateTxt = holder.mDateTxt;    
    mDateContainerLayout = holder.mDateContainerLayout;    

    mDaysTxt.setText(daysArray[position]);    
    mDateTxt.setText(datesArray[position]);    

    if (!flagFirstItemSelected){    
        mDateContainerLayout.setBackgroundColor(Color.GREEN);    
        flagFirstItemSelected = true;    
    }else {    
        mDateContainerLayout.setBackground(null);    
    }    
}    

@Override    
public int getItemCount() {    
    return daysArray.length;    
}    

class MyCardViewHolder extends RecyclerView.ViewHolder{    
    TextView mDaysTxt = null, mDateTxt = null;    
    LinearLayout mDateContainerLayout = null;    
    LinearLayout linearLayout = null;    
    View view = null;    
    MyCardViewHolder myCardViewHolder = null;    

    public MyCardViewHolder(View itemView) {    
        super(itemView);    
        mDaysTxt = (TextView) itemView.findViewById(R.id.daysTxt);    
        mDateTxt = (TextView) itemView.findViewById(R.id.dateTxt);    
        mDateContainerLayout = (LinearLayout) itemView.findViewById(R.id.dateContainerLayout);    

        mDateContainerLayout.setOnClickListener(new View.OnClickListener() {    
            @Override    
            public void onClick(View v) {    
                LinearLayout linearLayout = null;    
                View view = null;    

                if (getAdapterPosition() == previousPosition){    
                    view = mRecyclerList.findViewHolderForAdapterPosition(previousPosition).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackgroundColor(Color.GREEN);    
                    previousPosition = getAdapterPosition();    

                }else {    
                    view = mRecyclerList.findViewHolderForAdapterPosition(previousPosition).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackground(null);    

                    view = mRecyclerList.findViewHolderForAdapterPosition(getAdapterPosition()).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackgroundColor(Color.GREEN);    
                    previousPosition = getAdapterPosition();    
                }    
            }    
        });    
    }    
}       

} first element selected second element selected and previously selected item becomes unselected fifth element selected and previously selected item becomes unselected

Get JSON Data from URL Using Android?

Don't know about android but in POJ I use

public final class MyJSONObject extends JSONObject {
    public MyJSONObject(URL url) throws IOException {
        super(getServerData(url));
    }
    static String getServerData(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String text = ir.lines().collect(Collectors.joining("\n"));
        return (text);
    }
}

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

Laravel 5: Retrieve JSON array from $request

You can use getContent() method on Request object.

$request->getContent() //json as a string.

Mongoose: findOneAndUpdate doesn't return updated document

Why this happens?

The default is to return the original, unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: an object with the new property set to true.

From the mongoose docs:

Query#findOneAndUpdate

Model.findOneAndUpdate(conditions, update, options, (error, doc) => {
  // error: any errors that occurred
  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
});

Available options

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

Solution

Pass {new: true} if you want the updated result in the doc variable:

//                                                         V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

Get div's offsetTop positions in React

Eugene's answer uses the correct function to get the data, but for posterity I'd like to spell out exactly how to use it in React v0.14+ (according to this answer):

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var rect = ReactDOM.findDOMNode(this)
      .getBoundingClientRect()
  }

Is working for me perfectly, and I'm using the data to scroll to the top of the new component that just mounted.

How to get docker-compose to always re-create containers from fresh images?

docker-compose up --build

OR

docker-compose build --no-cache

Simple way to measure cell execution time in ipython notebook

When in trouble what means what:

?%timeit or ??timeit

To get the details:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

How to define constants in ReactJS

Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases

You can use ES7 statics:

npm install babel-preset-stage-0

And then add "stage-0" to .babelrc presets:

{
    "presets": ["es2015", "react", "stage-0"]
}

Afterwards, you go

class Component extends React.Component {
    static foo = 'bar';
    static baz = {a: 1, b: 2}
}

And then you use them like this:

Component.foo

Change the location of the ~ directory in a Windows install of Git Bash

So, $HOME is what I need to modify. However I have been unable to find where this mythical $HOME variable is set so I assumed it was a Linux system version of PATH or something. Anyway...**

Answer

Adding HOME at the top of the profile file worked.

HOME="c://path/to/custom/root/".

  #THE FIX WAS ADDING THE FOLLOWING LINE TO THE TOP OF THE PROFILE FILE

  HOME="c://path/to/custom/root/"

  # below are the original contents ===========
  # To the extent possible under law, ..blah blah

  # Some resources...
  # Customizing Your Shell: http://www.dsl.org/cookbook/cookbook_5.html#SEC69
  # Consistent BackSpace and Delete Configuration:
  #   http://www.ibb.net/~anne/keyboard.html
  # The Linux Documentation Project: http://www.tldp.org/
  # The Linux Cookbook: http://www.tldp.org/LDP/linuxcookbook/html/
  # Greg's Wiki http://mywiki.wooledge.org/

  # Setup some default paths. Note that this order will allow user installed
  # software to override 'system' software.
  # Modifying these default path settings can be done in different ways.
  # To learn more about startup files, refer to your shell's man page.

  MSYS2_PATH="/usr/local/bin:/usr/bin:/bin"
  MANPATH="/usr/local/man:/usr/share/man:/usr/man:/share/man:${MANPATH}"
  INFOPATH="/usr/local/info:/usr/share/info:/usr/info:/share/info:${INFOPATH}"
  MINGW_MOUNT_POINT=
  if [ -n "$MSYSTEM" ]
  then
    case "$MSYSTEM" in
      MINGW32)
        MINGW_MOUNT_POINT=/mingw32
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MINGW64)
        MINGW_MOUNT_POINT=/mingw64
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MSYS)
        PATH="${MSYS2_PATH}:/opt/bin:${PATH}"
        PKG_CONFIG_PATH="/usr/lib/pkgconfig:/usr/share/pkgconfig:/lib/pkgconfig"
      ;;
      *)
        PATH="${MSYS2_PATH}:${PATH}"
      ;;
    esac
  else
    PATH="${MSYS2_PATH}:${PATH}"
  fi

  MAYBE_FIRST_START=false
  SYSCONFDIR="${SYSCONFDIR:=/etc}"

  # TMP and TEMP as defined in the Windows environment must be kept
  # for windows apps, even if started from msys2. However, leaving
  # them set to the default Windows temporary directory or unset
  # can have unexpected consequences for msys2 apps, so we define
  # our own to match GNU/Linux behaviour.
  ORIGINAL_TMP=$TMP
  ORIGINAL_TEMP=$TEMP
  #unset TMP TEMP
  #tmp=$(cygpath -w "$ORIGINAL_TMP" 2> /dev/null)
  #temp=$(cygpath -w "$ORIGINAL_TEMP" 2> /dev/null)
  #TMP="/tmp"
  #TEMP="/tmp"
  case "$TMP" in *\\*) TMP="$(cygpath -m "$TMP")";; esac
  case "$TEMP" in *\\*) TEMP="$(cygpath -m "$TEMP")";; esac
  test -d "$TMPDIR" || test ! -d "$TMP" || {
    TMPDIR="$TMP"
    export TMPDIR
  }


  # Define default printer
  p='/proc/registry/HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/Windows/Device'
  if [ -e "${p}" ] ; then
    read -r PRINTER < "${p}"
    PRINTER=${PRINTER%%,*}
  fi
  unset p

  print_flags ()
  {
    (( $1 & 0x0002 )) && echo -n "binary" || echo -n "text"
    (( $1 & 0x0010 )) && echo -n ",exec"
    (( $1 & 0x0040 )) && echo -n ",cygexec"
    (( $1 & 0x0100 )) && echo -n ",notexec"
  }

  # Shell dependent settings
  profile_d ()
  {
    local file=
    for file in $(export LC_COLLATE=C; echo /etc/profile.d/*.$1); do
      [ -e "${file}" ] && . "${file}"
    done

    if [ -n ${MINGW_MOUNT_POINT} ]; then
      for file in $(export LC_COLLATE=C; echo ${MINGW_MOUNT_POINT}/etc/profile.d/*.$1); do
        [ -e "${file}" ] && . "${file}"
      done
    fi
  }

  for postinst in $(export LC_COLLATE=C; echo /etc/post-install/*.post); do
    [ -e "${postinst}" ] && . "${postinst}"
  done

  if [ ! "x${BASH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    [ -f "/etc/bash.bashrc" ] && . "/etc/bash.bashrc"
  elif [ ! "x${KSH_VERSION}" = "x" ]; then
    typeset -l HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1=$(print '\033]0;${PWD}\n\033[32m${USER}@${HOSTNAME} \033[33m${PWD/${HOME}/~}\033[0m\n$ ')
  elif [ ! "x${ZSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d zsh
    PS1='(%n@%m)[%h] %~ %% '
  elif [ ! "x${POSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    PS1="$ "
  else
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1="$ "
  fi

  if [ -n "$ACLOCAL_PATH" ]
  then
    export ACLOCAL_PATH
  fi

  export PATH MANPATH INFOPATH PKG_CONFIG_PATH USER TMP TEMP PRINTER HOSTNAME PS1 SHELL tmp temp
  test -n "$TERM" || export TERM=xterm-256color

  if [ "$MAYBE_FIRST_START" = "true" ]; then
    sh /usr/bin/regen-info.sh

    if [ -f "/usr/bin/update-ca-trust" ]
    then
      sh /usr/bin/update-ca-trust
    fi

    clear
    echo
    echo
    echo "###################################################################"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "#                   C   A   U   T   I   O   N                     #"
    echo "#                                                                 #"
    echo "#                  This is first start of MSYS2.                  #"
    echo "#       You MUST restart shell to apply necessary actions.        #"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "###################################################################"
    echo
    echo
  fi
  unset MAYBE_FIRST_START

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

Run these two commands on root of laravel

find * -type d -print0 | xargs -0 chmod 0755 # for directories

find . -type f -print0 | xargs -0 chmod 0644 # for files

Scikit-learn train_test_split with indices

You can use pandas dataframes or series as Julien said but if you want to restrict your-self to numpy you can pass an additional array of indices:

from sklearn.model_selection import train_test_split
import numpy as np
n_samples, n_features, n_classes = 10, 2, 2
data = np.random.randn(n_samples, n_features)  # 10 training examples
labels = np.random.randint(n_classes, size=n_samples)  # 10 labels
indices = np.arange(n_samples)
x1, x2, y1, y2, idx1, idx2 = train_test_split(
    data, labels, indices, test_size=0.2)

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

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

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

Option b) Install in your homedir:

pip install --user -r requirements.txt

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

How to use confirm using sweet alert?

You need To use then() function, like this

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!"
 }).then(
       function () { /*Your Code Here*/ },
       function () { return false; });

When do I use path params vs. query params in a RESTful API?

Example URL: /rest/{keyword}

This URL is an example for path parameters. We can get this URL data by using @PathParam.

Example URL: /rest?keyword=java&limit=10

This URL is an example for query parameters. We can get this URL data by using @Queryparam.

Sending cookies with postman

I used postman chrome extension until it became deprecated. Chrome extension also less usable and powerful then native postman application. So, it became not very convenient to use chrome extension. I have found next approach:

  1. copy any request in chrome/any other browser as CURL request (image 1)
  2. import to postman copied request (image 2)
  3. save imported request in postman's list

copy curl request image 1

enter image description here image 2

Delete the last two characters of the String

An alternative solution would be to use some sort of regex:

for example:

    String s = "apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16";
    String results=  s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
    System.out.println(results); // output 9
    System.out.println(results.length());// output "apple car"

MySQL user DB does not have password columns - Installing MySQL on OSX

Root Cause: root has no password, and your python connect statement should reflect that.

To solve error 1698, change your python connect password to ''.

note: manually updating the user's password will not solve the problem, you will still get error 1698

Authentication failed because remote party has closed the transport stream

Adding the below code helped me overcome the issue.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout) Check it.

Handling errors in Promise.all

That's how Promise.all is designed to work. If a single promise reject()'s, the entire method immediately fails.

There are use cases where one might want to have the Promise.all allowing for promises to fail. To make this happen, simply don't use any reject() statements in your promise. However, to ensure your app/script does not freeze in case any single underlying promise never gets a response, you need to put a timeout on it.

function getThing(uid,branch){
    return new Promise(function (resolve, reject) {
        xhr.get().then(function(res) {
            if (res) {
                resolve(res);
            } 
            else {
                resolve(null);
            }
            setTimeout(function(){reject('timeout')},10000)
        }).catch(function(error) {
            resolve(null);
        });
    });
}

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

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

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

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

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

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

const isEqualSet = (a, b) => {
  const unionSize = new Set([...a, ...b])
  return unionSize === a.length && unionSize === b.length
}

rebase in progress. Cannot commit. How to proceed or stop (abort)?

  • Step 1: Keep going git rebase --continue

  • Step 2: fix CONFLICTS then git add .

  • Back to step 1, now if it says no changes .. then run git rebase --skip and go back to step 1

  • If you just want to quit rebase run git rebase --abort

  • Once all changes are done run git commit -m "rebase complete" and you are done.


Note: If you don't know what's going on and just want to go back to where the repo was, then just do:

git rebase --abort

Read about rebase: git-rebase doc

Visual Studio 2015 or 2017 does not discover unit tests

Popping in to share my solution. I was on Windows 10, Visual Studio 2015, NUnit 3.5, NUnit Test Adapter 3.6 (via NuGet, not the VISX extension) and none of my tests were being discovered. My problem was that in the Tests project of my solution, somehow a shortcut to my "Documents" folder had been created within the project folder. I'm guessing the test adapter was seeing the shortcut and getting hung up trying to figure out what to do with it, resulting in the failure to display unit tests.

Cancel a vanilla ECMAScript 6 Promise chain

Using CPromise package we can use the following approach (Live demo)

import CPromise from "c-promise2";

const chain = new CPromise((resolve, reject, { onCancel }) => {
  const timer = setTimeout(resolve, 1000, 123);
  onCancel(() => clearTimeout(timer));
})
  .then((value) => value + 1)
  .then(
    (value) => console.log(`Done: ${value}`),
    (err, scope) => {
      console.warn(err); // CanceledError: canceled
      console.log(`isCanceled: ${scope.isCanceled}`); // true
    }
  );

setTimeout(() => {
  chain.cancel();
}, 100);

The same thing using AbortController (Live demo)

import CPromise from "c-promise2";

const controller= new CPromise.AbortController();

new CPromise((resolve, reject, { onCancel }) => {
  const timer = setTimeout(resolve, 1000, 123);
  onCancel(() => clearTimeout(timer));
})
  .then((value) => value + 1)
  .then(
    (value) => console.log(`Done: ${value}`),
    (err, scope) => {
      console.warn(err);
      console.log(`isCanceled: ${scope.isCanceled}`);
    }
  ).listen(controller.signal);

setTimeout(() => {
  controller.abort();
}, 100);

How to disable or enable viewpager swiping in android

For disabling swiping

mViewPager.beginFakeDrag();

For enable swiping

if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();

How can I encode a string to Base64 in Swift?

FOR SWIFT 3.0

let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")

let utf8str = str.data(using: String.Encoding.utf8)

if let base64Encoded = utf8str?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
{

  print("Encoded:  \(base64Encoded)")

  if let base64Decoded = NSData(base64Encoded: base64Encoded, options:   NSData.Base64DecodingOptions(rawValue: 0))
    .map({ NSString(data: $0 as Data, encoding: String.Encoding.utf8.rawValue) })
  {
    // Convert back to a string
    print("Decoded:  \(base64Decoded)!")
  }
}

Android java.exe finished with non-zero exit value 1

Had the same error encountered which was due to conflicting drawable resources. I did a clean project and the error was no longer encountered.

Adding value labels on a matplotlib bar chart

If you only want to add Datapoints above the bars, you could easily do it with:

 for i in range(len(frequencies)): # your number of bars
    plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
    y = y_values[i]+1, #takes your y values as vertical positioning argument 
    s = data_labels[i], # the labels you want to add to the data
    size = 9) # font size of datalabels

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

The solution is pretty easy... Searched for it for a while and it turns out that you just have to edit 2 config-files:

  • /usr/my.cnf
  • /etc/mysql/my.cnf

in both files you'll have to add:

[mysqld]
...
sql_mode=NO_ENGINE_SUBSTITUTION

At least, that's what's working for 5.6.24-2+deb.sury.org~precise+2

How to change DatePicker dialog color for Android 5.0

try this, work for me

Put the two options, colorAccent and android:colorAccent

<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
   ....
    <item name="android:dialogTheme">@style/AppTheme.DialogTheme</item>
    <item name="android:datePickerDialogTheme">@style/Dialog.Theme</item>
</style>

<style name="AppTheme.DialogTheme" parent="Theme.AppCompat.Light.Dialog">

<!-- Put the two options, colorAccent and android:colorAccent. -->
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:colorPrimary">@color/colorPrimary</item>
    <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:colorAccent">@color/colorPrimary</item>
 </style>

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

Laravel Eloquent - distinct() and count() not working properly together

You can use the following way to get the unique data as per your need as follows,

$data = $ad->getcodes()->get()->unique('email');

$count = $data->count();

Hope this will work.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?

Essentially, the other script was doing:

let tables = $("table");
for (let i = 0; i < tables.length; i++) {
  const table = tables[i];
  if ($.fn.DataTable.isDataTable(table)) {
    $(table).DataTable().destroy(remove);
    $(table).empty();
  }
}

And it should have been doing:

let tables = $("table.some-class-only");
... the rest ...

Custom pagination view in Laravel 5

Laravel 5 ships with a Bootstrap 4 paginator if anyone needs it.

First create a new service provider.

php artisan make:provider PaginationServiceProvider

In the register method pass a closure to Laravel's paginator class that creates and returns the new presenter.

<?php


namespace App\Providers;

use Illuminate\Pagination\BootstrapFourPresenter;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class PaginationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        Paginator::presenter(function($paginator)
        {
            return new BootstrapFourPresenter($paginator);
        });
    }
}

Register the new provider in config/app.php

'providers' => [
    //....
    App\Providers\PaginationServiceProvider::class,
]

I found this example at Bootstrap 4 Pagination With Laravel

UICollectionView - dynamic cell height?

Swift 4.*

I have created a Xib for UICollectionViewCell which seems to be the good approach.

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return size(indexPath: indexPath)
    }

    private func size(for indexPath: IndexPath) -> CGSize {
        // load cell from Xib
        let cell = Bundle.main.loadNibNamed("ACollectionViewCell", owner: self, options: nil)?.first as! ACollectionViewCell

        // configure cell with data in it
        let data = self.data[indexPath.item]
        cell.configure(withData: data)

        cell.setNeedsLayout()
        cell.layoutIfNeeded()

        // width that you want
        let width = collectionView.frame.width
        let height: CGFloat = 0

        let targetSize = CGSize(width: width, height: height)

        // get size with width that you want and automatic height
        let size = cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .defaultHigh, verticalFittingPriority: .fittingSizeLevel)
        // if you want height and width both to be dynamic use below
        // let size = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)

        return size
    }
}

#note: I don't recommend setting image when configuring data in this size determining case. It gave me the distorted/unwanted result. Configuring texts only gave me below result.

enter image description here

Toolbar Navigation Hamburger Icon missing

ok to hide back arrow use

getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);

then find hamburger icon in web ->hamburger

and finally, set this drawable in your project with action bar method:

getSupportActionBar().setLogo(R.drawable.hamburger_icon);

Upload a file to Amazon S3 with NodeJS

Or Using promises:

const AWS = require('aws-sdk');
AWS.config.update({
    accessKeyId: 'accessKeyId',
    secretAccessKey: 'secretAccessKey',
    region: 'region'
});

let params = {
    Bucket: "yourBucketName",
    Key: 'someUniqueKey',
    Body: 'someFile'
};
try {
    let uploadPromise = await new AWS.S3().putObject(params).promise();
    console.log("Successfully uploaded data to bucket");
} catch (e) {
    console.log("Error uploading data: ", e);
}

httpd-xampp.conf: How to allow access to an external IP besides localhost?

I tried this and it works. Be careful though. This means that anyone in your LAN can access it. Deepak Naik's answer is safer.

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    # Require local
    Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

How to configure Docker port mapping to use Nginx as an upstream proxy?

Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.

Apply vs transform on a group object

As I felt similarly confused with .transform operation vs. .apply I found a few answers shedding some light on the issue. This answer for example was very helpful.

My takeout so far is that .transform will work (or deal) with Series (columns) in isolation from each other. What this means is that in your last two calls:

df.groupby('A').transform(lambda x: (x['C'] - x['D']))
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())

You asked .transform to take values from two columns and 'it' actually does not 'see' both of them at the same time (so to speak). transform will look at the dataframe columns one by one and return back a series (or group of series) 'made' of scalars which are repeated len(input_column) times.

So this scalar, that should be used by .transform to make the Series is a result of some reduction function applied on an input Series (and only on ONE series/column at a time).

Consider this example (on your dataframe):

zscore = lambda x: (x - x.mean()) / x.std() # Note that it does not reference anything outside of 'x' and for transform 'x' is one column.
df.groupby('A').transform(zscore)

will yield:

       C      D
0  0.989  0.128
1 -0.478  0.489
2  0.889 -0.589
3 -0.671 -1.150
4  0.034 -0.285
5  1.149  0.662
6 -1.404 -0.907
7 -0.509  1.653

Which is exactly the same as if you would use it on only on one column at a time:

df.groupby('A')['C'].transform(zscore)

yielding:

0    0.989
1   -0.478
2    0.889
3   -0.671
4    0.034
5    1.149
6   -1.404
7   -0.509

Note that .apply in the last example (df.groupby('A')['C'].apply(zscore)) would work in exactly the same way, but it would fail if you tried using it on a dataframe:

df.groupby('A').apply(zscore)

gives error:

ValueError: operands could not be broadcast together with shapes (6,) (2,)

So where else is .transform useful? The simplest case is trying to assign results of reduction function back to original dataframe.

df['sum_C'] = df.groupby('A')['C'].transform(sum)
df.sort('A') # to clearly see the scalar ('sum') applies to the whole column of the group

yielding:

     A      B      C      D  sum_C
1  bar    one  1.998  0.593  3.973
3  bar  three  1.287 -0.639  3.973
5  bar    two  0.687 -1.027  3.973
4  foo    two  0.205  1.274  4.373
2  foo    two  0.128  0.924  4.373
6  foo    one  2.113 -0.516  4.373
7  foo  three  0.657 -1.179  4.373
0  foo    one  1.270  0.201  4.373

Trying the same with .apply would give NaNs in sum_C. Because .apply would return a reduced Series, which it does not know how to broadcast back:

df.groupby('A')['C'].apply(sum)

giving:

A
bar    3.973
foo    4.373

There are also cases when .transform is used to filter the data:

df[df.groupby(['B'])['D'].transform(sum) < -1]

     A      B      C      D
3  bar  three  1.287 -0.639
7  foo  three  0.657 -1.179

I hope this adds a bit more clarity.

What's the proper way to "go get" a private repository?

I have created a user specific ssh-config, so my user automatically logs in with the correct credentials and key.

First I needed to generate an key-pair

ssh-keygen -t rsa -b 4096 -C "[email protected]"

and saved it to e.g ~/.ssh/id_my_domain. Note that this is also the keypair (private and public) I've connected to my Github account, so mine is stored in~/.ssh/id_github_com.

I have then created (or altered) a file called ~/.ssh/config with an entry:

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_github_com

On another server, the "ssh-url" is [email protected]:username/private-repo.git and the entry for this server would have been:

Host domain.com
    HostName domain.com
    User admin
    IdentityFile ~/.ssh/id_domain_com

Just to clarify that you need ensure that the User, Host and HostName is set correctly.

Now I can just browse into the go path and then go get <package>, e.g go get main where the file main/main.go includes the package (from last example above) domain.com:username/private-repo.git.

Postgres: How to convert a json string to text?

In 9.4.4 using the #>> operator works for me:

select to_json('test'::text) #>> '{}';

To use with a table column:

select jsoncol #>> '{}' from mytable;

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

I encountered the same problem with a nexus 5 Android Lollipop 5.0.1:

Installation error: INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.android.** pkg=com.android.**

And in my case I couldn't fix this problem uninstalling the app because it was an android app, but I had to change my app custom permissions name in manifest because they were the same as an android app, which I could not uninstall or do any change.

Hope this helps somebody!

Powershell: count members of a AD group

The Get-ADGroupMember cmdlet would solve this in a much more efficient way than you're tying.

As an example:

$users = Get-ADGroupMember -Identity 'Group Name'
$users.count
132

EDIT:

In order to clarify things, and to make your script simpler. Here's a generic script that will work for your environment that outputs the user count for each group matching your filters.

$groups = Get-ADGroup -filter {(name -like "WA*") -or (name -like "workstation*")}
foreach($group in $groups){
  $countUser = (Get-ADGroupMember $group.DistinguishedName).count
  Write-Host "The group $($group.Name) has $countUser user(s)."
}

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

Since this is the first Google result for 'pandas new column from others', here's a simple example:

import pandas as pd

# make a simple dataframe
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
df
#    a  b
# 0  1  3
# 1  2  4

# create an unattached column with an index
df.apply(lambda row: row.a + row.b, axis=1)
# 0    4
# 1    6

# do same but attach it to the dataframe
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)
df
#    a  b  c
# 0  1  3  4
# 1  2  4  6

If you get the SettingWithCopyWarning you can do it this way also:

fn = lambda row: row.a + row.b # define a function for the new column
col = df.apply(fn, axis=1) # get column data with an index
df = df.assign(c=col.values) # assign values to column 'c'

Source: https://stackoverflow.com/a/12555510/243392

And if your column name includes spaces you can use syntax like this:

df = df.assign(**{'some column name': col.values})

And here's the documentation for apply, and assign.

An unhandled exception occurred during the execution of the current web request. ASP.NET

Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.

Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.

Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)

Good luck.

ng-change get new value and original value

Also you can use

<select ng-change="updateValue(user, oldValue)"     
       ng-init="oldValue=0"
       ng-focus="oldValue=user.id"
       ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

Array formula on Excel for Mac

CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!

Android: making a fullscreen application

Add these to Activity of your application.

Android JAVA

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  WindowManager.LayoutParams.FLAG_FULLSCREEN)

;

Android Kotlin

supportActionBar?.hide()
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)

Touch move getting stuck Ignored attempt to cancel a touchmove

The event must be cancelable. Adding an if statement solves this issue.

if (e.cancelable) {
   e.preventDefault();
}

In your code you should put it here:

if (this.isSwipe(swipeThreshold) && e.cancelable) {
   e.preventDefault();
   e.stopPropagation();
   swiping = true;
}

Swift apply .uppercaseString to only the first letter of a string

I'm partial to this version, which is a cleaned up version from another answer:

extension String {
  var capitalizedFirst: String {
    let characters = self.characters
    if let first = characters.first {
      return String(first).uppercased() + 
             String(characters.dropFirst())
    }
    return self
  }
}

It strives to be more efficient by only evaluating self.characters once, and then uses consistent forms to create the sub-strings.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is for my reference, as I encountered a variety of SQL error messages while trying to connect with provider. Other answers prescribe "try this, then this, then this". I appreciate the other answers, but I like to pair specific solutions with specific problems


Error

...provider did not give information...Cannot initialize data source object...

Error Numbers

7399, 7303

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  The provider did not give any information about the error. 
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object
  of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

File was open. Close it.

Credit


Error

Access denied...Cannot get the column information...

Error Numbers

7399, 7350

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  Access denied.
Msg 7350, Level 16, State 2, Line 2 Cannot get the column information 
  from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Give access

Credit


Error

No value given for one or more required parameters....Cannot execute the query ...

Error Numbers

???, 7320

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "No value given for one or more required parameters.".
Msg 7320, Level 16, State 2, Line 2
Cannot execute the query "select [Col A], [Col A] FROM $Sheet" against OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". 

Solution

Column names might be wrong. Do [Col A] and [Col B] actually exist in your spreadsheet?


Error

"Unspecified error"...Cannot initialize data source object...

Error Numbers

???, 7303

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Run SSMS as admin. See this question.


Other References

Other answers which suggest modifying properties. Not sure how modifying these two properties (checking them or unchecking them) would help.

How to merge a Series and DataFrame

You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:

In [27]:

df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:

df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)

This assumes that the indices match the length.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

Move view with keyboard using Swift

I made a cocoapod to simplify the matter:

https://github.com/xtrinch/KeyboardLayoutHelper

How to use it:

Make an auto layout bottom constraint, give it a class of KeyboardLayoutConstraint in module KeyboardLayoutHelper and the pod will do the work necessary to increase it to accomodate appearing and disappearing keyboard. See example project on examples how to use it (I made two: textFields inside a scrollView, and vertically centered textFields with two basic views - login & register).

The bottom layout constraint can be of the container view, the textField itself, anything, you name it.

How to mount host volumes into docker containers in Dockerfile during build

First, to answer "why doesn't VOLUME work?" When you define a VOLUME in the Dockerfile, you can only define the target, not the source of the volume. During the build, you will only get an anonymous volume from this. That anonymous volume will be mounted at every RUN command, prepopulated with the contents of the image, and then discarded at the end of the RUN command. Only changes to the container are saved, not changes to the volume.


Since this question has been asked, a few features have been released that may help. First is multistage builds allowing you to build a disk space inefficient first stage, and copy just the needed output to the final stage that you ship. And the second feature is Buildkit which is dramatically changing how images are built and new capabilities are being added to the build.

For a multi-stage build, you would have multiple FROM lines, each one starting the creation of a separate image. Only the last image is tagged by default, but you can copy files from previous stages. The standard use is to have a compiler environment to build a binary or other application artifact, and a runtime environment as the second stage that copies over that artifact. You could have:

FROM debian:sid as builder
COPY export /export
RUN compile command here >/result.bin

FROM debian:sid
COPY --from=builder /result.bin /result.bin
CMD ["/result.bin"]

That would result in a build that only contains the resulting binary, and not the full /export directory.


Buildkit is coming out of experimental in 18.09. It's a complete redesign of the build process, including the ability to change the frontend parser. One of those parser changes has has implemented the RUN --mount option which lets you mount a cache directory for your run commands. E.g. here's one that mounts some of the debian directories (with a reconfigure of the debian image, this could speed up reinstalls of packages):

# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/var/lib/apt/lists,type=cache \
    --mount=target=/var/cache/apt,type=cache \
    apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      git

You would adjust the cache directory for whatever application cache you have, e.g. $HOME/.m2 for maven, or /root/.cache for golang.


TL;DR: Answer is here: With that RUN --mount syntax, you can also bind mount read-only directories from the build-context. The folder must exist in the build context, and it is not mapped back to the host or the build client:

# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/export,type=bind,source=export \
    process export directory here...

Note that because the directory is mounted from the context, it's also mounted read-only, and you cannot push changes back to the host or client. When you build, you'll want an 18.09 or newer install and enable buildkit with export DOCKER_BUILDKIT=1.

If you get an error that the mount flag isn't supported, that indicates that you either didn't enable buildkit with the above variable, or that you didn't enable the experimental syntax with the syntax line at the top of the Dockerfile before any other lines, including comments. Note that the variable to toggle buildkit will only work if your docker install has buildkit support built in, which requires version 18.09 or newer from Docker, both on the client and server.

Converting file into Base64String and back again

For Java, consider using Apache Commons FileUtils:

/**
 * Convert a file to base64 string representation
 */
public String fileToBase64(File file) throws IOException {
    final byte[] bytes = FileUtils.readFileToByteArray(file);
    return Base64.getEncoder().encodeToString(bytes);
}

/**
 * Convert base64 string representation to a file
 */
public void base64ToFile(String base64String, String filePath) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}

Uses for the '&quot;' entity in HTML

Reason #1

There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.

Reason #2

When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars() function is one such example. Though there are optional arguments to htmlspecialchars() that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.

Comparing the contents of two files in Sublime Text

UPDATE JAN 2018 - especially for Sublime/Mac

(This is very similar to Marty F's reply, but addresses some issues from previous responses, combines several different suggestions and discusses the critical distinction that gave me problems at first.)

I'm using Sublime Text 3 (build 3143) on Mac and have been trying for about 30 minutes to find this File Compare feature. I had used it before on Sublime/Mac without any problems, but this time, it was trickier. But, I finally figured it out.

  1. The file format does not need to be UTF-8. I have successfully compared files that are UTF-8, ISO-8559-1, and Windows-1252.

  2. There is no File > Open Folders on Sublime/Mac. Many instructions above start with "Select File > Open Folders," but that doesn't exist on Sublime/Mac.

  3. File compare works on a Project basis. If you want to compare two files, they must be saved to disk and part of the current project.

  4. Ways to open a project

  • If Sublime/Mac is not running or if it's running but no windows are open, drag a folder onto the Sublime app.
  • If Sublime/Mac is running, select "File > Open", navigate to the desired folder, don't select a file or folder and click "Open".
  1. Add a folder to a project. If the files you want to compare are not part of the same hierarchy, first open the folder containing one of the files. Then, select "Project > Add Folder to Project", navigate to the folder you want and click "Open". You will now see two root-level folders in your sidebar.

  2. The Sidebar must be visible. You can either "View > Side Bar > Show Side Bar" or use the shortcut, Command-K, Command-B.

  3. Files must be closed (ie, saved) to compare. Single-clicking a file in the Side Bar does not open the file, but it does display it. You can tell if a file is open if it's listed in the "Open Files" section at the top of the Side Bar. Double-clicking a file or making a modification to a file will automatically change a file's status to "Open". In this case, be sure to close it before trying to compare.

  4. Select files from the folder hierarchy. Standard Mac shorcut here, (single) click the first file, then Command-click the second file. When you select the first file, you'll see its contents, but it's not open. Then, when you Command-click the second file, you'll see its contents, but again, neither are open. You'll notice only one tab in the editing panel.

  5. Control-click is not the same as right-click. This was the one that got me. I use my trackpad and often resort to Control-click as a right-click or secondary-click. This does not work for me. However, since I configured my trackpad in System Preferences to use the bottom-right corner of my trackpad as a right-click, that worked, displaying the contextual menu, with "Delete", "Reveal in Finder", and.... "Diff Files..."

Voilà!

git am error: "patch does not apply"

This kind of error can be caused by LF vs CRLF line ending mismatches, e.g. when you're looking at the patch file and you're absolutely sure it should be able to apply, but it just won't.

To test this out, if you have a patch that applies to just one file, you can try running 'unix2dos' or 'dos2unix' on just that file (try both, to see which one causes the file to change; you can get these utilities for Windows as well as Unix), then commit that change as a test commit, then try applying the patch again. If that works, that was the problem.

NB git am applies patches as LF by default (even if the patch file contains CRLF), so if you want to apply CRLF patches to CRLF files you must use git am --keep-cr, as per this answer.

Replace Div Content onclick

A Third Answer

Sorry, maybe I have it correct this time...

jsFiddle Demo

var savedBox1, savedBox2, state1=0, state2=0;

jQuery(document).ready(function() {
    jQuery(".rec1").click(function() {
        if (state1==0){
            savedBox1 = jQuery('#rec-box').html();
            jQuery('#rec-box').html(jQuery(this).next().html()); 
            state1 = 1;
        }else{
            jQuery('#rec-box').html(savedBox1); 
            state1 = 0;
        }
    });

    jQuery(".rec2").click(function() {
        if (state1==0){
            savedBox2 = jQuery('#rec-box2').html();
            jQuery('#rec-box2').html(jQuery(this).next().html()); 
            state2 = 1;
        }else{
            jQuery('#rec-box2').html(savedBox2); 
            state2 = 0;
        }
    });
});

How can I remove an SSH key?

Note that there are at least two bug reports for ssh-add -d/-D not removing keys:

The exact issue is:

ssh-add -d/-D deletes only manually added keys from gnome-keyring.
There is no way to delete automatically added keys.
This is the original bug, and it's still definitely present.

So, for example, if you have two different automatically-loaded ssh identities associated with two different GitHub accounts -- say for work and for home -- there's no way to switch between them. GitHubtakes the first one which matches, so you always appear as your 'home' user to GitHub, with no way to upload things to work projects.

Allowing ssh-add -d to apply to automatically-loaded keys (and ssh-add -t X to change the lifetime of automatically-loaded keys), would restore the behavior most users expect.


More precisely, about the issue:

The culprit is gpg-keyring-daemon:

  • It subverts the normal operation of ssh-agent, mostly just so that it can pop up a pretty box into which you can type the passphrase for an encrypted ssh key.
  • And it paws through your .ssh directory, and automatically adds any keys it finds to your agent.
  • And it won't let you delete those keys.

How do we hate this? Let's not count the ways -- life's too short.

The failure is compounded because newer ssh clients automatically try all the keys in your ssh-agent when connecting to a host.
If there are too many, the server will reject the connection.
And since gnome-keyring-daemon has decided for itself how many keys you want your ssh-agent to have, and has autoloaded them, AND WON'T LET YOU DELETE THEM, you're toast.

This bug is still confirmed in Ubuntu 14.04.4, as recently as two days ago (August 21st, 2014)


A possible workaround:

  • Do ssh-add -D to delete all your manually added keys. This also locks the automatically added keys, but is not much use since gnome-keyring will ask you to unlock them anyways when you try doing a git push.
  • Navigate to your ~/.ssh folder and move all your key files except the one you want to identify with into a separate folder called backup. If necessary you can also open seahorse and delete the keys from there.
  • Now you should be able to do git push without a problem.

Another workaround:

What you really want to do is to turn off gpg-keyring-daemon altogether.
Go to System --> Preferences --> Startup Applications, and unselect the "SSH Key Agent (Gnome Keyring SSH Agent)" box -- you'll need to scroll down to find it.

You'll still get an ssh-agent, only now it will behave sanely: no keys autoloaded, you run ssh-add to add them, and if you want to delete keys, you can. Imagine that.

This comments actually suggests:

The solution is to keep gnome-keyring-manager from ever starting up, which was strangely difficult by finally achieved by removing the program file's execute permission.


Ryan Lue adds another interesting corner case in the comments:

In case this helps anyone: I even tried deleting the id_rsa and id_rsa.pub files altogether, and the key was still showing up.

Turns out gpg-agent was caching them in a ~/.gnupg/sshcontrol file; I had to manually delete them from there.

That is the case when the keygrip has been added as in here.

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

just right click on your project, hover maven then click update project.. done!!

Simple pagination in javascript

enter image description here file:icons.svg

<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id="icon-triangle-left" viewBox="0 0 20 20">
<title>triangle-left</title>
<path d="M14 5v10l-9-5 9-5z"></path>
</symbol>
<symbol id="icon-triangle-right" viewBox="0 0 20 20">
<title>triangle-right</title>
<path d="M15 10l-9 5v-10l9 5z"></path>
</symbol>
</defs>
</svg>

file: style.css

 .results__btn--prev{
    float: left;
    flex-direction: row-reverse; }
  .results__btn--next{
    float: right; }

file index.html:

<body>
<form class="search">
                <input type="text" class="search__field" placeholder="Search over 1,000,000 recipes...">
                <button class="btn search__btn">
                    <svg class="search__icon">
                        <use href="img/icons.svg#icon-magnifying-glass"></use>
                    </svg>
                    <span>Search</span>
                </button>
            </form>
     <div class="results">
         <ul class="results__list">
         </ul>
         <div class="results__pages">
         </div>
     </div>
</body>

file: searchView.js

export const element = {
    searchForm:document.querySelector('.search'),
    searchInput: document.querySelector('.search__field'),
    searchResultList: document.querySelector('.results__list'),
    searchRes:document.querySelector('.results'),
    searchResPages:document.querySelector('.results__pages')

}
export const getInput = () => element.searchInput.value;
export const clearResults = () =>{
    element.searchResultList.innerHTML=``;
    element.searchResPages.innerHTML=``;
}
export const clearInput = ()=> element.searchInput.value = "";

const limitRecipeTitle = (title, limit=17)=>{
    const newTitle = [];
    if(title.length>limit){
        title.split(' ').reduce((acc, cur)=>{
            if(acc+cur.length <= limit){
                newTitle.push(cur);
            }
            return acc+cur.length;
        },0);
    }

    return `${newTitle.join(' ')} ...`
}
const renderRecipe = recipe =>{
    const markup = `
        <li>
            <a class="results__link" href="#${recipe.recipe_id}">
                <figure class="results__fig">
                    <img src="${recipe.image_url}" alt="${limitRecipeTitle(recipe.title)}">
                </figure>
                <div class="results__data">
                    <h4 class="results__name">${recipe.title}</h4>
                    <p class="results__author">${recipe.publisher}</p>
                </div>
            </a>
        </li>
    `;
    var htmlObject = document.createElement('div');
    htmlObject.innerHTML = markup;
    element.searchResultList.insertAdjacentElement('beforeend',htmlObject);
}

const createButton = (page, type)=>`

    <button class="btn-inline results__btn--${type}" data-goto=${type === 'prev'? page-1 : page+1}>
    <svg class="search__icon">
        <use href="img/icons.svg#icon-triangle-${type === 'prev'? 'left' : 'right'}}"></use>
    </svg>
    <span>Page ${type === 'prev'? page-1 : page+1}</span>
    </button>
`
const renderButtons = (page, numResults, resultPerPage)=>{
    const pages = Math.ceil(numResults/resultPerPage);
    let button;
    if(page == 1 && pages >1){
        //button to go to next page
        button = createButton(page, 'next');
    }else if(page<pages){
      //both buttons  
      button = `
      ${createButton(page, 'prev')}
      ${createButton(page, 'next')}`;


    }
    else if (page === pages && pages > 1){
        //Only button to go to prev page
        button = createButton(page, 'prev');
    }

    element.searchResPages.insertAdjacentHTML('afterbegin', button);
}
export const renderResults = (recipes, page=1, resultPerPage=10) =>{
    /*//recipes.foreach(el=>renderRecipe(el))
    //or foreach will automatically call the render recipes
    //recipes.forEach(renderRecipe)*/
    const start = (page-1)*resultPerPage;
    const end = page * resultPerPage;
    recipes.slice(start, end).forEach(renderRecipe);
    renderButtons(page, recipes.length, resultPerPage);
}

file: Search.js

export default class Search{
    constructor(query){
        this.query = query;
    }
    async getResults(){
        try{
            const res = await axios(`https://api.com/api/search?&q=${this.query}`);
            this.result = res.data.recipes;
            //console.log(this.result);
        }catch(error){
            alert(error);
        }
    }
}

file: Index.js

onst state = {};
const controlSearch = async()=>{
  const query = searchView.getInput();
  if (query){
    state.search = new Search(query); 
    searchView.clearResults();
    searchView.clearInput();
    await state.search.getResults();
    searchView.renderResults(state.search.result);
  }
}
//event listner to the parent object to delegate the event
element.searchForm.addEventListener('submit', event=>{
  console.log("submit search");
  event.preventDefault();
  controlSearch();
});

element.searchResPages.addEventListener('click', e=>{
  const btn = e.target.closest('.btn-inline');
  if(btn){
    const goToPage = parseInt(btn.dataset.goto, 10);//base 10
    searchView.clearResults();
    searchView.renderResults(state.search.result, goToPage);
  }
});

Dynamically add item to jQuery Select2 control that uses AJAX

I have resolved issue with the help of this link http://www.bootply.com/122726. hopefully will help you

Add option in select2 jquery and bind your ajax call with created link id(#addNew) for new option from backend. and the code

 $.getScript('http://ivaynberg.github.io/select2/select2-3.4.5/select2.js',function(){

  $("#mySel").select2({
    width:'240px',
    allowClear:true,
    formatNoMatches: function(term) {
        /* customize the no matches output */
        return "<input class='form-control' id='newTerm' value='"+term+"'><a href='#' id='addNew' class='btn btn-default'>Create</a>"
    }
  })
  .parent().find('.select2-with-searchbox').on('click','#addNew',function(){
    /* add the new term */
    var newTerm = $('#newTerm').val();
    //alert('adding:'+newTerm);
    $('<option>'+newTerm+'</option>').appendTo('#mySel');
    $('#mySel').select2('val',newTerm); // select the new term
    $("#mySel").select2('close');       // close the dropdown
  })

});



<div class="container">
    <h3>Select2 - Add new term when no search matches</h3>
    <select id="mySel">
        <option>One</option>
        <option>Two</option>
        <option>Three</option>
        <option>Four</option>
        <option>Five</option>
        <option>Six</option>
        <option>Twenty Four</option>
    </select>
    <br>
    <br>
</div>

Datatables: Cannot read property 'mData' of undefined

FYI dataTables requires a well formed table. It must contain <thead> and <tbody> tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.

The following will throw error (no <thead> and <tbody> tags)

<table id="sample-table">
    <tr>
        <th>title-1</th>
        <th>title-2</th>
    </tr>
    <tr>
        <td>data-1</td>
        <td>data-2</td>
    </tr>
</table>

The following will also throw an error (unequal number of columns)

<table id="sample-table">
    <thead>
        <tr>
            <th>title-1</th>
            <th>title-2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>data-1</td>
            <td>data-2</td>
            <td>data-3</td>
        </tr>
    </tbody>
</table>

For more info read more here

How do I use the includes method in lodash to check if an object is in the collection?

Supplementing the answer by p.s.w.g, here are three other ways of achieving this using lodash 4.17.5, without using _.includes():

Say you want to add object entry to an array of objects numbers, only if entry does not exist already.

let numbers = [
    { to: 1, from: 2 },
    { to: 3, from: 4 },
    { to: 5, from: 6 },
    { to: 7, from: 8 },
    { to: 1, from: 2 } // intentionally added duplicate
];

let entry = { to: 1, from: 2 };

/* 
 * 1. This will return the *index of the first* element that matches:
 */
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0


/* 
 * 2. This will return the entry that matches. Even if the entry exists
 *    multiple time, it is only returned once.
 */
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}


/* 
 * 3. This will return an array of objects containing all the matches.
 *    If an entry exists multiple times, if is returned multiple times.
 */
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]

If you want to return a Boolean, in the first case, you can check the index that is being returned:

_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Culprit: False Data Dependency (and the compiler isn't even aware of it)

On Sandy/Ivy Bridge and Haswell processors, the instruction:

popcnt  src, dest

appears to have a false dependency on the destination register dest. Even though the instruction only writes to it, the instruction will wait until dest is ready before executing. This false dependency is (now) documented by Intel as erratum HSD146 (Haswell) and SKL029 (Skylake)

Skylake fixed this for lzcnt and tzcnt.
Cannon Lake (and Ice Lake) fixed this for popcnt.
bsf/bsr have a true output dependency: output unmodified for input=0. (But no way to take advantage of that with intrinsics - only AMD documents it and compilers don't expose it.)

(Yes, these instructions all run on the same execution unit).


This dependency doesn't just hold up the 4 popcnts from a single loop iteration. It can carry across loop iterations making it impossible for the processor to parallelize different loop iterations.

The unsigned vs. uint64_t and other tweaks don't directly affect the problem. But they influence the register allocator which assigns the registers to the variables.

In your case, the speeds are a direct result of what is stuck to the (false) dependency chain depending on what the register allocator decided to do.

  • 13 GB/s has a chain: popcnt-add-popcnt-popcnt → next iteration
  • 15 GB/s has a chain: popcnt-add-popcnt-add → next iteration
  • 20 GB/s has a chain: popcnt-popcnt → next iteration
  • 26 GB/s has a chain: popcnt-popcnt → next iteration

The difference between 20 GB/s and 26 GB/s seems to be a minor artifact of the indirect addressing. Either way, the processor starts to hit other bottlenecks once you reach this speed.


To test this, I used inline assembly to bypass the compiler and get exactly the assembly I want. I also split up the count variable to break all other dependencies that might mess with the benchmarks.

Here are the results:

Sandy Bridge Xeon @ 3.5 GHz: (full test code can be found at the bottom)

  • GCC 4.6.3: g++ popcnt.cpp -std=c++0x -O3 -save-temps -march=native
  • Ubuntu 12

Different Registers: 18.6195 GB/s

.L4:
    movq    (%rbx,%rax,8), %r8
    movq    8(%rbx,%rax,8), %r9
    movq    16(%rbx,%rax,8), %r10
    movq    24(%rbx,%rax,8), %r11
    addq    $4, %rax

    popcnt %r8, %r8
    add    %r8, %rdx
    popcnt %r9, %r9
    add    %r9, %rcx
    popcnt %r10, %r10
    add    %r10, %rdi
    popcnt %r11, %r11
    add    %r11, %rsi

    cmpq    $131072, %rax
    jne .L4

Same Register: 8.49272 GB/s

.L9:
    movq    (%rbx,%rdx,8), %r9
    movq    8(%rbx,%rdx,8), %r10
    movq    16(%rbx,%rdx,8), %r11
    movq    24(%rbx,%rdx,8), %rbp
    addq    $4, %rdx

    # This time reuse "rax" for all the popcnts.
    popcnt %r9, %rax
    add    %rax, %rcx
    popcnt %r10, %rax
    add    %rax, %rsi
    popcnt %r11, %rax
    add    %rax, %r8
    popcnt %rbp, %rax
    add    %rax, %rdi

    cmpq    $131072, %rdx
    jne .L9

Same Register with broken chain: 17.8869 GB/s

.L14:
    movq    (%rbx,%rdx,8), %r9
    movq    8(%rbx,%rdx,8), %r10
    movq    16(%rbx,%rdx,8), %r11
    movq    24(%rbx,%rdx,8), %rbp
    addq    $4, %rdx

    # Reuse "rax" for all the popcnts.
    xor    %rax, %rax    # Break the cross-iteration dependency by zeroing "rax".
    popcnt %r9, %rax
    add    %rax, %rcx
    popcnt %r10, %rax
    add    %rax, %rsi
    popcnt %r11, %rax
    add    %rax, %r8
    popcnt %rbp, %rax
    add    %rax, %rdi

    cmpq    $131072, %rdx
    jne .L14

So what went wrong with the compiler?

It seems that neither GCC nor Visual Studio are aware that popcnt has such a false dependency. Nevertheless, these false dependencies aren't uncommon. It's just a matter of whether the compiler is aware of it.

popcnt isn't exactly the most used instruction. So it's not really a surprise that a major compiler could miss something like this. There also appears to be no documentation anywhere that mentions this problem. If Intel doesn't disclose it, then nobody outside will know until someone runs into it by chance.

(Update: As of version 4.9.2, GCC is aware of this false-dependency and generates code to compensate it when optimizations are enabled. Major compilers from other vendors, including Clang, MSVC, and even Intel's own ICC are not yet aware of this microarchitectural erratum and will not emit code that compensates for it.)

Why does the CPU have such a false dependency?

We can speculate: it runs on the same execution unit as bsf / bsr which do have an output dependency. (How is POPCNT implemented in hardware?). For those instructions, Intel documents the integer result for input=0 as "undefined" (with ZF=1), but Intel hardware actually gives a stronger guarantee to avoid breaking old software: output unmodified. AMD documents this behaviour.

Presumably it was somehow inconvenient to make some uops for this execution unit dependent on the output but others not.

AMD processors do not appear to have this false dependency.


The full test code is below for reference:

#include <iostream>
#include <chrono>
#include <x86intrin.h>

int main(int argc, char* argv[]) {

   using namespace std;
   uint64_t size=1<<20;

   uint64_t* buffer = new uint64_t[size/8];
   char* charbuffer=reinterpret_cast<char*>(buffer);
   for (unsigned i=0;i<size;++i) charbuffer[i]=rand()%256;

   uint64_t count,duration;
   chrono::time_point<chrono::system_clock> startP,endP;
   {
      uint64_t c0 = 0;
      uint64_t c1 = 0;
      uint64_t c2 = 0;
      uint64_t c3 = 0;
      startP = chrono::system_clock::now();
      for( unsigned k = 0; k < 10000; k++){
         for (uint64_t i=0;i<size/8;i+=4) {
            uint64_t r0 = buffer[i + 0];
            uint64_t r1 = buffer[i + 1];
            uint64_t r2 = buffer[i + 2];
            uint64_t r3 = buffer[i + 3];
            __asm__(
                "popcnt %4, %4  \n\t"
                "add %4, %0     \n\t"
                "popcnt %5, %5  \n\t"
                "add %5, %1     \n\t"
                "popcnt %6, %6  \n\t"
                "add %6, %2     \n\t"
                "popcnt %7, %7  \n\t"
                "add %7, %3     \n\t"
                : "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
                : "r"  (r0), "r"  (r1), "r"  (r2), "r"  (r3)
            );
         }
      }
      count = c0 + c1 + c2 + c3;
      endP = chrono::system_clock::now();
      duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "No Chain\t" << count << '\t' << (duration/1.0E9) << " sec \t"
            << (10000.0*size)/(duration) << " GB/s" << endl;
   }
   {
      uint64_t c0 = 0;
      uint64_t c1 = 0;
      uint64_t c2 = 0;
      uint64_t c3 = 0;
      startP = chrono::system_clock::now();
      for( unsigned k = 0; k < 10000; k++){
         for (uint64_t i=0;i<size/8;i+=4) {
            uint64_t r0 = buffer[i + 0];
            uint64_t r1 = buffer[i + 1];
            uint64_t r2 = buffer[i + 2];
            uint64_t r3 = buffer[i + 3];
            __asm__(
                "popcnt %4, %%rax   \n\t"
                "add %%rax, %0      \n\t"
                "popcnt %5, %%rax   \n\t"
                "add %%rax, %1      \n\t"
                "popcnt %6, %%rax   \n\t"
                "add %%rax, %2      \n\t"
                "popcnt %7, %%rax   \n\t"
                "add %%rax, %3      \n\t"
                : "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
                : "r"  (r0), "r"  (r1), "r"  (r2), "r"  (r3)
                : "rax"
            );
         }
      }
      count = c0 + c1 + c2 + c3;
      endP = chrono::system_clock::now();
      duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "Chain 4   \t"  << count << '\t' << (duration/1.0E9) << " sec \t"
            << (10000.0*size)/(duration) << " GB/s" << endl;
   }
   {
      uint64_t c0 = 0;
      uint64_t c1 = 0;
      uint64_t c2 = 0;
      uint64_t c3 = 0;
      startP = chrono::system_clock::now();
      for( unsigned k = 0; k < 10000; k++){
         for (uint64_t i=0;i<size/8;i+=4) {
            uint64_t r0 = buffer[i + 0];
            uint64_t r1 = buffer[i + 1];
            uint64_t r2 = buffer[i + 2];
            uint64_t r3 = buffer[i + 3];
            __asm__(
                "xor %%rax, %%rax   \n\t"   // <--- Break the chain.
                "popcnt %4, %%rax   \n\t"
                "add %%rax, %0      \n\t"
                "popcnt %5, %%rax   \n\t"
                "add %%rax, %1      \n\t"
                "popcnt %6, %%rax   \n\t"
                "add %%rax, %2      \n\t"
                "popcnt %7, %%rax   \n\t"
                "add %%rax, %3      \n\t"
                : "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
                : "r"  (r0), "r"  (r1), "r"  (r2), "r"  (r3)
                : "rax"
            );
         }
      }
      count = c0 + c1 + c2 + c3;
      endP = chrono::system_clock::now();
      duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "Broken Chain\t"  << count << '\t' << (duration/1.0E9) << " sec \t"
            << (10000.0*size)/(duration) << " GB/s" << endl;
   }

   free(charbuffer);
}

An equally interesting benchmark can be found here: http://pastebin.com/kbzgL8si
This benchmark varies the number of popcnts that are in the (false) dependency chain.

False Chain 0:  41959360000 0.57748 sec     18.1578 GB/s
False Chain 1:  41959360000 0.585398 sec    17.9122 GB/s
False Chain 2:  41959360000 0.645483 sec    16.2448 GB/s
False Chain 3:  41959360000 0.929718 sec    11.2784 GB/s
False Chain 4:  41959360000 1.23572 sec     8.48557 GB/s

Django 1.7 - makemigrations not detecting changes

If you're changing over from an existing app you made in django 1.6, then you need to do one pre-step (as I found out) listed in the documentation:

python manage.py makemigrations your_app_label

The documentation does not make it obvious that you need to add the app label to the command, as the first thing it tells you to do is python manage.py makemigrations which will fail. The initial migration is done when you create your app in version 1.7, but if you came from 1.6 it wouldn't have been carried out. See the 'Adding migration to apps' in the documentation for more details.

Resolve promises one after another (i.e. in sequence)?

I created this simple method on the Promise object:

Create and add a Promise.sequence method to the Promise object

Promise.sequence = function (chain) {
    var results = [];
    var entries = chain;
    if (entries.entries) entries = entries.entries();
    return new Promise(function (yes, no) {
        var next = function () {
            var entry = entries.next();
            if(entry.done) yes(results);
            else {
                results.push(entry.value[1]().then(next, function() { no(results); } ));
            }
        };
        next();
    });
};

Usage:

var todo = [];

todo.push(firstPromise);
if (someCriterium) todo.push(optionalPromise);
todo.push(lastPromise);

// Invoking them
Promise.sequence(todo)
    .then(function(results) {}, function(results) {});

The best thing about this extension to the Promise object, is that it is consistent with the style of promises. Promise.all and Promise.sequence is invoked the same way, but have different semantics.

Caution

Sequential running of promises is not usually a very good way to use promises. It's usually better to use Promise.all, and let the browser run the code as fast as possible. However, there are real use cases for it - for example when writing a mobile app using javascript.

python numpy ValueError: operands could not be broadcast together with shapes

You are looking for np.matmul(X, y). In Python 3.5+ you can use X @ y.

Swift - encode URL

This is working for me in Swift 5. The usage case is taking a URL from the clipboard or similar which may already have escaped characters but which also contains Unicode characters which could cause URLComponents or URL(string:) to fail.

First, create a character set that includes all URL-legal characters:

extension CharacterSet {

    /// Characters valid in at least one part of a URL.
    ///
    /// These characters are not allowed in ALL parts of a URL; each part has different requirements. This set is useful for checking for Unicode characters that need to be percent encoded before performing a validity check on individual URL components.
    static var urlAllowedCharacters: CharacterSet {
        // Start by including hash, which isn't in any set
        var characters = CharacterSet(charactersIn: "#")
        // All URL-legal characters
        characters.formUnion(.urlUserAllowed)
        characters.formUnion(.urlPasswordAllowed)
        characters.formUnion(.urlHostAllowed)
        characters.formUnion(.urlPathAllowed)
        characters.formUnion(.urlQueryAllowed)
        characters.formUnion(.urlFragmentAllowed)

        return characters
    }
}

Next, extend String with a method to encode URLs:

extension String {

    /// Converts a string to a percent-encoded URL, including Unicode characters.
    ///
    /// - Returns: An encoded URL if all steps succeed, otherwise nil.
    func encodedUrl() -> URL? {        
        // Remove preexisting encoding,
        guard let decodedString = self.removingPercentEncoding,
            // encode any Unicode characters so URLComponents doesn't choke,
            let unicodeEncodedString = decodedString.addingPercentEncoding(withAllowedCharacters: .urlAllowedCharacters),
            // break into components to use proper encoding for each part,
            let components = URLComponents(string: unicodeEncodedString),
            // and reencode, to revert decoding while encoding missed characters.
            let percentEncodedUrl = components.url else {
            // Encoding failed
            return nil
        }

        return percentEncodedUrl
    }

}

Which can be tested like:

let urlText = "https://www.example.com/??/search?q=123&foo=bar&multi=eggs+and+ham&hangul=??&spaced=lovely%20spam&illegal=<>#top"
let url = encodedUrl(from: urlText)

Value of url at the end: https://www.example.com/%ED%8F%B4%EB%8D%94/search?q=123&foo=bar&multi=eggs+and+ham&hangul=%ED%95%9C%EA%B8%80&spaced=lovely%20spam&illegal=%3C%3E#top

Note that both %20 and + spacing are preserved, Unicode characters are encoded, the %20 in the original urlText is not double encoded, and the anchor (fragment, or #) remains.

Edit: Now checking for validity of each component.

How to change default format at created_at and updated_at value laravel

Use Carbon\Carbon;

$targetDate =  "2014-06-26 04:07:31";
Carbon::parse($targetDate)->format('Y-m-d');

Oracle SqlDeveloper JDK path

For those who use Mac, edit this file:

/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh

Mine had:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`

and I changed it to 1.8 and it stopped complaining about java version.

Swift Beta performance: sorting arrays

TL;DR: Yes, the only Swift language implementation is slow, right now. If you need fast, numeric (and other types of code, presumably) code, just go with another one. In the future, you should re-evaluate your choice. It might be good enough for most application code that is written at a higher level, though.

From what I'm seeing in SIL and LLVM IR, it seems like they need a bunch of optimizations for removing retains and releases, which might be implemented in Clang (for Objective-C), but they haven't ported them yet. That's the theory I'm going with (for now… I still need to confirm that Clang does something about it), since a profiler run on the last test-case of this question yields this “pretty” result:

Time profiling on -O3 Time profiling on -Ofast

As was said by many others, -Ofast is totally unsafe and changes language semantics. For me, it's at the “If you're going to use that, just use another language” stage. I'll re-evaluate that choice later, if it changes.

-O3 gets us a bunch of swift_retain and swift_release calls that, honestly, don't look like they should be there for this example. The optimizer should have elided (most of) them AFAICT, since it knows most of the information about the array, and knows that it has (at least) a strong reference to it.

It shouldn't emit more retains when it's not even calling functions which might release the objects. I don't think an array constructor can return an array which is smaller than what was asked for, which means that a lot of checks that were emitted are useless. It also knows that the integer will never be above 10k, so the overflow checks can be optimized (not because of -Ofast weirdness, but because of the semantics of the language (nothing else is changing that var nor can access it, and adding up to 10k is safe for the type Int).

The compiler might not be able to unbox the array or the array elements, though, since they're getting passed to sort(), which is an external function and has to get the arguments it's expecting. This will make us have to use the Int values indirectly, which would make it go a bit slower. This could change if the sort() generic function (not in the multi-method way) was available to the compiler and got inlined.

This is a very new (publicly) language, and it is going through what I assume are lots of changes, since there are people (heavily) involved with the Swift language asking for feedback and they all say the language isn't finished and will change.

Code used:

import Cocoa

let swift_start = NSDate.timeIntervalSinceReferenceDate();
let n: Int = 10000
let x = Int[](count: n, repeatedValue: 1)
for i in 0..n {
    for j in 0..n {
        let tmp: Int = x[j]
        x[i] = tmp
    }
}
let y: Int[] = sort(x)
let swift_stop = NSDate.timeIntervalSinceReferenceDate();

println("\(swift_stop - swift_start)s")

P.S: I'm not an expert on Objective-C nor all the facilities from Cocoa, Objective-C, or the Swift runtimes. I might also be assuming some things that I didn't write.

Finding index of character in Swift String

let mystring:String = "indeep";
let findCharacter:Character = "d";

if (mystring.characters.contains(findCharacter))
{
    let position = mystring.characters.indexOf(findCharacter);
    NSLog("Position of c is \(mystring.startIndex.distanceTo(position!))")

}
else
{
    NSLog("Position of c is not found");
}

What does an exclamation mark mean in the Swift language?

Some big picture perspective to add to the other useful but more detail-centric answers:

In Swift, the exclamation point appears in several contexts:

  • Forced unwrapping: let name = nameLabel!.text
  • Implicitly unwrapped optionals: var logo: UIImageView!
  • Forced casting: logo.image = thing as! UIImage
  • Unhandled exceptions: try! NSJSONSerialization.JSONObjectWithData(data, [])

Every one of these is a different language construct with a different meaning, but they all have three important things in common:

1. Exclamation points circumvent Swift’s compile-time safety checks.

When you use ! in Swift, you are essentially saying, “Hey, compiler, I know you think an error could happen here, but I know with total certainty that it never will.”

Not all valid code fits into the box of Swift’s compile-time type system — or any language’s static type checking, for that matter. There are situations where you can logically prove that an error will never happen, but you can’t prove it to the compiler. That’s why Swift’s designers added these features in the first place.

However, whenever you use !, you’re ruling out having a recovery path for an error, which means that…

2. Exclamation points are potential crashes.

An exclamation point also says, “Hey Swift, I am so certain that this error can never happen that it’s better for you to crash my whole app than it is for me to code a recovery path for it.”

That’s a dangerous assertion. It can be the correct one: in mission-critical code where you have thought hard about your code’s invariants, it may be that bogus output is worse than a crash.

However, when I see ! in the wild, it's rarely used so mindfully. Instead, it too often means, “this value was optional and I didn’t really think too hard about why it could be nil or how to properly handle that situation, but adding ! made it compile … so my code is correct, right?”

Beware the arrogance of the exclamation point. Instead…

3. Exclamation points are best used sparingly.

Every one of these ! constructs has a ? counterpart that forces you to deal with the error/nil case:

  • Conditional unwrapping: if let name = nameLabel?.text { ... }
  • Optionals: var logo: UIImageView?
  • Conditional casts: logo.image = thing as? UIImage
  • Nil-on-failure exceptions: try? NSJSONSerialization.JSONObjectWithData(data, [])

If you are tempted to use !, it is always good to consider carefully why you are not using ? instead. Is crashing your program really the best option if the ! operation fails? Why is that value optional/failable?

Is there a reasonable recovery path your code could take in the nil/error case? If so, code it.

If it can’t possibly be nil, if the error can never happen, then is there a reasonable way to rework your logic so that the compiler knows that? If so, do it; your code will be less error-prone.

There are times when there is no reasonable way to handle an error, and simply ignoring the error — and thus proceeding with wrong data — would be worse than crashing. Those are the times to use force unwrapping.

I periodically search my entire codebase for ! and audit every use of it. Very few usages stand up to scrutiny. (As of this writing, the entire Siesta framework has exactly two instances of it.)

That’s not to say you should never use ! in your code — just that you should use it mindfully, and never make it the default option.

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

In my case, I had to use different certificates for different git repositories.

Follow steps below (If you have a certificate of your repository, you can read from step 5)

  1. Go to remote repository's site. Ex: github.com, bitbucket.org, tfs.example...

  2. Click Lock icon on the upper left side and click Certificate.

  3. Go to Certification Path tab and double click to .. Root Certificate

  4. Go to Details tab and click Copy to file.

  5. Export/Copy certificate to wherever you want. Ex: C:\certs\example.cer

  6. Open git bash at your local repository folder and type:

    $ git config http.sslCAInfo "C:\certs\example.cer"

Now you can use different certificates for each repository.

Remember, calling with the --global parameter will also change the certificates of git repositories in other folders, so you should not use the --global parameter when executing this command.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Remove your Gemfile.lock.

Move to bash if you are using zsh.

sudo bash
gem update --system 

Now run command bundle to create a new Gemfile.lock file. Move back to your zsh sudo exec zsh now run your rake commands.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

your $(this).val() has no scope in your ajax call, because its not in change event function scope

May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.

simply get the value using id selector instead of

$(#CourseSelect).val()

whole code should be like this:

 $(document).ready(function () 
{
    $("#CourseSelect").change(loadTeachers);
    loadTeachers();
});

function loadTeachers()
{
    $.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
        success:function(data)
        { 
            $('#TeacherSelect').get(0).options.length = 0;    

            $.each(data, function(i, teacher) 
            {
                var option = $('<option />');
                option.val(teacher.employeeId);
                option.text(teacher.name);
                $('#TeacherSelect').append(option);
            });
        }, error:function(){ alert("Error while getting results"); }
    });
}

phpMyAdmin allow remote users

The other answers so far seem to advocate the complete replacement of the <Directory/> block, this is not needed and may remove extra settings like the 'AddDefaultCharset UTF-8' now included.

To allow remote access you need to add 1 line to the 2.4 config block or change 2 lines in the 2.2 (depending on your apache version):

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #ADD following line:
       Require all granted
       Require ip 127.0.0.1
       Require ip ::1
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     #CHANGE following 2 lines:
     Order Allow,Deny
     Allow from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

Bootstrap full responsive navbar with logo or brand name text

Just set the height and width where you are adding that logo. I tried and its working fine

Remove Duplicate objects from JSON Array

Use this Pseudocode

var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];
var newArr =[]
for(var i in standardsList){
    newArr.push(JSON.stringify(standardsList[i]))
}
var obj = {};
newArr= newArr.filter((item)=>{
    return obj.hasOwnProperty(item) ? false : (obj[item] = true);
})
standardsList.length = 0
for(var i in newArr){
    standardsList.push(JSON.parse(newArr[i]))
}
console.log(standardsList)

I have choose a sample array similar to yours. Its easier to compare objects once you stringfy them. Then you just have to compare strings.

Laravel Eloquent LEFT JOIN WHERE NULL

This can be resolved by specifying the specific column names desired from the specific table like so:

$c = Customer::leftJoin('orders', function($join) {
      $join->on('customers.id', '=', 'orders.customer_id');
    })
    ->whereNull('orders.customer_id')
    ->first([
        'customers.id',
        'customers.first_name',
        'customers.last_name',
        'customers.email',
        'customers.phone',
        'customers.address1',
        'customers.address2',
        'customers.city',
        'customers.state',
        'customers.county',
        'customers.district',
        'customers.postal_code',
        'customers.country'
    ]);

Forbidden :You don't have permission to access /phpmyadmin on this server

With the latest version of phpmyadmin 5.0.2+ at least

Check that the actual installation was completed correctly,

Mine had been copied over into a sub folder on a linux machine rather that being at the

/usr/share/phpmyadmin/

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

AngularJS : Factory and Service?

Service vs Factory


enter image description here enter image description here

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Factory are a great way for communicating between controllers like sharing data.

  • Can use other dependencies

  • Usually used when the service instance requires complex creation logic

  • Cannot be injected in .config() function.

  • Used for non configurable services

  • If you're using an object, you could use the factory provider.

  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Services are used for communication between controllers to share data

  • You can add properties and functions to a service object by using the this keyword

  • Dependencies are injected as constructor arguments

  • Used for simple creation logic

  • Cannot be injected in .config() function.

  • If you're using a class you could use the service provider

  • Syntax: module.service(‘serviceName’, function);

Sample Demo

In below example I have define MyService and MyFactory. Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

Also Take a look at this beautiful stuffs

Confused about service vs factory

AngularJS Factory, Service and Provider

Angular.js: service vs provider vs factory?

Build error: You must add a reference to System.Runtime

To implement the fix, first expand out the existing web.config compilation section that looks like this by default:

<compilation debug="true" targetFramework="4.5"/>

Once expanded, I then added the following new configuration XML as I was instructed:

  <assemblies>     
    <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />   
  </assemblies>

The final web.config tags should look like this:

<compilation debug="true" targetFramework="4.5">
  <assemblies>     
    <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />   
  </assemblies>
</compilation>

C++ - Decimal to binary converting

Your solution needs a modification. The final string should be reversed before returning:

std::reverse(r.begin(), r.end());
return r;

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Map<String, Integer> map = new HashMap<>();
map.put("test1", 1);
map.put("test2", 2);

Map<String, Integer> map2 = new HashMap<>();
map.forEach(map2::put);

System.out.println("map: " + map);
System.out.println("map2: " + map2);
// Output:
// map:  {test2=2, test1=1}
// map2: {test2=2, test1=1}

You can use the forEach method to do what you want.

What you're doing there is:

map.forEach(new BiConsumer<String, Integer>() {
    @Override
    public void accept(String s, Integer integer) {
        map2.put(s, integer);     
    }
});

Which we can simplify into a lambda:

map.forEach((s, integer) ->  map2.put(s, integer));

And because we're just calling an existing method we can use a method reference, which gives us:

map.forEach(map2::put);

Vagrant error : Failed to mount folders in Linux guest

Your log complains about not finding exportfs: sudo: /usr/bin/exportfs: command not found

The exportfs makes local directories available for NFS clients to mount.

Java "lambda expressions not supported at this language level"

7.0 does not support lambda expressions. Just add this to your app gradle to change your language level to 8.0:

compileOptions {
    targetCompatibility 1.8
    sourceCompatibility 1.8
}

enter image description here

<embed> vs. <object>

Embed is not a standard tag, though object is. Here's an article that looks like it will help you, since it seems the situation is not so simple. An example for PDF is included.

How to resolve /var/www copy/write permission denied?

it'matter of *unix permissions, gain root acces, for example by typing

sudo su
[then type your password]

and try to do what you have to do

Return a `struct` from a function in C

yes, it is possible we can pass structure and return structure as well. You were right but you actually did not pass the data type which should be like this struct MyObj b = a.

Actually I also came to know when I was trying to find out a better solution to return more than one values for function without using pointer or global variable.

Now below is the example for the same, which calculate the deviation of a student marks about average.

#include<stdio.h>
struct marks{
    int maths;
    int physics;
    int chem;
};

struct marks deviation(struct marks student1 , struct marks student2 );

int main(){

    struct marks student;
    student.maths= 87;
    student.chem = 67;
    student.physics=96;

    struct marks avg;
    avg.maths= 55;
    avg.chem = 45;
    avg.physics=34;
    //struct marks dev;
    struct marks dev= deviation(student, avg );
    printf("%d %d %d" ,dev.maths,dev.chem,dev.physics);

    return 0;
 }

struct marks deviation(struct marks student , struct marks student2 ){
    struct marks dev;

    dev.maths = student.maths-student2.maths;
    dev.chem = student.chem-student2.chem;
    dev.physics = student.physics-student2.physics; 

    return dev;
}

Using 24 hour time in bootstrap timepicker

//Timepicker
$(".timepicker").timepicker({
  showInputs: false,
  showMeridian: false //24hr mode 
});

Disable all dialog boxes in Excel while running VB script?

In order to get around the Enable Macro prompt I suggest

Application.AutomationSecurity = msoAutomationSecurityForceDisable

Be sure to return it to default when you are done

Application.AutomationSecurity = msoAutomationSecurityLow

A reminder that the .SaveAs function contains all optional arguments.I recommend removing CreatBackup:= False as it is not necessary.

The most interesting way I think is to create an object of the workbook and access the .SaveAs property that way. I have not tested it but you are never using Workbooks.Open rendering Application.AutomationSecurity inapplicable. Possibly saving resources and time as well.

That said I was able to execute the following without any notifications on Excel 2013 windows 10.

    Option Explicit

    Sub Convert()

    OptimizeVBA (True)  
    'function to set all the things you want to set, but hate keying in

    Application.AutomationSecurity = msoAutomationSecurityForceDisable  
    'this should stop those pesky enable prompts

    ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to 
    xlsx stop popup"

    Workbooks.Open ("Book1.xlsm")

    ActiveWorkbook.SaveAs Filename:= _
    "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_ 
    stop popup\Book1.xlsx" _
    , FileFormat:=xlOpenXMLWorkbook

    ActiveWorkbook.Close

    Application.AutomationSecurity = msoAutomationSecurityLow 
    'make sure you set this up when done

    Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_ 
    to xlsx stop popup\Book1.xlsx") 'clean up

    OptimizeVBA (False)
    End Sub


    Function OptimizeVBA(ByRef Status As Boolean)

    If Status = True Then
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        Application.DisplayAlerts = False
        Application.EnableEvents = False
    Else
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    End If

    End Function

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

Encoding URL query parameters in Java

It is not necessary to encode a colon as %3B in the query, although doing so is not illegal.

URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
query       = *( pchar / "/" / "?" )
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

It also seems that only percent-encoded spaces are valid, as I doubt that space is an ALPHA or a DIGIT

look to the URI specification for more details.

Connect to Amazon EC2 file directory using Filezilla and SFTP

This is very simple if you used your pem file ( I am using MacOS / windows user can follow the same steps.)

  1. Just download your FileZilla (I'm using MacOS - and downloaded free version, that's good enough)

  2. Open Site Manager in FileZilla (?S) -> New Site

enter image description here

  1. Put your host name in the Host field.

Example: eca-**-**-**-111.ap-southwest-9.compute.amazonaws.com

  • Select Protocol as SFTP - SSH File Transfer Protocol

  • Select Logon type as Key File

  • Put your user name in the User field : for me it's ubuntu (find your ssh user)

Note:

OS vs Username

Amazon - ec2-user

Centos - centos

Debian - admin or root

Fedora - ec2-user

RHEL - ec2-user or root

SUSE - ec2-user or root

Ubuntu - ubuntu or root

  1. For Key file field, browse your pem file: and click Connect

enter image description here

  1. That's all :) have fun!

Note:

(Remember to allow SSH connection to your IP address from EC2) If not you will get connecting error message!

Note: Allowing your IP to connect your aws instance via SFTP

EC2 -> SecurityGroups -> SSH -> Inbound rules -> Edit -> Add Rule ( SSH|TCP|22|My IP(it's get ip automatically | name for rule) -> Save

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx (as noted already by @jewelsea above)

/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar

Jackson with JSON: Unrecognized field, not marked as ignorable

This works better than All please refer to this property.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    projectVO = objectMapper.readValue(yourjsonstring, Test.class);

gradle build fails on lint task

Add these lines to your build.gradle file:

android { 
  lintOptions { 
    abortOnError false 
  }
}

Then clean your project :D

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

'Static readonly' vs. 'const'

I would use static readonly if the Consumer is in a different assembly. Having the const and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.

Convert a Unicode string to an escaped ASCII string

You need to use the Convert() method in the Encoding class:

  • Create an Encoding object that represents ASCII encoding
  • Create an Encoding object that represents Unicode encoding
  • Call Encoding.Convert() with the source encoding, the destination encoding, and the string to be encoded

There is an example here:

using System;
using System.Text;

namespace ConvertExample
{
   class ConvertExampleClass
   {
      static void Main()
      {
         string unicodeString = "This string contains the unicode character Pi(\u03a0)";

         // Create two different encodings.
         Encoding ascii = Encoding.ASCII;
         Encoding unicode = Encoding.Unicode;

         // Convert the string into a byte[].
         byte[] unicodeBytes = unicode.GetBytes(unicodeString);

         // Perform the conversion from one encoding to the other.
         byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

         // Convert the new byte[] into a char[] and then into a string.
         // This is a slightly different approach to converting to illustrate
         // the use of GetCharCount/GetChars.
         char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
         ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
         string asciiString = new string(asciiChars);

         // Display the strings created before and after the conversion.
         Console.WriteLine("Original string: {0}", unicodeString);
         Console.WriteLine("Ascii converted string: {0}", asciiString);
      }
   }
}

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

The error occurred because the code is not for the default compiler used there. Paste this code in effective POM before the root element ends, after declaring dependencies, to change the compiler used. Adjust version as you need.

<dependencies>
...
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

redistributable offline .NET Framework 3.5 installer for Windows 8

After several month without real solution for this problem, I suppose that the best solution is to upgrade the application to .NET framework 4.0, which is supported by Windows 8, Windows 10 and Windows 2012 Server by default and it is still available as offline installation for Windows XP.

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Assuming those methods are in one of the libs it looks like an ordering problem.

When linking libraries into an executable they are done in the order they are declared.
Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies.

How it works:

  • Take all the object files and combine them into an executable
  • Resolve any dependencies among object files.
  • For-each library in order:
    • Check unresolved dependencies and see if the lib resolves them.
    • If so load required part into the executable.

Example:

Objects requires:

  • Open
  • Close
  • BatchRead
  • BatchWrite

Lib 1 provides:

  • Open
  • Close
  • read
  • write

Lib 2 provides

  • BatchRead (but uses lib1:read)
  • BatchWrite (but uses lib1:write)

If linked like this:

gcc -o plop plop.o -l1 -l2

Then the linker will fail to resolve the read and write symbols.

But if I link the application like this:

gcc -o plop plop.o -l2 -l1

Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved.

Where does Android emulator store SQLite database?

The filesystem of the emulator doesn't map to a directory on your hard drive. The emulator's disk image is stored as an image file, which you can manage through either Eclipse (look for the G1-looking icon in the toolbar), or through the emulator binary itself (run "emulator -help" for a description of options).

You're best off using adb from the command line to jack into a running emulator. If you can get the specific directory and filename, you can do an "adb pull" to get the database file off of the emulator and onto your regular hard drive.

Edit: Removed suggestion that this works for unrooted devices too - it only works for emulators, and devices where you are operating adb as root.

How to automatically generate unique id in SQL like UID12345678?

Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:

SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID ) 
                     FROM returns 
                     WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM 
returns t

Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:

SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
                     FROM returns 
                     WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM 
returns t

All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql

how to convert string into time format and add two hours

Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.

class demo
{private int hour,min,sec;
    void input(int hour,int min,int sec)
    {this.hour=hour;
    this.min=min;
    this.sec=sec;

    }
    demo add(demo d2)//demo  because we are returning object
    {   demo obj=new demo();
    obj.hour=hour+d2.hour;
    obj.min=min+d2.min;
    obj.sec=sec+d2.sec;
    return obj;//Returning object and later on it gets allocated to demo d3                    
    }
    void display()
    {
        System.out.println(hour+":"+min+":"+sec);
    }
    public static  void main(String args[])
    {
        demo d1=new demo();
        demo d2=new demo();
        d1.input(2, 5, 10);
        d2.input(3, 3, 3);
        demo d3=d1.add(d2);//Note another object is created
        d3.display();


    }

}

Modified Time Addition Program

class demo {private int hour,min,sec; void input(int hour,int min,int sec) {this.hour=(hour>12&&hour<24)?(hour-12):hour; this.min=(min>60)?0:min; this.sec=(sec>60)?0:sec; } demo add(demo d2) { demo obj=new demo(); obj.hour=hour+d2.hour; obj.min=min+d2.min; obj.sec=sec+d2.sec; if(obj.sec>60) {obj.sec-=60; obj.min++; } if(obj.min>60) { obj.min-=60; obj.hour++; } return obj; } void display() { System.out.println(hour+":"+min+":"+sec); } public static void main(String args[]) { demo d1=new demo(); demo d2=new demo(); d1.input(12, 55, 55); d2.input(12, 7, 6); demo d3=d1.add(d2); d3.display(); } }

'negative' pattern matching in python

You can also do it without negative look ahead. You just need to add parentheses to that part of expression which you want to extract. This construction with parentheses is named group.

Let's write python code:

string = """OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
.
"""

search_result = re.search(r"^OK.*\n((.|\s)*).", string)

if search_result:
    print(search_result.group(1))

Output is:

1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

^OK.*\n will find first line with OK statement, but we don't want to extract it so leave it without parentheses. Next is part which we want to capture: ((.|\s)*), so put it inside parentheses. And in the end of regexp we look for a dot ., but we also don't want to capture it.

P.S: I find this answer is super helpful to understand power of groups. https://stackoverflow.com/a/3513858/4333811

getString Outside of a Context or Activity

BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;

So 2 basic things to get string visible in the different class:

//make sure you are importing the right R class
import your.namespace.R;

//don't forget about the context
public void some_method(Context context) {
   context.getString(R.string.YOUR_STRING);
}

docker entrypoint running bash script gets "permission denied"

This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.

In my working directory I have two files: Dockerfile & provision.sh

Dockerfile:

FROM centos:6.8

# put the script in the /root directory of the container
COPY provision.sh /root

# execute the script inside the container
RUN /root/provision.sh

EXPOSE 80

# Default command
CMD ["/bin/bash"]

provision.sh:

#!/usr/bin/env bash

yum upgrade

I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh then running docker build . .

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Either remove the below code from the pom.xml or correct your java version to make it work.

  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>

Kill python interpeter in linux from the terminal

You can try the killall command:

killall python

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

I believe the author is not asking how to wait for a fractional time (delay), but instead how to pass a scalar as argument of the selector (withObject:) and the fastest way in modern objective C is:

[obj performSelector:...  withObject:@(0.123123123) afterDelay:10]

your selector have to change its parameter to NSNumber, and retrieve the value using a selector like floatValue or doubleValue

Cancel a vanilla ECMAScript 6 Promise chain

const makeCancelable = promise => {
    let rejectFn;

    const wrappedPromise = new Promise((resolve, reject) => {
        rejectFn = reject;

        Promise.resolve(promise)
            .then(resolve)
            .catch(reject);
    });

    wrappedPromise.cancel = () => {
        rejectFn({ canceled: true });
    };

    return wrappedPromise;
};

Usage:

const cancelablePromise = makeCancelable(myPromise);
// ...
cancelablePromise.cancel();

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

What's the best way to share data between activities?

All of the aforementioned answers are great... I'm just adding one no one had mentioned yet about persisting data through activities and that is to use the built in android SQLite database to persist relevant data... In fact you can place your databaseHelper in the application state and call it as needed throughout the activates.. Or just make a helper class and make the DB calls when needed... Just adding another layer for you to consider... But all of the other answers would suffice as well.. Really just preference

How to scroll the window using JQuery $.scrollTo() function

If it's not working why don't you try using jQuery's scrollTop method?

$("#id").scrollTop($("#id").scrollTop() + 100);

If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.

How to get the value from the GET parameters?

I made a function that does this:

var getUrlParams = function (url) {
  var params = {};
  (url + '?').split('?')[1].split('&').forEach(function (pair) {
    pair = (pair + '=').split('=').map(decodeURIComponent);
    if (pair[0].length) {
      params[pair[0]] = pair[1];
    }
  });
  return params;
};

Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):

const getUrlParams = url => `${url}?`.split('?')[1]
  .split('&').reduce((params, pair) =>
    ((key, val) => key ? {...params, [key]: val} : params)
    (...`${pair}=`.split('=').map(decodeURIComponent)), {});

Some tests:

console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}

Update 3/26/2018, here is a Typescript implementation:

const getUrlParams = (search: string) => `${search}?`
  .split('?')[1]
  .split('&')
  .reduce(
    (params: object, pair: string) => {
      const [key, value] = `${pair}=`
        .split('=')
        .map(decodeURIComponent)

      return key.length > 0 ? { ...params, [key]: value } : params
    },
    {}
  )

Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.

interface IParams { [key: string]: string }

const paramReducer = (params: IParams, pair: string): IParams => {
  const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)

  return key.length > 0 ? { ...params, [key]: value } : params
}

const getUrlParams = (search: string): IParams =>
  `${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})

Produce a random number in a range using C#

Use:

Random r = new Random();
 int x= r.Next(10);//Max range

How to call base.base.method()?

The answer (which I know is not what you're looking for) is:

class SpecialDerived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.

EDIT:

Your edit works, but I think I would use something like this:

class Derived : Base
{
    protected bool _useBaseSay = false;

    public override void Say()
    {
        if(this._useBaseSay)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Of course, in a real implementation, you might do something more like this for extensibility and maintainability:

class Derived : Base
{
    protected enum Mode
    {
        Standard,
        BaseFunctionality,
        Verbose
        //etc
    }

    protected Mode Mode
    {
        get; set;
    }

    public override void Say()
    {
        if(this.Mode == Mode.BaseFunctionality)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Then, derived classes can control their parents' state appropriately.

How can I check if an ip is in a network in Python?

Wherever possible I'd recommend the built in ipaddress module. It's only available in Python 3 though, but it is super easy to use, and supports IPv6. And why aren't you using Python 3 yet anyway, right?


The accepted answer doesn't work ... which is making me angry. Mask is backwards and doesn't work with any bits that are not a simple 8 bit block (eg /24). I adapted the answer, and it works nicely.

    import socket,struct
    
    def addressInNetwork(ip, net_n_bits):  
      ipaddr = struct.unpack('!L', socket.inet_aton(ip))[0]
      net, bits = net_n_bits.split('/')
      netaddr = struct.unpack('!L', socket.inet_aton(net))[0]
      netmask = (0xFFFFFFFF >> int(bits)) ^ 0xFFFFFFFF
      return ipaddr & netmask == netaddr

here is a function that returns a dotted binary string to help visualize the masking.. kind of like ipcalc output.

    def bb(i):
     def s = '{:032b}'.format(i)
     def return s[0:8]+"."+s[8:16]+"."+s[16:24]+"."+s[24:32]

eg:

screen shot of python

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

Opening the Settings app from another app

YES!! you can launch Device Settings screen, I have tested on iOS 9.2

Step 1. we need to add URL schemes

Go to Project settings --> Info --> URL Types --> Add New URL Schemes

enter image description here

Step 2. Launch Settings programmatically Thanks to @davidcann

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]];

Also we can launch sub-screens like Music, Location etc. as well by just using proper name

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=MUSIC"]];

See this full name list here shared by Henri Normak


Update:

As per the comment everyone wants to know what happens after this change to my application submission status?

So YES!! I got successful update submission and application is available on store without any complain.

Just to confirm, I Just downloaded this morning and disabled Location services, and then started the app, which asked me for location permission and then my alert popup was there to send me on settings -> location services page --> Enabled --> That's it!!

![NOTICE: Your app might be rejected ... even if it's approved it can be rejected in future version if you use this method...]4

What exactly do "u" and "r" string flags do, and what are raw string literals?

There's not really any "raw string"; there are raw string literals, which are exactly the string literals marked by an 'r' before the opening quote.

A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, \, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence.

This syntax variant exists mostly because the syntax of regular expression patterns is heavy with backslashes (but never at the end, so the "except" clause above doesn't matter) and it looks a bit better when you avoid doubling up each of them -- that's all. It also gained some popularity to express native Windows file paths (with backslashes instead of regular slashes like on other platforms), but that's very rarely needed (since normal slashes mostly work fine on Windows too) and imperfect (due to the "except" clause above).

r'...' is a byte string (in Python 2.*), ur'...' is a Unicode string (again, in Python 2.*), and any of the other three kinds of quoting also produces exactly the same types of strings (so for example r'...', r'''...''', r"...", r"""...""" are all byte strings, and so on).

Not sure what you mean by "going back" - there is no intrinsically back and forward directions, because there's no raw string type, it's just an alternative syntax to express perfectly normal string objects, byte or unicode as they may be.

And yes, in Python 2.*, u'...' is of course always distinct from just '...' -- the former is a unicode string, the latter is a byte string. What encoding the literal might be expressed in is a completely orthogonal issue.

E.g., consider (Python 2.6):

>>> sys.getsizeof('ciao')
28
>>> sys.getsizeof(u'ciao')
34

The Unicode object of course takes more memory space (very small difference for a very short string, obviously ;-).

intellij idea - Error: java: invalid source release 1.9

I've just had a similar issue. The project had opened using Java 9 but even after all the modules and project were set back to 1.8, I was still getting the error.

I needed to force Gradle to refresh the project and then everything ran as expected.

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

How to use a TRIM function in SQL Server

Example:

DECLARE @Str NVARCHAR(MAX) = N'
            foo   bar
        Foo           Bar        

'

PRINT '[' + @Str + ']'

DECLARE @StrPrv NVARCHAR(MAX) = N''

WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
    SET @StrPrv = @Str

    -- Beginning
    IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
        SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))

    -- Ending
    IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
        SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END

PRINT '[' + @Str + ']'

Result

[
            foo   bar
        Foo           Bar        

]
[foo   bar
        Foo           Bar]

Using fnTrim

Source: https://github.com/reduardo7/fnTrim

SELECT dbo.fnTrim(colName)

Java socket API: How to tell if a connection has been closed?

I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).

If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.

I have read that to actually determine whether or not a socket has been closed data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation.

If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:

  • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).
  • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...

I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.

ORA-00972 identifier is too long alias column name

I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.

The name does not exist in the namespace error in XAML

The solution for me was to unblock the assembly DLLs. The error messages you get don't indicate this, but the XAML designer refuses to load what it calls "sandboxed" assemblies. You can see this in the output window when you build. DLLs are blocked if they are downloaded from the internet. To unblock your 3rd-party assembly DLLs:

  1. Right click on the DLL file in Windows Explorer and select Properties.
  2. At the bottom of the General tab click the "Unblock" button or checkbox.

Note: Only unblock DLLs if you are sure they are safe.

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

jquery find element by specific class when element has multiple classes

You can combine selectors like this

$(".alert-box.warn, .alert-box.dead");

Or if you want a wildcard use the attribute-contains selector

$("[class*='alert-box']");

Note: Preferably you would know the element type or tag when using the selectors above. Knowing the tag can make the selector more efficient.

$("div.alert-box.warn, div.alert-box.dead");
$("div[class*='alert-box']");

TempData keep() vs peek()

Keep() method marks the specified key in the dictionary for retention

You can use Keep() when prevent/hold the value depends on additional logic.

when you read TempData one’s and want to hold for another request then use keep method, so TempData can available for next request as above example.

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

SQL Server, division returns zero

Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.

Using FolderBrowserDialog in WPF application

You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog class.

Adding using WinForms = System.Windows.Forms; will be helpful.

Box shadow for bottom side only

-webkit-box-shadow: 0 3px 5px -3px #000;
-moz-box-shadow: 0 3px 5px -3px #000;
box-shadow: 0 3px 5px -3px #000;

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

Specifying and saving a figure with exact size in pixels

I had same issue. I used PIL Image to load the images and converted to a numpy array then patched a rectangle using matplotlib. It was a jpg image, so there was no way for me to get the dpi from PIL img.info['dpi'], so the accepted solution did not work for me. But after some tinkering I figured out way to save the figure with the same size as the original.

I am adding the following solution here thinking that it will help somebody who had the same issue as mine.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

img = Image.open('my_image.jpg') #loading the image
image = np.array(img) #converting it to ndarray
dpi = plt.rcParams['figure.dpi'] #get the default dpi value
fig_size = (img.size[0]/dpi, img.size[1]/dpi) #saving the figure size
fig, ax = plt.subplots(1, figsize=fig_size) #applying figure size
#do whatver you want to do with the figure
fig.tight_layout() #just to be sure
fig.savefig('my_updated_image.jpg') #saving the image

This saved the image with the same resolution as the original image.

In case you are not working with a jupyter notebook. you can get the dpi in the following manner.

figure = plt.figure()
dpi = figure.dpi

How to add 10 minutes to my (String) time?

Java 7 Time API

    DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");

    LocalTime lt = LocalTime.parse("14:10");
    System.out.println(df.format(lt.plusMinutes(10)));

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

How to get cookie's expire time

It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:

Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain

This way you can also get deleted ones since their value is deleted:

Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain

From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.

This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.

For more info see:

https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php

I want my android application to be only run in portrait mode?

There are two ways,

  1. Add android:screenOrientation="portrait" for each Activity in Manifest File
  2. Add this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); in each java file.

convert php date to mysql format

$date = mysql_real_escape_string($_POST['intake_date']);

1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

2. If your MySQL column is DATETIME type:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.


Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;

Output:

2009-07-02 00:07:00

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Viewing all defined variables

As RedBlueThing and analog said:

  • dir() gives a list of in scope variables
  • globals() gives a dictionary of global variables
  • locals() gives a dictionary of local variables

Using the interactive shell (version 2.6.9), after creating variables a = 1 and b = 2, running dir() gives

['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']

running locals() gives

{'a': 1, 'b': 2, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

Running globals() gives exactly the same answer as locals() in this case.

I haven't gotten into any modules, so all the variables are available as both local and global variables. locals() and globals() list the values of the variables as well as the names; dir() only lists the names.

If I import a module and run locals() or globals() inside the module, dir() still gives only a small number of variables; it adds __file__ to the variables listed above. locals() and globals() also list the same variables, but in the process of printing out the dictionary value for __builtin__, it lists a far larger number of variables: built-in functions, exceptions, and types such as "'type': <type 'type'>", rather than just the brief <module '__builtin__' (built-in)> as shown above.

For more about dir() see Python 2.7 quick reference at New Mexico Tech or the dir() function at ibiblio.org.

For more about locals() and globals() see locals and globals at Dive Into Python and a page about globals at New Mexico Tech.

[Comment: @Kurt: You gave a link to enumerate-or-list-all-variables-in-a-program-of-your-favorite-language-here but that answer has a mistake in it. The problem there is: type(name) in that example will always return <type 'str'>. You do get a list of the variables, which answers the question, but with incorrect types listed beside them. This was not obvious in your example because all the variables happened to be strings anyway; however, what it's returning is the type of the name of the variable instead of the type of the variable. To fix this: instead of print type(name) use print eval('type(' + name + ')'). I apologize for posting a comment in the answer section but I don't have comment posting privileges, and the other question is closed.]

JSON parsing using Gson for Java

Firstly generate getter and setter using below parsing site

http://www.jsonschema2pojo.org/

Now use Gson

GettetSetterClass object=new Gson().fromjson(jsonLine, GettetSetterClass.class);

Now use object to get values such as data,translationText

How do I find out if first character of a string is a number?

IN KOTLIN :

Suppose that you have a String like this :

private val phoneNumber="9121111111"

At first you should get the first one :

val firstChar=phoneNumber.slice(0..0)

At second you can check the first char that return a Boolean :

firstChar.isInt() // or isFloat()

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java does not support multiple inheritance because of two reasons:

  1. In java, every class is a child of Object class. When it inherits from more than one super class, sub class gets the ambiguity to acquire the property of Object class..
  2. In java every class has a constructor, if we write it explicitly or not at all. The first statement is calling super() to invoke the supper class constructor. If the class has more than one super class, it gets confused.

So when one class extends from more than one super class, we get compile time error.

Should you use .htm or .html file extension? What is the difference, and which file is correct?

I guess it's a little too late now however the only time it does make a difference is when you set up HTML signatures on MS Outlook (even 2010). It's just not able to handle .html extensions, only .htm

conversion from infix to prefix

simple google search came up with this. Doubt anyone can explain this any simpler. But I guess after an edit, I can try to bring forward the concepts so that you can answer your own question.

Hint :

Study for exam, hard, you must. Predict you, grade get high, I do :D

Explanation :

It's all about the way operations are associated with operands. each notation type has its own rules. You just need to break down and remember these rules. If I told you I wrote (2*2)/3 as [* /] (2,2,3) all you need to do is learn how to turn the latter notation in the former notation.

My custom notation says that take the first two operands and multiple them, then the resulting operand should be divided by the third. Get it ? They are trying to teach you three things.

  1. To become comfortable with different notations. The example I gave is what you will find in assembly languages. operands (which you act on) and operations (what you want to do to the operands).
  2. Precedence rules in computing do not necessarily need to follow those found in mathematics.
  3. Evaluation: How a machine perceives programs, and how it might order them at run-time.

How to append multiple values to a list in Python

If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

set serveroutput on in oracle procedure

Procedure successful but any outpout

Error line1: Unexpected identifier

Here is the code:

SET SERVEROUTPUT ON 

DECLARE

    -- Curseurs 
    CURSOR c1 IS        
    SELECT RWID FROM J_EVT
     WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));

    -- Collections 

    TYPE tc1 IS TABLE OF c1%RWTYPE;

    -- Variables de type record
    rtc1                        tc1;    

    vCpt                        NUMBER:=0;

BEGIN

    OPEN c1;
    LOOP
        FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;

        FORALL i IN 1..rtc1.COUNT 
        DELETE FROM J_EVT
          WHERE RWID = rtc1(i).RWID;
        COMMIT;

        -- Nombres lus : 5025651
        FOR i IN 1..rtc1.COUNT LOOP               
            vCpt := vCpt + SQL%BULK_RWCOUNT(i);
        END LOOP;            

        EXIT WHEN c1%NOTFOUND;   
    END LOOP;
    CLOSE c1;
    COMMIT;

    DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt)); 

END;
/
exit

Finishing current activity from a fragment

In Fragment use getActivity.finishAffinity()

getActivity().finishAffinity();

It will remove all the fragment which pushed by the current activity from the Stack with the Activity too...

When using SASS how can I import a file from a different directory?

To define the file to import it's possible to use all folders common definitions. You just have to be aware that it's relative to file you are defining it. More about import option with examples you can check here.

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Here is some weak adobe documentation on different flash 9 wmode settings.

A note of caution on wmode transparent is here in the adobe bug trac.

And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

What does OpenCV's cvWaitKey( ) function do?

waits milliseconds to check if the key is pressed, if pressed in that interval return its ascii value, otherwise it still -1

How to get substring in C

If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);

or

for(int i=0; i<4; i++)
    sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
    sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
    sub3[i] = baseString[i+8];
sub3[4] = 0;

Prefer strncpy if possible.

Owl Carousel, making custom navigation

You can use a JS and SCSS/Fontawesome combination for the Prev/Next buttons.

In your JS (this includes screenreader only/accessibility classes with Zurb Foundation):

$('.whatever-carousel').owlCarousel({
    ... ...
    navText: ["<span class='show-for-sr'>Previous</span>","<span class='show-for-sr'>Next</span>"]
    ... ...
})

In your SCSS this:

.owl-theme {

    .owl-nav {
        .owl-prev,
        .owl-next {
            font-family: FontAwesome;
            //border-radius: 50%;
            //padding: whatever-to-get-a-circle;
            transition: all, .2s, ease;
        }
        .owl-prev {
            &::before {
                content: "\f104";
            }
        }
        .owl-next {
            &::before {
                content: "\f105";
            }
        }
    }
}

For the FontAwesome font-family I happen to use the embed code in the document header:

<script src="//use.fontawesome.com/123456whatever.js"></script>

There are various ways to include FA, strokes/folks, but I find this is pretty fast and as I'm using webpack I can just about live with that 1 extra js server call.

And to update this - there's also this JS option for slightly more complex arrows, still with accessibility in mind:

$('.whatever-carousel').owlCarousel({
    navText: ["<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Previous</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-left fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>","<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Next</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-right fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>"]
})

Loads of escaping there, use single quotes instead if preferred.

And in the SCSS just comment out the ::before attrs:

.owl-prev {
        //&::before { content: "\f104"; }
    }
    .owl-next {
        //&::before { content: "\f105"; }
    }

PHP error: Notice: Undefined index:

Make sure the tags correctly closed. And the closing tag will not include inside a loop. (if it contains in a looping structure).

Changing Background Image with CSS3 Animations

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

_x000D_
_x000D_
#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; }
@keyframes changeBg{
   0%,100%  {background-image: url("https://i.stack.imgur.com/YdrqG.png");}
   25% {background-image: url("https://i.stack.imgur.com/2wKWi.png");}
   50% {background-image: url("https://i.stack.imgur.com/HobHO.png");}
   75% {background-image: url("https://i.stack.imgur.com/3hiHO.png");}
}
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_


Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

I had this issue while testing software. Drivers were not signed.

Tip for me was: in cmd line: (administrator) bcdedit /set TESTSIGNING ON and reboot the machine (shutdown -r -t 5)

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.

After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.

How can I create an object and add attributes to it?

These solutions are very helpful during testing. Building on everyone else's answers I do this in Python 2.7.9 (without staticmethod I get a TypeError (unbound method...):

In [11]: auth = type('', (), {})
In [12]: auth.func = staticmethod(lambda i: i * 2)
In [13]: auth.func(2)
Out[13]: 4

Angular Directive refresh on parameter change

angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

How to easily map c++ enums to strings

I have spent more time researching this topic that I'd like to admit. Luckily there are great open source solutions in the wild.

These are two great approaches, even if not well known enough (yet),

wise_enum

  • Standalone smart enum library for C++11/14/17. It supports all of the standard functionality that you would expect from a smart enum class in C++.
  • Limitations: requires at least C++11.

Better Enums

  • Reflective compile-time enum library with clean syntax, in a single header file, and without dependencies.
  • Limitations: based on macros, can't be used inside a class.

ConcurrentHashMap vs Synchronized HashMap

A simple performance test for ConcurrentHashMap vs Synchronized HashMap . The test flow is calling put in one thread and calling get in three threads on Map concurrently. As @trshiv said, ConcurrentHashMap has higher throughput and speed for whose reading operation without lock. The result is when operation times is over 10^7, ConcurrentHashMap is 2x faster than Synchronized HashMap.

How can I install MacVim on OS X?

  1. Download the latest build from https://github.com/macvim-dev/macvim/releases

  2. Expand the archive.

  3. Put MacVim.app into /Applications/.

Done.

ETag vs Header Expires

ETag is used to determine whether a resource should use the copy one. and Expires Header like Cache-Control is told the client that before the cache decades, client should fetch the local resource.

In modern sites, There are often offer a file named hash, like app.98a3cf23.js, so that it's a good practice to use Expires Header. Besides this, it also reduce the cost of network.

Hope it helps ;)

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

adb uninstall <package_name>

can be used to uninstall an app via your PC. If you want this to happen automatically every time you launch your app via Android Studio, you can do this:

  1. In Android Studio, click the drop down list to the left of Run button, and select Edit configurations...
  2. Click on app under Android Application, and in General Tab, find the heading 'Before Launch'
  3. Click the + button, select Run external tool, click the + button in the popup window.
  4. Give some name (Eg adb uninstall) and description, and type adb in Program: and uninstall <your-package-name> in Parameters:. Make sure that the new item is selected when you click Ok in the popup window.

Note: If you do not have adb in your PATH environment variable, give the full path to adb in Program: field (eg /home/user/android/sdk/platform-tools/adb).

Position buttons next to each other in the center of page

your code will look something like this ...

<!doctype html>
<html lang="en">

<head>
<style>
#button1{
width: 300px;
height: 40px;

}
#button2{
width: 300px;
height: 40px;
}
display:inline-block;
</style>

<meta charset="utf-8">
<meta name="Homepage" content="Starting page for the survey website ">

 <title> Survey HomePage</title>
</head>
<body>
<center>
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
 <button type="button home-button" id="button1" >Home</button>
 <button type="button contact-button" id="button2">Contact Us</button>
</center>
</body>
 </html>

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

unique combinations of values in selected columns in pandas data frame and count

You can groupby on cols 'A' and 'B' and call size and then reset_index and rename the generated column:

In [26]:

df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[26]:
     A    B  count
0   no   no      1
1   no  yes      2
2  yes   no      4
3  yes  yes      3

update

A little explanation, by grouping on the 2 columns, this groups rows where A and B values are the same, we call size which returns the number of unique groups:

In[202]:
df1.groupby(['A','B']).size()

Out[202]: 
A    B  
no   no     1
     yes    2
yes  no     4
     yes    3
dtype: int64

So now to restore the grouped columns, we call reset_index:

In[203]:
df1.groupby(['A','B']).size().reset_index()

Out[203]: 
     A    B  0
0   no   no  1
1   no  yes  2
2  yes   no  4
3  yes  yes  3

This restores the indices but the size aggregation is turned into a generated column 0, so we have to rename this:

In[204]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})

Out[204]: 
     A    B  count
0   no   no      1
1   no  yes      2
2  yes   no      4
3  yes  yes      3

groupby does accept the arg as_index which we could have set to False so it doesn't make the grouped columns the index, but this generates a series and you'd still have to restore the indices and so on....:

In[205]:
df1.groupby(['A','B'], as_index=False).size()

Out[205]: 
A    B  
no   no     1
     yes    2
yes  no     4
     yes    3
dtype: int64

Regex that matches integers in between whitespace or start/end of string only

Similar to manojlds but includes the optional negative/positive numbers:

var regex = /^[-+]?\d+$/;

EDIT

If you don't want to allow zeros in the front (023 becomes invalid), you could write it this way:

var regex = /^[-+]?[1-9]\d*$/;

EDIT 2

As @DmitriyLezhnev pointed out, if you want to allow the number 0 to be valid by itself but still invalid when in front of other numbers (example: 0 is valid, but 023 is invalid). Then you could use

var regex = /^([+-]?[1-9]\d*|0)$/

AngularJS - value attribute for select

Try it as below:

var scope = $(this).scope();
alert(JSON.stringify(scope.model.options[$('#selOptions').val()].value));

Disable Logback in SpringBoot

In my case, it was only required to exclude the spring-boot-starter-logging artifact from the spring-boot-starter-security one.

This is in a newly generated spring boot 2.2.6.RELEASE project including the following dependencies:

  • spring-boot-starter-security
  • spring-boot-starter-validation
  • spring-boot-starter-web
  • spring-boot-starter-test

I found out by running mvn dependency:tree and looking for ch.qos.logback.

The spring boot related <dependencies> in my pom.xml looks like this:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>           
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>



</dependencies>

SQL to Query text in access with an apostrophe in it

Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

How can I get the count of milliseconds since midnight for the current?

Calendar.getInstance().get(Calendar.MILLISECOND);

Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

C++ cast to derived class

You can't cast a base object to a derived type - it isn't of that type.

If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:

DerivedType D;
BaseType B;

BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type

DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

If using cocoapods, try reinstalling the pods by running the following command.

pod install

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

ImportError: DLL load failed: The specified module could not be found

(I found this answer from a video: http://www.youtube.com/watch?v=xmvRF7koJ5E)

  1. Download msvcp71.dll and msvcr71.dll from the web.

  2. Save them to your C:\Windows\System32 folder.

  3. Save them to your C:\Windows\SysWOW64 folder as well (if you have a 64-bit operating system).

Now try running your code file in Python and it will load the graph in couple of seconds.

How to position a div scrollbar on the left hand side?

No, you can't change scrollbars placement without any additional issues.

You can change text-direction to right-to-left ( rtl ), but it also change text position inside block.

This code can helps you, but I not sure it works in all browsers and OS.

<element style="direction: rtl; text-align: left;" />

Suppress/ print without b' prefix for bytes in Python 3

If we take a look at the source for bytes.__repr__, it looks as if the b'' is baked into the method.

The most obvious workaround is to manually slice off the b'' from the resulting repr():

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))
b'\x01\x02\x03\x04'

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

CSS, Images, JS not loading in IIS

Use this in configuration section of your web.config file:

<location path="images">
<system.web>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>
</location>
<location path="css">
<system.web>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>
</location>
<location path="js">
<system.web>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>
</location>

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

JavaScript override methods

_x000D_
_x000D_
function A() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 123;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
function B() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 999;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
_x000D_
C = function () {_x000D_
   this.x = 10;_x000D_
   this.y = 20;_x000D_
_x000D_
   this.modify = function() {_x000D_
      this.x = 30;_x000D_
      this.y = 40;_x000D_
   };_x000D_
   _x000D_
   this.sum = function(){_x000D_
 this.modify();_x000D_
 console.log("The sum is: " + (this.x+this.y));_x000D_
   }_x000D_
}_x000D_
_x000D_
A();_x000D_
B();
_x000D_
_x000D_
_x000D_

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

Auto insert date and time in form input field?

var date = new Date();

document.getElementById("date").value = date.getFullYear() + "-" + (date.getMonth()<10?'0':'') + (date.getMonth() + 1) + "-" + (date.getDate()<10?'0':'') + date.getDate();

document.getElementById("hour").value = (date.getHours()<10?'0':'') + date.getHours()  + ":" + (date.getMinutes()<10?'0':'') + date.getMinutes();

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

jQuery: Check if button is clicked

$('#submit1, #submit2').click(function () {
   if (this.id == 'submit1') {
      alert('Submit 1 clicked');
   }
   else if (this.id == 'submit2') {
      alert('Submit 2 clicked');
   }
});

JavaScript: Alert.Show(message) From ASP.NET Code-behind

string script = string.Format("alert('{0}');", cleanMessage);
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
{
    page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
}

dereferencing pointer to incomplete type

Outside of possible scenarios involving whole-program optimization, the code code generated for something like:

struct foo *bar;
struct foo *test(struct foo *whatever, int blah)
{
  return blah ? whatever: bar;
}

will be totally unaffected by what members struct foo might contain. Because make utilities will generally recompile any compilation unit in which the complete definition of a structure appears, even when such changes couldn't actually affect the code generated for them, it's common to omit complete structure definitions from compilation units that don't actually need them, and such omission is generally not worthy of a warning.

A compiler needs to have a complete structure or union definition to know how to handle declarations objects of the type with automatic or static duration, declarations of aggregates containing members of the type, or code which accesses members of the structure or union. If the compiler doesn't have the information needed to perform one of the above operations, it will have no choice but to squawk about it.

Incidentally, there's one more situation where the Standard would allow a compiler to require a complete union definition to be visible but would not require a diagnostic: if two structures start with a Common Initial Sequence, and a union type containing both is visible when the compiler is processing code that uses a pointer of one of the structure types to inspects a member of that Common Initial Sequence, the compiler is required to recognize that such code might be accessing the corresponding member of a structure of the other type. I don't know what compilers if any comply with the Standard when the complete union type is visible but not when it isn't [gcc is prone to generate non-conforming code in either case unless the -fno-strict-aliasing flag is used, in which case it will generate conforming code in both cases] but if one wants to write code that uses the CIS rule in such a fashion as to guarantee correct behavior on conforming compilers, one may need to ensure that complete union type definition is visible; failure to do so may result in a compiler silently generating bogus code.

Solving a "communications link failure" with JDBC and MySQL

I found the solution

since MySQL need the Localhost in-order to work.

go to /etc/network/interfaces file and make sure you have the localhost configuration set there:

auto lo
iface lo inet loopback

NOW RESTART the Networking subsystem and the MySQL Services:

sudo /etc/init.d/networking restart

sudo /etc/init.d/mysql restart

Try it now

Is there an effective tool to convert C# code to Java code?

Well the syntax is almost the same but they rely on different frameworks so the only way to convert is by getting someone who knows both languages and convert the code :) the answer to your question is no there is no "effective" tool to convert c# to java

What is the correct way to free memory in C#

The garbage collector will come around and clean up anything that no longer has references to it. Unless you have unmanaged resources inside Foo, calling Dispose or using a using statement on it won't really help you much.

I'm fairly sure this applies, since it was still in C#. But, I took a game design course using XNA and we spent some time talking about the garbage collector for C#. Garbage collecting is expensive, since you have to check if you have any references to the object you want to collect. So, the GC tries to put this off as long as possible. So, as long as you weren't running out of physical memory when your program went to 700MB, it might just be the GC being lazy and not worrying about it yet.

But, if you just use Foo o outside the loop and create a o = new Foo() each time around, it should all work out fine.

How to pass values between Fragments

This is a stone age question and yet still very relevant. Specially now that Android team is pushing more towards adhering to single activity models, communication between the fragments becomes all the more important. LiveData and Interfaces are perfectly fine ways to tackle this issue. But now Google has finally addressed this problem and tried to bring a much simpler solution using FragmentManager. Here's how it can be done in Kotlin.

In receiver fragment add a listener:

setFragmentResultListener(
    "data_request_key",
    lifecycleOwner,
    FragmentResultListener { requestKey: String, bundle: Bundle ->
        // unpack the bundle and use data
        val frag1Str = bundle.getString("frag1_data_key")

    })

In sender fragment(frag1):

setFragmentResult(
    "data_request_key",
    bundleOf("frag1_data_key" to value)
)

Remember this functionality is only available in fragment-ktx version 1.3.0-alpha04 and up.

Credits and further reading:

A New Way to Pass Data Between Fragments

Android Fragments: Fragment Result

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

Fetch API request timeout?

Building on Endless' excellent answer, I created a helpful utility function.

const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
};
  1. If the timeout is reached before the resource is fetched then the fetch is aborted.
  2. If the resource is fetched before the timeout is reached then the timeout is cleared.
  3. If the input signal is aborted then the fetch is aborted and the timeout is cleared.
const controller = new AbortController();

document.querySelector("button.cancel").addEventListener("click", () => controller.abort());

fetchTimeout("example.json", 5000, { signal: controller.signal })
    .then(response => response.json())
    .then(console.log)
    .catch(error => {
        if (error.name === "AbortError") {
            // fetch aborted either due to timeout or due to user clicking the cancel button
        } else {
            // network error or json parsing error
        }
    });

Hope that helps.

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

How can I write a regex which matches non greedy?

The non-greedy ? works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .. You need to tell them explicitly that you want to match line-breaks too with .

For example,

<img\s.*?>

works fine!

Check the results here.

Also, read about how dot behaves in various regex flavours.

Nth word in a string variable

No expensive forks, no pipes, no bashisms:

$ set -- $STRING
$ eval echo \${$N}
three

But beware of globbing.

SQL Server Restore Error - Access is Denied

I was having the same problem. It turned out that my SQL Server and SQL Server Agent services logon as were running under the Network Services account which didn't have write access to perform the restore of the back up.

I changed both of these services to logon on as Local System Account and this fixed the problem.

jQuery - add additional parameters on submit (NOT ajax)

You don't need to bind the submit event on the click of the submit button just bind the submit event and it will capture the submit event no mater how it gets triggered.

Think what you are wanting is to submit the sortable like you would via ajax. Try doing something like this:

var form = $('#event').submit(function () {
    $.each($('#attendance').sortable('toArray'),function(i, value){
        $("<input>").attr({
            'type':'hidden',
            'name':'attendace['+i+']'
        }).val(value).appendTo(form);
    });
});

How to disable phone number linking in Mobile Safari?

Add this, I think it is what you're looking for:

<meta name = "format-detection" content = "telephone=no">

How to assign the output of a Bash command to a variable?

You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.

All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.

It looks something like this:

NUM_PROCS=$(ps -e | sed 1d | wc -l)

I hope that helps add some handy information to this discussion.

How can I generate a list of consecutive numbers?

Depending on how you want the result, you can also print each number in a for loop:

def numbers():
    for i in range(int(input('How far do you wanna go? '))+1):
        print(i)

So if the user input was 7 for example:

How far do you wanna go? 7
0
1
2
3
4
5
6
7

You can also delete the '+1' in the for loop and place it on the print statement, which will change it to starting at 1 instead of 0.

Collections.emptyList() vs. new instance

The main difference is that Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add elements. (Same applies to the List.of() introduced in Java 9.)

In the rare cases where you do want to modify the returned list, Collections.emptyList() and List.of() are thus not a good choices.

I'd say that returning an immutable list is perfectly fine (and even the preferred way) as long as the contract (documentation) does not explicitly state differently.


In addition, emptyList() might not create a new object with each call.

Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

The implementation of emptyList looks as follows:

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

So if your method (which returns an empty list) is called very often, this approach may even give you slightly better performance both CPU and memory wise.

CSS background image URL failing to load

I know this is really old, but I'm posting my solution anyways since google finds this thread.

background-image: url('./imagefolder/image.jpg');

That is what I do. Two dots means drill back one directory closer to root ".." while one "." should mean start where you are at as if it were root. I was having similar issues but adding that fixed it for me. You can even leave the "." in it when uploading to your host because it should work fine so long as your directory setup is exactly the same.

How do I consume the JSON POST data in an Express application

I think you're conflating the use of the response object with that of the request.

The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.

If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.

For earlier versions of Express (< 4)

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

app.listen(3000);

Test along the lines of:

$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}

Updated for Express 4+

Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser

var express = require('express')
  , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Update for Express 4.16+

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');

var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

How to add default value for html <textarea>?

Placeholder cannot set the default value for text area. You can use

<textarea rows="10" cols="55" name="description"> /*Enter default value here to display content</textarea>

This is the tag if you are using it for database connection. You may use different syntax if you are using other languages than php.For php :

e.g.:

<textarea rows="10" cols="55" name="description" required><?php echo $description; ?></textarea>

required command minimizes efforts needed to check empty fields using php.

Finalize vs Dispose

Others have already covered the difference between Dispose and Finalize (btw the Finalize method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the Finalize method comes in handy.

Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the using construct.

Others are a bit more difficult. WaitEventHandles for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call Dispose on these? As a safeguard types like these implement a Finalize method, which makes sure resources are disposed when the instance is no longer referenced by the application.

Is the order of elements in a JSON list preserved?

"Is the order of elements in a JSON list maintained?" is not a good question. You need to ask "Is the order of elements in a JSON list maintained when doing [...] ?" As Felix King pointed out, JSON is a textual data format. It doesn't mutate without a reason. Do not confuse a JSON string with a (JavaScript) object.

You're probably talking about operations like JSON.stringify(JSON.parse(...)). Now the answer is: It depends on the implementation. 99%* of JSON parsers do not maintain the order of objects, and do maintain the order of arrays, but you might as well use JSON to store something like

{
    "son": "David",
    "daughter": "Julia",
    "son": "Tom",
    "daughter": "Clara"
}

and use a parser that maintains order of objects.

*probably even more :)

How to parse a CSV file using PHP

Handy one liner to parse a CSV file into an array

$csv = array_map('str_getcsv', file('data.csv'));

How to check if ZooKeeper is running or up from command prompt?

I did some test:

When it's running:

$ /usr/lib/zookeeper/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/lib/zookeeper/bin/../conf/zoo.cfg
Mode: follower

When it's stopped:

$ zkServer status                                                                                                                                
JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Error contacting service. It is probably not running.

I'm not running on the same machine, but you get the idea.

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

Difference between \b and \B in regex

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

Source: http://www.regular-expressions.info/wordboundaries.html

Images can't contain alpha channels or transparencies

I've found you can also just re-export the png's in Preview, but uncheck the Alpha checkbox when saving.

enter image description here

How to remove outliers from a dataset

I looked up for packages related to removing outliers, and found this package (surprisingly called "outliers"!): https://cran.r-project.org/web/packages/outliers/outliers.pdf
if you go through it you see different ways of removing outliers and among them I found rm.outlier most convenient one to use and as it says in the link above: "If the outlier is detected and confirmed by statistical tests, this function can remove it or replace by sample mean or median" and also here is the usage part from the same source:
"Usage

rm.outlier(x, fill = FALSE, median = FALSE, opposite = FALSE)

Arguments
x a dataset, most frequently a vector. If argument is a dataframe, then outlier is removed from each column by sapply. The same behavior is applied by apply when the matrix is given.
fill If set to TRUE, the median or mean is placed instead of outlier. Otherwise, the outlier(s) is/are simply removed.
median If set to TRUE, median is used instead of mean in outlier replacement. opposite if set to TRUE, gives opposite value (if largest value has maximum difference from the mean, it gives smallest and vice versa) "

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Use the .scrollHeight property of the DOM node: $('#your_div')[0].scrollHeight

Popup window in winform c#

Just create another form (let's call it formPopup) using Visual Studio. In a button handler write the following code:

var formPopup = new Form();
formPopup.Show(this); // if you need non-modal window

If you need a non-modal window use: formPopup.Show();. If you need a dialog (so your code will hang on this invocation until you close the opened form) use: formPopup.ShowDialog()

Is unsigned integer subtraction defined behavior?

The result of a subtraction generating a negative number in an unsigned type is well-defined:

  1. [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (ISO/IEC 9899:1999 (E) §6.2.5/9)

As you can see, (unsigned)0 - (unsigned)1 equals -1 modulo UINT_MAX+1, or in other words, UINT_MAX.

Note that although it does say "A computation involving unsigned operands can never overflow", which might lead you to believe that it applies only for exceeding the upper limit, this is presented as a motivation for the actual binding part of the sentence: "a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This phrase is not restricted to overflow of the upper bound of the type, and applies equally to values too low to be represented.

Load image from resources

ResourceManager will work if your image is in a resource file. If it is just a file in your project (let's say the root) you can get it using something like this:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel);
this.pictureBox1.Image = Image.FromStream(file);

Or if you're in WPF:

    private ImageSource GetImage(string channel)
    {
        StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" + channel, UriKind.Relative));
        BitmapImage bmp = new BitmapImage();
        bmp.BeginInit();
        bmp.StreamSource = sri.Stream;
        bmp.EndInit();

        return bmp;
    }

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

TLDR? Try: file = open(filename, encoding='cp437)

Why? When one use:

file = open(filename)
text = file.read()

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

file = open(filename, errors='replace')

Another workaround is to use:

file = open(filename, errors='ignore')

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

file = open(filename, encoding='cp437')

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

I had this message when using git extensions for windows. My fix was to simply close git extensions then open again as administrator

Create list or arrays in Windows Batch

Array type does not exist

There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.

Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.

  • As for echoing to a file echo variable >> filepath works for echoing the contents of a variable to a file,
  • and echo. (the period is not a typo) works for echoing a newline character.

I think that these two together should work to accomplish what you need.

Further reading

Why does this CSS margin-top style not work?

What @BoltClock mentioned are pretty solid. And Here I just want to add several more solutions for this problem. check this w3c_collapsing margin. The green parts are the potential thought how this problem can be solved.

Solution 1

Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).

that means I can add float:left to either #outer or #inner demo1.

also notice that float would invalidate the auto in margin.

Solution 2

Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.

other than visible, let's put overflow: hidden into #outer. And this way seems pretty simple and decent. I like it.

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    overflow: hidden;
}
#inner {
    background: #FFCC33;
    height: 50px;
    margin: 50px;
}

Solution 3

Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    position: absolute; 
}
#inner{
    background: #FFCC33;
    height: 50px;
    margin: 50px;
}

or

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    position: relative; 
}
#inner {
    background: #FFCC33;
    height: 50px;
    margin: 50px;
    position: absolute;
}

these two methods will break the normal flow of div

Solution 4

Margins of inline-block boxes do not collapse (not even with their in-flow children).

is the same as @enderskill

Solution 5

The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.

This has not much work to do with the question since it is the collapsing margin between siblings. it generally means if a top-box has margin-bottom: 30px and a sibling-box has margin-top: 10px. The total margin between them is 30px instead of 40px.

Solution 6

The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.

This is very interesting and I can just add one top border line

#outer{
    width: 500px;
    height: 200px;
    background: #FFCCCC;
    margin: 50px auto;
    border-top: 1px solid red;

}
#inner {
    background: #FFCC33;
    height: 50px;
    margin: 50px;

}

And Also <div> is block-level in default, so you don't have to declare it on purpose. Sorry for not being able to post more than 2 links and images due to my novice reputation. At least you know where the problem comes from next time you see something similar.

How to declare a vector of zeros in R

You can also use the matrix command, to create a matrix with n lines and m columns, filled with zeros.

matrix(0, n, m)

How to use C++ in Go

You might need to add -lc++ to the LDFlags for Golang/CGo to recognize the need for the standard library.

Hibernate Auto Increment ID

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

It seems SEQUENCE + specifying the sequence name worked for you.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Use jquery click to handle anchor onClick()

<div class = "solTitle"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>

<div class= "solTitle"> <a href = "#"  id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>



$(document).ready(function(){
    $('.solTitle a').click(function(e) {
        e.preventDefault();
        alert('here in');
         var divId = 'summary' +$(this).attr('id');

        document.getElementById(divId).className = ''; /* or $('#'+divid).removeAttr('class'); */

    });
 });

I changed few things:

  1. remove the onclick attr and bind click event inside the document.ready
  2. changed solTitle to be an ID to a CLASS: id cant be repeated

"Series objects are mutable and cannot be hashed" error

gene_name = no_headers.iloc[1:,[1]]

This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:

gene_name[x]

you now have a Series object with a single value. You can't hash the Series.

The solution is to create Series from the start.

gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]

Also, where you have orph_dict[gene_name[x]] =+ 1, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.

How do I bind a WPF DataGrid to a variable number of columns?

I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.

Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the objects in ItemsSource and generates a column for each one. Perhaps I could generate a type on the fly with a property for each column but this is getting way off track.

Since this problem is so easily sovled in code I will stick with a simple extension method I call whenever the data context is updated with new columns:

public static void GenerateColumns(this DataGrid dataGrid, IEnumerable<ColumnSchema> columns)
{
    dataGrid.Columns.Clear();

    int index = 0;
    foreach (var column in columns)
    {
        dataGrid.Columns.Add(new DataGridTextColumn
        {
            Header = column.Name,
            Binding = new Binding(string.Format("[{0}]", index++))
        });
    }
}

// E.g. myGrid.GenerateColumns(schema);

C default arguments

OpenCV uses something like:

/* in the header file */

#ifdef __cplusplus
    /* in case the compiler is a C++ compiler */
    #define DEFAULT_VALUE(value) = value
#else
    /* otherwise, C compiler, do nothing */
    #define DEFAULT_VALUE(value)
#endif

void window_set_size(unsigned int width  DEFAULT_VALUE(640),
                     unsigned int height DEFAULT_VALUE(400));

If the user doesn't know what he should write, this trick can be helpful:

usage example

How do you redirect HTTPS to HTTP?

Keep in mind that the Rewrite engine only kicks in once the HTTP request has been received - which means you would still need a certificate, in order for the client to set up the connection to send the request over!

However if the backup machine will appear to have the same hostname (as far as the client is concerned), then there should be no reason you can't use the same certificate as the main production machine.

Get scroll position using jquery

cross browser variant

$(document).scrollTop();

How can I find out if I have Xcode commandline tools installed?

For macOS catalina try this : open Xcode. if not existing. download from App store (about 11GB) then open Xcode>open developer tool>more developer tool and used my apple id to download a compatible command line tool. Then, after downloading, I opened Xcode>Preferences>Locations>Command Line Tool and selected the newly downloaded command line tool from downloads.

Why would you use String.Equals over ==?

There is practical difference between string.Equals and ==

bool result = false;

object obj = "String";    
string str2 = "String";
string str3 = typeof(string).Name;
string str4 = "String";
object obj2 = str3;

// Comparision between object obj and string str2 -- Com 1
result = string.Equals(obj, str2);// true
result = String.ReferenceEquals(obj, str2); // true
result = (obj == str2);// true

// Comparision between object obj and string str3 -- Com 2
result = string.Equals(obj, str3);// true
result = String.ReferenceEquals(obj, str3); // false
result = (obj == str3);// false

// Comparision between object obj and string str4 -- Com 3
result = string.Equals(obj, str4);// true
result = String.ReferenceEquals(obj, str4); // true
result = (obj == str4);// true

// Comparision between string str2 and string str3 -- Com 4
result = string.Equals(str2, str3);// true
result = String.ReferenceEquals(str2, str3); // false
result = (str2 == str3);// true

// Comparision between string str2 and string str4 -- Com 5
result = string.Equals(str2, str4);// true
result = String.ReferenceEquals(str2, str4); // true
result = (str2 == str4);// true

// Comparision between string str3 and string str4 -- Com 6
result = string.Equals(str3, str4);// true
result = String.ReferenceEquals(str3, str4); // false
result = (str3 == str4);// true

// Comparision between object obj and object obj2 -- Com 7
result = String.Equals(obj, obj2);// true
result = String.ReferenceEquals(obj, obj2); // false
result = (obj == obj2);// false

Adding Watch

obj     "String" {1#}   object {string}
str2    "String" {1#}   string
str3    "String" {5#}   string
str4    "String" {1#}   string
obj2    "String" {5#}   object {string}

Now look at {1#} and {5#}

obj, str2, str4 and obj2 references are same.

obj and obj2 are object type and others are string type

Conclusion:

  1. com1: result = (obj == str2);// true
    • compares object and string so performs a reference equality check
    • obj and str2 point to the same reference so the result is true
  2. com2: result = (obj == str3);// false
    • compares object and string so performs a reference equality check
    • obj and str3 point to the different references so the result is false
  3. com3: result = (obj == str4);// true
    • compares object and string so performs a reference equality check
    • obj and str4 point to the same reference so the result is true
  4. com4: result = (str2 == str3);// true
    • compares string and string so performs a string value check
    • str2 and str3 are both "String" so the result is true
  5. com5: result = (str2 == str4);// true
    • compares string and string so performs a string value check
    • str2 and str4 are both "String" so the result is true
  6. com6: result = (str3 == str4);// true
    • compares string and string so performs a string value check
    • str3 and str4 are both "String" so the result is true
  7. com7: result = (obj == obj2);// false  - compares object and object so performs a reference equality check      - obj and obj2 point to the different references so the result is false

Padding between ActionBar's home icon and title

I used AppBarLayout and custom ImageButton do to so.

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    android:background="@android:color/transparent"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">

       <ImageView
           android:layout_width="32dp"
           android:layout_height="32dp"
           android:src="@drawable/selector_back_button"
           android:layout_centerVertical="true"
           android:layout_marginLeft="8dp"
           android:id="@+id/back_button"/>

       <android.support.v7.widget.Toolbar
           android:id="@+id/toolbar"
           android:layout_width="match_parent"
           android:layout_height="?attr/actionBarSize"
           app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </RelativeLayout>    
</android.support.design.widget.AppBarLayout>

My Java code:

findViewById(R.id.appbar).bringToFront();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
getSupportActionBar().setDisplayShowTitleEnabled(false);

HTML input file selection event not firing upon selecting the same file

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); this.value=null; return false;" type='file'>
    <br>
    <input type='submit' value='Upload'>
</form>

this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;

Here is a FIDDLE

xcode library not found

In my case, the project uses CocoaPods. And some files are missing from my project.

So I install it from CocoaPods: https://cocoapods.org/.

And if the project uses CocoaPods we've to be aware to always open the .xcworkspace folder instead of the .xcodeproj folder in the Xcode.

Format date to MM/dd/yyyy in JavaScript

Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.

_x000D_
_x000D_
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
    alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
_x000D_
_x000D_

Tricks to manage the available memory in an R session

I quite like the improved objects function developed by Dirk. Much of the time though, a more basic output with the object name and size is sufficient for me. Here's a simpler function with a similar objective. Memory use can be ordered alphabetically or by size, can be limited to a certain number of objects, and can be ordered ascending or descending. Also, I often work with data that are 1GB+, so the function changes units accordingly.

showMemoryUse <- function(sort="size", decreasing=FALSE, limit) {

  objectList <- ls(parent.frame())

  oneKB <- 1024
  oneMB <- 1048576
  oneGB <- 1073741824

  memoryUse <- sapply(objectList, function(x) as.numeric(object.size(eval(parse(text=x)))))

  memListing <- sapply(memoryUse, function(size) {
        if (size >= oneGB) return(paste(round(size/oneGB,2), "GB"))
        else if (size >= oneMB) return(paste(round(size/oneMB,2), "MB"))
        else if (size >= oneKB) return(paste(round(size/oneKB,2), "kB"))
        else return(paste(size, "bytes"))
      })

  memListing <- data.frame(objectName=names(memListing),memorySize=memListing,row.names=NULL)

  if (sort=="alphabetical") memListing <- memListing[order(memListing$objectName,decreasing=decreasing),] 
  else memListing <- memListing[order(memoryUse,decreasing=decreasing),] #will run if sort not specified or "size"

  if(!missing(limit)) memListing <- memListing[1:limit,]

  print(memListing, row.names=FALSE)
  return(invisible(memListing))
}

And here is some example output:

> showMemoryUse(decreasing=TRUE, limit=5)
      objectName memorySize
       coherData  713.75 MB
 spec.pgram_mine  149.63 kB
       stoch.reg  145.88 kB
      describeBy    82.5 kB
      lmBandpass   68.41 kB

conditional Updating a list using LINQ

If you really want to use linq, you can do something like this

li= (from tl in li
    select new Myclass
    {
        name = tl.name,
        age = (tl.name == "di" ? 10 : (tl.name == "marks" ? 20 : 30))

    }).ToList();

or

li = li.Select(ex => new MyClass { name = ex.name, age = (ex.name == "di" ? 10 : (ex.name == "marks" ? 20 : 30)) }).ToList();

This assumes that there are only 3 types of name. I would externalize that part into a function to make it more manageable.

How to change heatmap.2 color range in R?

Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)

OnClick vs OnClientClick for an asp:CheckBox?

You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx

Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.

Best way to check if a drop down list contains a value?

If 0 is your default value, you can just use a simple assignment:

ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();

This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.

I use this mechanism quite a lot and find it very handy.

Change URL parameters

My solution:

const setParams = (data) => {
    if (typeof data !== 'undefined' && typeof data !== 'object') {
        return
    }

    let url = new URL(window.location.href)
    const params = new URLSearchParams(url.search)

    for (const key of Object.keys(data)) {
        if (data[key] == 0) {
            params.delete(key)
        } else {
            params.set(key, data[key])
        }
    }

    url.search = params
    url = url.toString()
    window.history.replaceState({ url: url }, null, url)
}

Then just call "setParams" and pass an object with data you want to set.

Example:

$('select').on('change', e => {
    const $this = $(e.currentTarget)
    setParams({ $this.attr('name'): $this.val() })
})

In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.

Hope this helps yall

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

One way to order by positive integers, when they are stored as varchar, is to order by the length first and then the value:

order by len(registration_no), registration_no

This is particularly useful when the column might contain non-numeric values.

Note: in some databases, the function to get the length of a string might be called length() instead of len().

Query to count the number of tables I have in MySQL

To count number of tables just do this:

USE your_db_name;    -- set database
SHOW TABLES;         -- tables lists
SELECT FOUND_ROWS(); -- number of tables

Sometimes easy things will do the work.

Converting Hexadecimal String to Decimal Integer

This is a little library that should help you with hexadecimals in Java: https://github.com/PatrykSitko/HEX4J

It can convert from and to hexadecimals. It supports:

  • byte
  • boolean
  • char
  • char[]
  • String
  • short
  • int
  • long
  • float
  • double (signed and unsigned)

With it, you can convert your String to hexadecimal and the hexadecimal to a float/double.

Example:

String hexValue = HEX4J.Hexadecimal.from.String("Hello World");
double doubleValue = HEX4J.Hexadecimal.to.Double(hexValue);

Spring,Request method 'POST' not supported

Your user.jsp:

 <form:form action="profile/proffesional" modelAttribute="PROFESSIONAL">
     ---
     ---
    </form:form>

In your controller class:

(make it as a meaning full method name..Hear i think you are insert record in DB.)

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
    public @ResponseBody
    String proffessionalDetails(
            @ModelAttribute UserProfessionalForm professionalForm,
            BindingResult result, Model model) {

        UserProfileVO userProfileVO = new UserProfileVO();

        userProfileVO.setUser(sessionData.getUser());
        userService.saveUserProfile(userProfileVO);
        model.addAttribute("PROFESSIONAL", professionalForm);

        return "Your Professional Details Updated";

    }

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

Have you tried using the "auto-fill" in Excel?

If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.

You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).

Export javascript data to CSV file without server interaction

There's always the HTML5 download attribute :

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.

If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'myFile.csv';

document.body.appendChild(a);
a.click();

FIDDLE

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).

An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.


Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvString]);
    window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();
}

How to set only time part of a DateTime variable in C#

Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:

var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);

How to send email from SQL Server?

You can do it with a cursor also. Assuming that you have created an Account and a Profile e.g. "profile" and an Account and you have the table that holds the emails ready e.g. "EmailMessageTable" you can do the following:

USE database_name
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE mass_email AS
declare @email nvarchar (50) 
declare @body nvarchar (255)  

declare test_cur cursor for             
SELECT email from [dbo].[EmailMessageTable]

open test_cur                                        

fetch next from test_cur into   
@email     
while @@fetch_status = 0       
begin                                    

set @body = (SELECT body from [dbo].[EmailMessageTable] where email = @email)
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'profile',
    @recipients = @email,
    @body = @body,
    @subject = 'Credentials for Web';
fetch next from test_cur into  
@email 
end    
close test_cur   
deallocate test_cur

After that all you have to do is execute the Stored Procedure

EXECUTE mass_email
GO

ASP.NET page life cycle explanation

Partial Class _Default
    Inherits System.Web.UI.Page
    Dim str As String

    Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed

        str += "PAGE DISPOSED" & "<br />"
    End Sub

    Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
        str += "PAGE ERROR " & "<br />"
    End Sub

    Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        str += "PAGE INIT " & "<br />"
    End Sub

    Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
        str += "INIT Complte " & "<br />"
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        str += "PAGE LOAD " & "<br />"

    End Sub

    Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
        str += "PAGE LOAD Complete " & "<br />"
    End Sub

    Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
        str = ""
        str += "PAGE PRE INIT" & "<br />"
    End Sub

    Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
        str += "PAGE PRE LOAD " & "<br />"
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        str += "PAGE PRE RENDER " & "<br />"
    End Sub

    Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
        str += "PAGE PRE RENDER COMPLETE " & "<br />"
    End Sub

    Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
        str += "PAGE SAVE STATE COMPLTE  " & "<br />"
        lbl.Text = str
    End Sub

    Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
        'Response.Write("PAGE UN LOAD\n")
    End Sub
End Class

Object creation on the stack/heap?

The two forms are the same with one exception: temporarily, the new (Object *) has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

Git merge master into feature branch

You should be able to rebase your branch on master:

git checkout feature1
git rebase master

Manage all conflicts that arise. When you get to the commits with the bugfixes (already in master), Git will say that there were no changes and that maybe they were already applied. You then continue the rebase (while skipping the commits already in master) with

git rebase --skip

If you perform a git log on your feature branch, you'll see the bugfix commit appear only once, and in the master portion.

For a more detailed discussion, take a look at the Git book documentation on git rebase (https://git-scm.com/docs/git-rebase) which cover this exact use case.

================ Edit for additional context ====================

This answer was provided specifically for the question asked by @theomega, taking his particular situation into account. Note this part:

I want to prevent [...] commits on my feature branch which have no relation to the feature implementation.

Rebasing his private branch on master is exactly what will yield that result. In contrast, merging master into his branch would precisely do what he specifically does not want to happen: adding a commit that is not related to the feature implementation he is working on via his branch.

To address the users that read the question title, skip over the actual content and context of the question, and then only read the top answer blindly assuming it will always apply to their (different) use case, allow me to elaborate:

  • only rebase private branches (i.e. that only exist in your local repository and haven't been shared with others). Rebasing shared branches would "break" the copies other people may have.
  • if you want to integrate changes from a branch (whether it's master or another branch) into a branch that is public (e.g. you've pushed the branch to open a pull request, but there are now conflicts with master, and you need to update your branch to resolve those conflicts) you'll need to merge them in (e.g. with git merge master as in @Sven's answer).
  • you can also merge branches into your local private branches if that's your preference, but be aware that it will result in "foreign" commits in your branch.

Finally, if you're unhappy with the fact that this answer is not the best fit for your situation even though it was for @theomega, adding a comment below won't be particularly helpful: I don't control which answer is selected, only @theomega does.

How to do a SOAP Web Service call from Java class?

I found a much simpler alternative way to generating soap message. Given a Person Object:

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
  private String name;
  private int age;
  private String address; //setter and getters below
}

Below is a simple Soap Message Generator:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Slf4j
public class SoapGenerator {

  protected static final ObjectMapper XML_MAPPER = new XmlMapper()
      .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .registerModule(new JavaTimeModule());

  private static final String SOAP_BODY_OPEN = "<soap:Body>";
  private static final String SOAP_BODY_CLOSE = "</soap:Body>";
  private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
  private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";

  public static String soapWrap(String xml) {
    return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
  }

  public static String soapUnwrap(String xml) {
    return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
  }
}

You can use by:

 public static void main(String[] args) throws Exception{
        Person p = new Person();
        p.setName("Test");
        p.setAge(12);

        String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
        log.info("Generated String");
        log.info(xml);
      }

How can I parse a string with a comma thousand separator to a number?

const parseLocaleNumber = strNum => {
    const decSep = (1.1).toLocaleString().substring(1, 2);
    const formatted = strNum
        .replace(new RegExp(`([${decSep}])(?=.*\\1)`, 'g'), '')
        .replace(new RegExp(`[^0-9${decSep}]`, 'g'), '');
    return Number(formatted.replace(decSep, '.'));
};

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I had dialog showing function:

void showDialog(){
    new AlertDialog.Builder(MyActivity.this)
    ...
    .show();
}

I was getting this error and i just had to check isFinishing() before calling this dialog showing function.

if(!isFinishing())
    showDialog();

How to change the background color of Action Bar's Option Menu in Android 4.2?

If you read this, it's probably because all the previous answers didn't work for your Holo Dark based theme.

Holo Dark uses an additional wrapper for the PopupMenus, so after doing what Jonik suggested you have to add the following style to your 'xml' file:

<style name="PopupWrapper" parent="@android:style/Theme.Holo">
    <item name="android:popupMenuStyle">@style/YourPopupMenu</item>
</style>

Then reference it in your theme block:

<style name="Your.cool.Theme" parent="@android:style/Theme.Holo">
    .
    .
    .
    <item name="android:actionBarWidgetTheme">@style/PopupWrapper</item>
</style>

That's it!

What's the best way to determine which version of Oracle client I'm running?

In Windows -> use Command Promt:

tnsping localhost

It show the version and if is installed 32 o 64 bit client, for example:

TNS Ping Utility for 64-bit Windows: Version 10.2.0.4.0 - Production on 03-MAR-2015 16:47:26

Source: https://decipherinfosys.wordpress.com/2007/02/10/checking-for-oracle-client-version-on-windows/

How do I get milliseconds from epoch (1970-01-01) in Java?

You can also try

  Calendar calendar = Calendar.getInstance();
  System.out.println(calendar.getTimeInMillis());

getTimeInMillis() - the current time as UTC milliseconds from the epoch