问:
Why doesn't the Value get replaced in the variable?
```<code>A='A'
B='B'
C='C'
D='D'
E='E'
F='F'
G='G'
H='H'
I='I'
list1=[A,B,C]
list2=[D,E,F]
list3=[G,H,I]

def Output():
    print(list1)
    print(list2)
    print(list3)

Output()

print('The object of Tic Tac Toe is to get three in a row. You play on a three by three game board. The first player is known as X and the second is O. Players alternate placing Xs and Os on the game board until either oppent has three in a row or all nine squares are filled. X always goes first, and in the event that no one has three in a row, the stalemate is called a cat game.')
print()
print('This is a two player game. Single-player Coming soon!')
print()
print('You must place your letter by choosing a letter from above to decide the co-ordinates. The first player starts with X, and the second player starts with O.')

Decision=input('Enter Co-ordinate of First player:')
if Decision == A:
    A ='X'
if Decision == B:
    B = 'X'
if Decision == C:
    C ='X'
if Decision == D:
    D ='X'
if Decision == E:
    E ='X'
if Decision == F:
    F ='X'
if Decision == G:
    G ='X'
if Decision == H:
    H ='X'
if Decision == I:
    I ='X'
Output()
</code>```

<p>This was a code I started writing for Tic Tac Toe. Whenever I enter the Co-ordinate and then use the Output Function, the letter X doesn't appear in the place of the co-ordinate entered. </p>

答:
Because when you do :

```<code>if Decision == A:
    A ='X'
</code>```

Yes you are changing the value but where are you storing changed stuff ??

For that, you have to tell the list to change at that index and for that:

```<code>if Decision == A:
    list1[index_no] = 'value'
</code>```

so :

```<code>if Decision == A:
        list1[0] = 'X'
</code>```

Body:
A='A'
B='B'
C='C'
D='D'
E='E'
F='F'
G='G'
H='H'
I='I'
list1=[A,B,C]
list2=[D,E,F]
list3=[G,H,I]

def Output():
    print(list1)
    print(list2)
    print(list3)

Output()

print('The object of Tic Tac Toe is to get three in a row. You play on a three by three game board. The first player is known as X and the second is O. Players alternate placing Xs and Os on the game board until either oppent has three in a row or all nine squares are filled. X always goes first, and in the event that no one has three in a row, the stalemate is called a cat game.')
print()
print('This is a two player game. Single-player Coming soon!')
print()
print('You must place your letter by choosing a letter from above to decide the co-ordinates. The first player starts with X, and the second player starts with O.')

Decision=input('Enter Co-ordinate of First player:')
if Decision == A:
    A ='X'
if Decision == B:
    B = 'X'
if Decision == C:
    C ='X'
if Decision == D:
    D ='X'
if Decision == E:
    E ='X'
if Decision == F:
    F ='X'
if Decision == G:
    G ='X'
if Decision == H:
    H ='X'
if Decision == I:
    I ='X'
Output()

This was a code I started writing for Tic Tac Toe. Whenever I enter the Co-ordinate and then use the Output Function, the letter X doesn't appear in the place of the co-ordinate entered.

Body:
Because when you do :

if Decision == A:
    A ='X'

Yes you are changing the value but where are you storing changed stuff ??

For that, you have to tell the list to change at that index and for that:

if Decision == A:
    list1[index_no] = 'value'

so :

if Decision == A:
        list1[0] = 'X'


来源: stackexchange

问:
how to calculate binomial coefficents with non-integer numbers
I know how to calculate binomial coefficients for choose(5,2), but now I want to know if there is a function that I can calculate choose(5,2.1) in python or R programming language?</p>

答:
In R you could make a function like this using gamma:

```<code>choose <- function(x, y) {
  return(gamma(x+1)/(gamma(y+1)*gamma(x-y+1)))
}

print(choose(5,2.1)) # 10.30404
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In R you could make a function like this using gamma:

choose <- function(x, y) {
  return(gamma(x+1)/(gamma(y+1)*gamma(x-y+1)))
}

print(choose(5,2.1)) # 10.30404


问:
Firefox Extension API - permissions.request may only be called from a user input handler?
I'm using the Firefox permissions API documented HERE

I'm having a problem with the request method, wherein all of my permissions requests result in:

Error: permissions.request may only be called from a user input handler

You can produce this in firefox by debugging any addon or extension and entering browser.permissions.request({origins: ["https://google.com/*"]}) into the console.

I find it hard to swallow that a permissions request must always have a user input event callback in the parent stack trace.  I'm using Vue.js, and my Permissions are due to user interaction, but my user interactions are decoupled from the events they trigger.

What counts as a user input handler?

Why does it work like this?

Is there a good work-around?

答:
What counts as a user input handler?

A DOM event handler that corresponds to user input (e.g., target.addEventHandler("click", ...) or a WebExtension event listener that corresponds to user input (e.g., browser.browserAction.onClicked.addListener(...)

Why does it work like this?

Partly for basic UX (if a user is not directly interacting with an extension and a prompt for the extension suddenly prompts up, it can easily confuse them), but also to avoid clickjacking attacks where the prompt is put up at a carefully chosen moment when the user is likely to be expecting some unrelated prompt.

Is there a good work-around?

I think just organizing your code so that you request permissions from a user input handler is probably your best bet.


问:
Nodejs - parsing json retrieved from web

I'm trying to parse a json retrieved from the web (https://api.coinmarketcap.com/v1/ticker/?limit=3) and be able to select the name and price_usd. For reference:

```<code>[
{
    "id": "bitcoin",
    "name": "Bitcoin",
    "symbol": "BTC",
    "rank": "1",
    "price_usd": "16148.3",
    "price_btc": "1.0",
    "24h_volume_usd": "18799600000.0",
    "market_cap_usd": "270147332945",
    "available_supply": "16729150.0",
    "total_supply": "16729150.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "-0.28",
    "percent_change_24h": "-4.64",
    "percent_change_7d": "45.79",
    "last_updated": "1512792553"
},
{
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_usd": "471.833",
    "price_btc": "0.0296001",
    "24h_volume_usd": "2170950000.0",
    "market_cap_usd": "45401368016.0",
    "available_supply": "96223384.0",
    "total_supply": "96223384.0",
    "max_supply": null,
    "percent_change_1h": "0.01",
    "percent_change_24h": "9.29",
    "percent_change_7d": "0.65",
    "last_updated": "1512792556"
},
{
    "id": "bitcoin-cash",
    "name": "Bitcoin Cash",
    "symbol": "BCH",
    "rank": "3",
    "price_usd": "1510.48",
    "price_btc": "0.094759",
    "24h_volume_usd": "2229320000.0",
    "market_cap_usd": "25444318815.0",
    "available_supply": "16845188.0",
    "total_supply": "16845188.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "0.6",
    "percent_change_24h": "1.29",
    "percent_change_7d": "2.64",
    "last_updated": "1512792581"
    }
]
</code>```

Here's the code I currently have:

```<code>var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';
var dataResponse = '';
var body = '';

function retrieveData() {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            dataResponse = JSON.parse(body);
        });

    }).on('error', function(e) {
          console.log("Error: ", e);
    });

}

retrieveData();

var temp = (dataResponse[0]);

console.log(temp);
</code>```

I want to be able to get something like and be able to select the name and price:

```<code>        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "16148.3",
        "price_btc": "1.0",
        "24h_volume_usd": "18799600000.0",
        "market_cap_usd": "270147332945",
        "available_supply": "16729150.0",
        "total_supply": "16729150.0",
        "max_supply": "21000000.0",
        "percent_change_1h": "-0.28",
        "percent_change_24h": "-4.64",
        "percent_change_7d": "45.79",
        "last_updated": "1512792553"
</code>```

The error I get is that it logs an undefined. I'm not sure what I'm doing wrong. How would I go selecting the name also? Would I split each block into an array and select them by indexing?

答: Your issue is that the function receiveData is asynchronous and the console.log is actually ran before the dataResponse array is set.  There is a good write up about asynchronous code and how to handle it here: How do I return the response from an asynchronous call?

Body:
I'm trying to parse a json retrieved from the web (https://api.coinmarketcap.com/v1/ticker/?limit=3) and be able to select the name and price_usd. For reference:

[
{
    "id": "bitcoin",
    "name": "Bitcoin",
    "symbol": "BTC",
    "rank": "1",
    "price_usd": "16148.3",
    "price_btc": "1.0",
    "24h_volume_usd": "18799600000.0",
    "market_cap_usd": "270147332945",
    "available_supply": "16729150.0",
    "total_supply": "16729150.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "-0.28",
    "percent_change_24h": "-4.64",
    "percent_change_7d": "45.79",
    "last_updated": "1512792553"
},
{
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_usd": "471.833",
    "price_btc": "0.0296001",
    "24h_volume_usd": "2170950000.0",
    "market_cap_usd": "45401368016.0",
    "available_supply": "96223384.0",
    "total_supply": "96223384.0",
    "max_supply": null,
    "percent_change_1h": "0.01",
    "percent_change_24h": "9.29",
    "percent_change_7d": "0.65",
    "last_updated": "1512792556"
},
{
    "id": "bitcoin-cash",
    "name": "Bitcoin Cash",
    "symbol": "BCH",
    "rank": "3",
    "price_usd": "1510.48",
    "price_btc": "0.094759",
    "24h_volume_usd": "2229320000.0",
    "market_cap_usd": "25444318815.0",
    "available_supply": "16845188.0",
    "total_supply": "16845188.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "0.6",
    "percent_change_24h": "1.29",
    "percent_change_7d": "2.64",
    "last_updated": "1512792581"
    }
]

Here's the code I currently have:

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';
var dataResponse = '';
var body = '';

function retrieveData() {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            dataResponse = JSON.parse(body);
        });

    }).on('error', function(e) {
          console.log("Error: ", e);
    });

}

retrieveData();

var temp = (dataResponse[0]);

console.log(temp);

I want to be able to get something like and be able to select the name and price:

        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "16148.3",
        "price_btc": "1.0",
        "24h_volume_usd": "18799600000.0",
        "market_cap_usd": "270147332945",
        "available_supply": "16729150.0",
        "total_supply": "16729150.0",
        "max_supply": "21000000.0",
        "percent_change_1h": "-0.28",
        "percent_change_24h": "-4.64",
        "percent_change_7d": "45.79",
        "last_updated": "1512792553"

The error I get is that it logs an undefined. I'm not sure what I'm doing wrong. How would I go selecting the name also? Would I split each block into an array and select them by indexing?


问:
What will be the best embedded database to be used with a small Java desktop application?
My requirements are

Embedded Database

Easy Integration with Netbeans IDE

Should be able to develop using JPA

Free of cost

Size of the database should be minimum

Please do suggest me a database with the above mentioned features and some pointers to good tutorials regarding that.

答: H2 database is also a good choice.</p>

ContentLicense: CC BY-SA 2.5

Body: H2 database is also a good choice.


问:
Apply a directive conditionally
I am using Material 2 to add md-raised-button. I want to apply this directive only if certain condition becomes true.

For example:

```<code><button md-raised-button="true"></button>
</code>```

Another example:
I created a basic dynamic reactive form in plunker.
I am using formArrayName directive of reactive form for array of controls.
I want to apply formArrayName directive only if specific condition becomes true, otherwise don't add formArrayName directive.

Here is a plunker link.

答:
As already noted this does not appear to be possible. One thing that can be used to at least prevent some duplication is ng-template. This allows you to extract the content of the element affected by the ngIf branching.

If you for example want to create a hierarchical menu component using Angular Material:

<ng-template #contentTemplate>
    <mat-icon *ngIf="item.icon != null">{{ item.icon }}</mat-icon>
    {{ item.label }}
</ng-template>

<button *ngIf="item.children == null" mat-menu-item
    (click)="executeCommand()"
    [disabled]="enabled == false">
    <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</button>

<ng-container *ngIf="item.children != null">
    <button mat-menu-item
        [matMenuTriggerFor]="subMenu">
        <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
    </button>

    <mat-menu #subMenu="matMenu">
        <menu-item *ngFor="let child of item.children" [item]="child"></menu-item>
    </mat-menu>
</ng-container>
```

Here the conditionally applied directive is matMenuTriggerFor, which should only be applied to menu items with children. The contents of the button are inserted in both places via ngTemplateOutlet.

ContentLicense: CC BY-SA 4.0

Title: Apply a directive conditionally

Body:
I am using Material 2 to add md-raised-button. I want to apply this directive only if certain condition becomes true.

For example:

<button md-raised-button="true"></button>

Another example:
I created a basic dynamic reactive form in plunker.
I am using formArrayName directive of reactive form for array of controls.
I want to apply formArrayName directive only if specific condition becomes true, otherwise don't add formArrayName directive.

Here is a plunker link.

Body:
As already noted this does not appear to be possible. One thing that can be used to at least prevent some duplication is ng-template. This allows you to extract the content of the element affected by the ngIf branching.

If you for example want to create a hierarchical menu component using Angular Material:

<!-- Button contents -->
<ng-template #contentTemplate>
    <mat-icon *ngIf="item.icon != null">{{ item.icon }}</mat-icon>
    {{ item.label }}
</ng-template>

<!-- Leaf button -->
<button *ngIf="item.children == null" mat-menu-item
    (click)="executeCommand()"
    [disabled]="enabled == false">
    <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</button>
<!-- Node button -->
<ng-container *ngIf="item.children != null">
    <button mat-menu-item
        [matMenuTriggerFor]="subMenu">
        <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
    </button>

    <mat-menu #subMenu="matMenu">
        <menu-item *ngFor="let child of item.children" [item]="child"></menu-item>
    </mat-menu>
</ng-container>

Here the conditionally applied directive is matMenuTriggerFor, which should only be applied to menu items with children. The contents of the button are inserted in both places via ngTemplateOutlet.


问:
change the image is not transparent to be transparent with php
I want to ask, how do I get the first image to be the second picture?
in the sense that the first image of the backgroud is not transparent and will I change to transparant on the image become like the second picture?
how do you do it with php?
I really do not know

Image 1-

Image 2-

Please help!

答:
if you have only images B&W, it's possible in break the white in all pixel.

```<code><?php
  $url = "IUWBw.jpg";
  $image = imagecreatefromjpeg($url);//get your image
  //get size
  $width = imagesx($image);
  $height = imagesy($image);
  //create new image
  $out = ImageCreateTrueColor($width,$height);

  //configuration for make alpha color
  imagealphablending($out,false);
  imagesavealpha($out, true);

  for($x = $width-1;$x>=0;$x--){
    for($y = $height-1;$y>=0;$y--){
        $rgb = imagecolorat($image,$x,$y);//get pixel color of original image
        $r =   $rgb >> 16;
        $g =   ord(chr($rgb >> 8));
        $b =   ord(chr($rgb));
        if( $rgb != 0 ){ //if pixel is not black
            //if red is the low color
            if($r<$g && $r < $b){
                $alpha =  ($r / 2);
                $g-=$r;$b-=$r; $r=0;
            }
            //if green is the low color
            if($g<$r && $g < $b){
                $alpha =  ($g / 2);
                 $r-=$g;$b-=$g;$g=0;
            }
            //if blue is the low color
            if($b<$r && $b < $g){
                 $alpha =($b / 2);
                $r-=$b; $g-=$b;$b=0;
            }
            //if we all have equal value
            if($b == $r && $b == $g){
                 $alpha = ($b / 2);
                $r-=$b; $g-=$b;$b=0;
            }

            $color = $alpha << 24 | $r << 16 | $g << 8 | $b;

            imagesetpixel($out,$x,$y,$color);

        }else{//else is black just write
                imagesetpixel($out,$x,$y,$rgb);
        }
    }
  }

    $urlout = preg_replace("#(.+).jpe?g#i","$1.png",$url);

    imagepng($out,$urlout);
    echo "image writeted: ".$urlout;
    imagedestroy($out);
    imagedestroy($image);

?>
</code>```

this code looks for the low value of one pixel and subtracts it from the other value.

example: a pixel so the values are, r: 255 g: 226 b: 255.

he transforms it into r: 29 g: 0 b: 29;

now that the pixel has no value in white, it remains to put the appropriate alpha. the value of 'g' divides by 2 before its transformation. divide by 2 because the alpha supports a value of 127 instead of 255.
a = g / 2 = 226/2 = 113.

this code also works on color images, but the whole image will be translucent. Except the black.

Body:
if you have only images B&W, it's possible in break the white in all pixel.

<?php
  $url = "IUWBw.jpg";
  $image = imagecreatefromjpeg($url);//get your image
  //get size
  $width = imagesx($image);
  $height = imagesy($image);
  //create new image
  $out = ImageCreateTrueColor($width,$height);

  //configuration for make alpha color
  imagealphablending($out,false);
  imagesavealpha($out, true);

  for($x = $width-1;$x>=0;$x--){
    for($y = $height-1;$y>=0;$y--){
        $rgb = imagecolorat($image,$x,$y);//get pixel color of original image
        $r =   $rgb >> 16;
        $g =   ord(chr($rgb >> 8));
        $b =   ord(chr($rgb));
        if( $rgb != 0 ){ //if pixel is not black
            //if red is the low color
            if($r<$g && $r < $b){
                $alpha =  ($r / 2);
                $g-=$r;$b-=$r; $r=0;
            }
            //if green is the low color
            if($g<$r && $g < $b){
                $alpha =  ($g / 2);
                 $r-=$g;$b-=$g;$g=0;
            }
            //if blue is the low color
            if($b<$r && $b < $g){
                 $alpha =($b / 2);
                $r-=$b; $g-=$b;$b=0;
            }
            //if we all have equal value
            if($b == $r && $b == $g){
                 $alpha = ($b / 2);
                $r-=$b; $g-=$b;$b=0;
            }

            $color = $alpha << 24 | $r << 16 | $g << 8 | $b;

            imagesetpixel($out,$x,$y,$color);

        }else{//else is black just write
                imagesetpixel($out,$x,$y,$rgb);
        }
    }
  }

    $urlout = preg_replace("#(.+).jpe?g#i","$1.png",$url);

    imagepng($out,$urlout);
    echo "image writeted: ".$urlout;
    imagedestroy($out);
    imagedestroy($image);

?>

this code looks for the low value of one pixel and subtracts it from the other value.

example: a pixel so the values are, r: 255 g: 226 b: 255.

he transforms it into r: 29 g: 0 b: 29;

now that the pixel has no value in white, it remains to put the appropriate alpha. the value of 'g' divides by 2 before its transformation. divide by 2 because the alpha supports a value of 127 instead of 255.
a = g / 2 = 226/2 = 113.

this code also works on color images, but the whole image will be translucent. Except the black.


问:
Update a store property
I am getting a response from an API as below:

```<code>{
    "results": {
        "6": {
            "id": 6,
            "name": "akkha madrasi mirchi1",
        },
        "7": {
            "id": 7,
            "name": "almonds",
        },
        "8": {
            "id": 8,
            "name": "alu1",
        }
    }
}
</code>```

I am storing response.results in results reducer store {} so that I can access results as store.results. I want to modify an object inside the results. The API only returns the updated object. Now I want to update  id: 6 in store.results.

```<code>{
    "results": {
        "6": {
            "id": 6,
            "name": "Modified akkha madrasi mirchi1",
        }
    }
}
</code>```

If I do this in the results reducer:

```<code>[...state,action.response]
</code>```

will the object with key 6 replace the object with matching keys?

I am expecting state to be (note name changed to Modified akkha madrasi mirchi1 for id: 6):

```<code>"results": {
    "6": {
        "id": 6,
        "name": "Modified akkha madrasi mirchi1",
    },
    "7": {
        "id": 7,
        "name": "almonds",
    },
    "8": {
        "id": 8,
        "name": "alu1",
    }
}
</code>```

I want objects to be updated even if they are nested. Just match the key and keep on replacing.

答:
I could do it using the immutability-helper

this is my action creator:

```<code>export function itemupdate(response) {
    return {
        type: 'ITEMS_UPDATE_DATA_SUCCESS',
        idx: Object.keys(response.results)[0],
        obj: response.results[Object.keys(response.results)[0]]
    }
}
</code>```

This is how i replace that particular id object in the results.

```<code>export function data(state = {}, action) {
    case 'ITEMS_UPDATE_DATA_SUCCESS':
        return update(state,{results: {[action.idx]: {$set: action.obj} }})
    default:
        return state;
    }
</code>```

Title: Update a store property

Body:
I am getting a response from an API as below:

{
    "results": {
        "6": {
            "id": 6,
            "name": "akkha madrasi mirchi1",
        },
        "7": {
            "id": 7,
            "name": "almonds",
        },
        "8": {
            "id": 8,
            "name": "alu1",
        }
    }
}

I am storing response.results in results reducer store {} so that I can access results as store.results. I want to modify an object inside the results. The API only returns the updated object. Now I want to update  id: 6 in store.results.

{
    "results": {
        "6": {
            "id": 6,
            "name": "Modified akkha madrasi mirchi1",
        }
    }
}

If I do this in the results reducer:

[...state,action.response]

will the object with key 6 replace the object with matching keys?

I am expecting state to be (note name changed to Modified akkha madrasi mirchi1 for id: 6):

"results": {
    "6": {
        "id": 6,
        "name": "Modified akkha madrasi mirchi1",
    },
    "7": {
        "id": 7,
        "name": "almonds",
    },
    "8": {
        "id": 8,
        "name": "alu1",
    }
}

I want objects to be updated even if they are nested. Just match the key and keep on replacing.

Body:
I could do it using the immutability-helper

this is my action creator:

export function itemupdate(response) {
    return {
        type: 'ITEMS_UPDATE_DATA_SUCCESS',
        idx: Object.keys(response.results)[0],
        obj: response.results[Object.keys(response.results)[0]]
    }
}

This is how i replace that particular id object in the results.

export function data(state = {}, action) {
    case 'ITEMS_UPDATE_DATA_SUCCESS':
        return update(state,{results: {[action.idx]: {$set: action.obj} }})
    default:
        return state;
    }


问:
Getting BlazeInfoException in IntelliJ from the Bazel plugin
I just installed the Bazel plugin for IntelliJ, and I keep getting this exception:

```<code>com.google.idea.blaze.base.command.info.BlazeInfoException: blaze info failed with exit code: -1
java.util.concurrent.ExecutionException:
com.google.idea.blaze.base.command.info.BlazeInfoException: blaze info failed with exit code: -1
  at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:502)
  [...]
  at com.google.idea.blaze.base.async.FutureUtil$Builder.lambda$run$0(FutureUtil.java:93)
  [...]
  at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:170)
  at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:548)
  at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:493)
  at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:94)
  at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
  at com.google.idea.blaze.base.async.executor.BlazeExecutor$3.call(BlazeExecutor.java:108)
  at com.google.idea.blaze.base.async.executor.BlazeExecutor$3.call(BlazeExecutor.java:105)
  [...]
Caused by: com.google.idea.blaze.base.command.info.BlazeInfoException: blaze info failed with exit code: -1
  at com.google.idea.blaze.base.command.info.BlazeInfoRunnerImpl.runBlazeInfo(BlazeInfoRunnerImpl.java:105)
  at com.google.idea.blaze.base.command.info.BlazeInfoRunnerImpl.lambda$runBlazeInfo$2(BlazeInfoRunnerImpl.java:75)
  ... 6 more
</code>```

Edit: I am using IntelliJ 2017.3 on MacOS El Capitan 10.11.6, Java JRE 1.8.0, and the Bazel version is 0.8.1-homebrew (the plugin version is 2017.11.20.0.4). I get this error when I try to setup a new Java project (an Hello World with only one class and one BUILD file containing a java_binary similar to this tutorial), and it appears when I click on the Bazel sync button.

The output in the Bazel console is:

```<code>Syncing project: Sync (incremental)...
Updating VCS...
Running Bazel info...
Command:  info --tool_tag=ijwb:IDEA:community --curses=no --color=no --experimental_ui=no --progress_in_terminal_title=no --

==== TIMING REPORT ====

Sync: 47ms
BazelInfo: 4ms

Timing summary:

BlazeInvocation: 4ms
Sync failed
Command: git diff --name-status --no-renames abc8913346474d12ad45226503438848011929ae
</code>```

Does anybody have an idea about what is it and/or how to fix it? Thanks!

答:
I found my answer, thanks to this post.

In IntelliJ > Settings > Other Settings > Bazel Settings, the field "Bazel binary location" was empty. For my case, I entered /usr/local/bin/bazel and now it works!

Body:
I just installed the Bazel plugin for IntelliJ, and I keep getting this exception:

com.google.idea.blaze.base.command.info.BlazeInfoException: blaze info failed with exit code: -1
java.util.concurrent.ExecutionException:
com.google.idea.blaze.base.command.info.BlazeInfoException: blaze info failed with exit code: -1
  at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:502)
  [...]
  at com.google.idea.blaze.base.async.FutureUtil$Builder.lambda$run$0(FutureUtil.java:93)
  [...]
  at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:170)
  at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:548)
  at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:493)
  at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:94)
  at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
  at com.google.idea.blaze.base.async.executor.BlazeExecutor$3.call(BlazeExecutor.java:108)
  at com.google.idea.blaze.base.async.executor.BlazeExecutor$3.call(BlazeExecutor.java:105)
  [...]
Caused by: com.google.idea.blaze.base.command.info.BlazeInfoException: blaze info failed with exit code: -1
  at com.google.idea.blaze.base.command.info.BlazeInfoRunnerImpl.runBlazeInfo(BlazeInfoRunnerImpl.java:105)
  at com.google.idea.blaze.base.command.info.BlazeInfoRunnerImpl.lambda$runBlazeInfo$2(BlazeInfoRunnerImpl.java:75)
  ... 6 more

Edit: I am using IntelliJ 2017.3 on MacOS El Capitan 10.11.6, Java JRE 1.8.0, and the Bazel version is 0.8.1-homebrew (the plugin version is 2017.11.20.0.4). I get this error when I try to setup a new Java project (an Hello World with only one class and one BUILD file containing a java_binary similar to this tutorial), and it appears when I click on the Bazel sync button.

The output in the Bazel console is:

Syncing project: Sync (incremental)...
Updating VCS...
Running Bazel info...
Command:  info --tool_tag=ijwb:IDEA:community --curses=no --color=no --experimental_ui=no --progress_in_terminal_title=no --

==== TIMING REPORT ====

Sync: 47ms
BazelInfo: 4ms

Timing summary:

BlazeInvocation: 4ms
Sync failed
Command: git diff --name-status --no-renames abc8913346474d12ad45226503438848011929ae

Does anybody have an idea about what is it and/or how to fix it? Thanks!


问:
Getting the index of the leftmost active bit in an integer instantly
How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

```<code>int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}
</code>```

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit
(Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!

答:
Use this:

```<code>int left_most_bit = myInt & (1 << (sizeof myInt * CHAR_BIT - 1));
</code>```

How does it work?

sizeof myInt returns the size of the variable myInt in bytes

CHAR_BIT is a (possibly) platform-dependent macro that tells you how many bits are there in a byte, which is typically 8

Shift 1 left by that gets the leftmost bit.

Works great in O(1) time because both sizeof myInt and CHAR_BIT are compile-time constants, so the whole expression (1 << (sizeof myInt * CHAR_BIT - 1)) is a compile-time constant, too. The compiler can then apply maximum optimization to it.

Body:
How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit
(Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!

Body:
Use this:

int left_most_bit = myInt & (1 << (sizeof myInt * CHAR_BIT - 1));

How does it work?

sizeof myInt returns the size of the variable myInt in bytes

CHAR_BIT is a (possibly) platform-dependent macro that tells you how many bits are there in a byte, which is typically 8

Shift 1 left by that gets the leftmost bit.

Works great in O(1) time because both sizeof myInt and CHAR_BIT are compile-time constants, so the whole expression (1 << (sizeof myInt * CHAR_BIT - 1)) is a compile-time constant, too. The compiler can then apply maximum optimization to it.


问:
Confused on git workflow (PHP/MySQL)
I have a question regarding the proper workflow of git in a PHP/MySQL workflow.  The git repository has a config file with "blank" database data, just like any PHP/MySQL application.  MY question is related to development (pulling/cloning) -> development stage -> production (push).

So, I want to be able to clone my repository (blank MySQL config file), do some development (this is where I'd edit the "blank" config file) on my dev instance which includes testing,  and then push back to the repository (with a blank MySQL file, instead of with password information).

This might be super easy, I just do not have the knowledge of how git could do such a thing.

答:
Create another file with the same name as your current config file and add something like .sample or .dist to the end of it. i.e on my system i personally have my settings in config.php which is ignored by git and will never upload to the site, and i also have a config.php.dist (like distribution) which will push up to the repo.

So when your client downloads it, they just need to rename config.php.dist and remove the .dist part.

Second thing to do, you need to create a .gitignore in the root of the repo folder, and add the file name that you do not want to upload to the repo.

Contents of .gitignore
config.php.dist

Title: Confused on git workflow (PHP/MySQL)


问:
Semantic UI Dropdown is not showing the drop down but everything else is working
I am using Semantic UI Dropdown in my ASP.NET Web Forms application. Its working fine in this fiddle. But in my application it is not showing the drop down when clicked on the selector div. Also, I can select the elements by searching but in that case too the drop down is not showing. When I inspected using Firefox, I found that display: none property is not changing for .menu class. When I researched on SO, I found these related questions: Semantic-ui dropdown is not working and semantic UI dropdown not working. I tried the solutions but none of them seem to work. I checked other css in my project none of them shows any conflict. Then, what is wrong with it? You can find my dropdown code in the fiddle.

答: In my case, I had minchars set greater than 1.  Clicking on the dropdown does not render the menu in that case.


问:
JavaScript make a class's method static and available to its instances
How can you make a class's method static (available on the class itself) and accessible from its instances in JavaScript?

```<code>class MyClass {
    constructor() {}
    method() {}
}

const myInstance = new MyClass();

myInstance.method(); // calling from instance
MyClass.method(); // calling from class
</code>```

答:
Static method calls are made directly on the class and are not callable on instances of the class. But you can achieve the calls for static members from inside an instance.

Using syntax:

```<code>this.constructor.staticfunctionName();
</code>```

ES6 Class Example:

```<code>class MyClass {
    constructor() {}
    static staticMethod() {
        console.log('Static Method');
    }
}
MyClass.staticVar = 777;

var myInstance = new MyClass();
// calling from instance
myInstance.constructor.staticMethod();
console.log('From Inside Class : ',myInstance.constructor.staticVar);

// calling from class
MyClass.staticMethod();
console.log('Class : ', MyClass.staticVar);
</code>```

For ES5 Function Classes refer to my answer.

Body:
How can you make a class's method static (available on the class itself) and accessible from its instances in JavaScript?

class MyClass {
    constructor() {}
    method() {}
}

const myInstance = new MyClass();

myInstance.method(); // calling from instance
MyClass.method(); // calling from class

Body:
Static method calls are made directly on the class and are not callable on instances of the class. But you can achieve the calls for static members from inside an instance.

Using syntax:

this.constructor.staticfunctionName();

ES6 Class Example:

class MyClass {
    constructor() {}
    static staticMethod() {
        console.log('Static Method');
    }
}
MyClass.staticVar = 777;

var myInstance = new MyClass();
// calling from instance
myInstance.constructor.staticMethod();
console.log('From Inside Class : ',myInstance.constructor.staticVar);

// calling from class
MyClass.staticMethod();
console.log('Class : ', MyClass.staticVar);

For ES5 Function Classes refer to my answer.


问:
use RegEx to ignore lines that contain a specific phrase but do not end with an extension and period
Struggling to write a RegEx to use with my ANT FilterChain.

I am cleaning up a log file that contains entries such as (BAD ENTRY):

```<code>017Z WARN Broken: D:/folder/subfolder/subsubfolder/../Images/Filename (stuff about file).
</code>```

The log also contains entries like this (GOOD ENTRIES):

```<code>017Z WARN Broken: D:/folder/subfolder/subsubfolder/../Images/Filename (stuff about file).ai.
</code>```

I am able to successfully delete the "bad" entry and keep the "good" ones if I do something like this:

```<code>"^(?=.*WARN Broken:)(?!.*[.]ai.).*"
</code>```

That, however, would force me to write a regex for all possible extensions.  I actually don't know how to properly do the OR regex, in this case, to even do that. I would like to be able to do jpg, gif, eps, pdf in addition to ai.

Ideally, I would like to be able to keep everything that ends with ".extension."
That last period really makes things complicated for me.

答:
Here is how you would add the desired OR clause to your regex:</p>

```<code>^(?=.*WARN Broken:)(?!.*[.](ai|jpg|gif|eps|pdf).).*
</code>```

Body:
Struggling to write a RegEx to use with my ANT FilterChain.

I am cleaning up a log file that contains entries such as (BAD ENTRY):

017Z WARN Broken: D:/folder/subfolder/subsubfolder/../Images/Filename (stuff about file).

The log also contains entries like this (GOOD ENTRIES):

017Z WARN Broken: D:/folder/subfolder/subsubfolder/../Images/Filename (stuff about file).ai.

I am able to successfully delete the "bad" entry and keep the "good" ones if I do something like this:

"^(?=.*WARN Broken:)(?!.*[.]ai.).*"

That, however, would force me to write a regex for all possible extensions.  I actually don't know how to properly do the OR regex, in this case, to even do that. I would like to be able to do jpg, gif, eps, pdf in addition to ai.

Ideally, I would like to be able to keep everything that ends with ".extension."
That last period really makes things complicated for me.

Body:
Here is how you would add the desired OR clause to your regex:

^(?=.*WARN Broken:)(?!.*[.](ai|jpg|gif|eps|pdf).).*


问:
Building a function to read CSV
I am new to Python and building a function to read CSV. I am trying to use the pandas.read_csv() inside my function,and while the code gets compiled-i dont see the dataset (I know its an overkill, but am trying to learn it using a trial and error method).

```<code>>>> def CSV(filename):
        dataset=pd.read_csv(filename)
</code>```

I expect that when i run CSV('abc.csv'), it should create a df in my variable explorer. Unfortunately, the function gets compiled, but nothing is there

```<code>def CSV(filename):
    dataset=pd.read_csv(filename)

CSV('banking.csv')
</code>```

答:
The following example, taken from Read the Docs: Variables and Scope, illustrates the issue that you're experiencing -- dataset was created in your CSV function, but no longer exists outside of the scope of that function:

```<code># This is a global variable
a = 0

if a == 0:
    # This is still a global variable
    b = 1

def my_function(c):
    # this is a local variable
    d = 3
    print(c)
    print(d)

# Now we call the function, passing the value 7 as the first and only parameter
my_function(7)

# a and b still exist
print(a)
print(b)

# c and d don't exist anymore -- these statements will give us name errors!
print(c)
print(d)
</code>```

In this example, variable d is similar to your dataset variable -- it's trashed as soon as execution of the function is complete.

Instead:

```<code>def CSV(filename):
    return pd.open_csv(filename)

df = CSV('banking.csv')
</code>```

will create a DataFrame variable df that you can view in variable explorer.

Title: Building a function to read CSV

Body:
I am new to Python and building a function to read CSV. I am trying to use the pandas.read_csv() inside my function,and while the code gets compiled-i dont see the dataset (I know its an overkill, but am trying to learn it using a trial and error method).

>>> def CSV(filename):
        dataset=pd.read_csv(filename)

I expect that when i run CSV('abc.csv'), it should create a df in my variable explorer. Unfortunately, the function gets compiled, but nothing is there

def CSV(filename):
    dataset=pd.read_csv(filename)

CSV('banking.csv')

Body:
The following example, taken from Read the Docs: Variables and Scope, illustrates the issue that you're experiencing -- dataset was created in your CSV function, but no longer exists outside of the scope of that function:

# This is a global variable
a = 0

if a == 0:
    # This is still a global variable
    b = 1

def my_function(c):
    # this is a local variable
    d = 3
    print(c)
    print(d)

# Now we call the function, passing the value 7 as the first and only parameter
my_function(7)

# a and b still exist
print(a)
print(b)

# c and d don't exist anymore -- these statements will give us name errors!
print(c)
print(d)

In this example, variable d is similar to your dataset variable -- it's trashed as soon as execution of the function is complete.

Instead:

def CSV(filename):
    return pd.open_csv(filename)

df = CSV('banking.csv')

will create a DataFrame variable df that you can view in variable explorer.


答:
Make your function accept a callback Like this

```<code>function retrieveData(callback) {
    https.get(url, function(res){
        body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            var dataResponse = JSON.parse(body);
            callback(dataResponse,null);
        });
    }).on('error', function(e) {
          console.log("Error: ", e);
            callback(null,e)
        });
}
</code>```

Then call it like this,

```<code>retrieveData(function (dataResponse, err) {
 if (err) console.log(err);
 else {
   var temp = (dataResponse[0]);
   console.log(temp);
 }
});
</code>```

Title: Nodejs - parsing json retrieved from web

Body:
Make your function accept a callback Like this

function retrieveData(callback) {
    https.get(url, function(res){
        body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            var dataResponse = JSON.parse(body);
            callback(dataResponse,null);
        });
    }).on('error', function(e) {
          console.log("Error: ", e);
            callback(null,e)
        });
}

Then call it like this,

retrieveData(function (dataResponse, err) {
 if (err) console.log(err);
 else {
   var temp = (dataResponse[0]);
   console.log(temp);
 }
});


问:
Query has_many associations - Ecto, Phoenix
I'm trying to query all of the leagues that belong to a particular user in my system.

The data setup looks like this:

USER MODEL:

```<code>has_many :users_leagues, Statcasters.UsersLeagues
has_many :leagues, through: [:users_leagues, :league]
</code>```

So you can see, I have a has_many through association for users and leagues.

I'm trying to get a list of all the leagues a user has attached to it.

In rails it would look something like this: user.leagues and it would load up all of the leagues that have the current user id attached to it.

How can I do this with Ecto, Elixir and Phoenix?

答:
You can either preload leagues into user using Repo.preload:

```<code>user = user |> Repo.preload([:leagues])
# user.leagues is now a list of leagues
</code>```

or use assoc and Repo.all to get a list of leagues for the user:

```<code>leagues = Ecto.assoc(user, :leagues) |> Repo.all
</code>```

Body:
I'm trying to query all of the leagues that belong to a particular user in my system.

The data setup looks like this:

USER MODEL:

has_many :users_leagues, Statcasters.UsersLeagues
has_many :leagues, through: [:users_leagues, :league]

So you can see, I have a has_many through association for users and leagues.

I'm trying to get a list of all the leagues a user has attached to it.

In rails it would look something like this: user.leagues and it would load up all of the leagues that have the current user id attached to it.

How can I do this with Ecto, Elixir and Phoenix?

Body:
You can either preload leagues into user using Repo.preload:

user = user |> Repo.preload([:leagues])
# user.leagues is now a list of leagues

or use assoc and Repo.all to get a list of leagues for the user:

leagues = Ecto.assoc(user, :leagues) |> Repo.all


问:
T-SQL, how to get IDs that visit X amount of location within X amount of time?
T-SQL question, I been trying to find the best/optimal solution for this one.

Say we have this theoritical table

```<code>-----------------------------------
ID | DATETIME | Location
11 | 1/27 3:30pm | a
11 | 1/27 3:31pm | b
11 | 1/27 3:32pm | c
22 | 2/14 1:10pm | g
22 | 2/14 1:12pm | i
22 | 2/15 5:48pm | w
55 | 3/18 8:48pm | d
55 | 3/18 9:48pm | e
---------------------------
</code>```

I want to create a query that return IDs that have been in 2 or more different locations within 5 minutes. In this case if you look at the table, ID: 11 and 22 visits 2 or more different location within 5 minutes, thus it should return ID 11 and 22. How do I develop a query that returns the IDs that been to X amount of location within X amount of time in minutes?

答:
I suggest using cross apply</p>

```<code>select t.*, ca.num_visit
from table1 as t
cross apply (
  select count(*) num_visit
  from table1 as c
  where c.id = t.id
  and c.DATETIME > t.DATETIME
  and c.DATETIME <= dateadd(minute,5,t.DATETIME)
  ) ca
where num_visit >= 2
</code>```

Body:
T-SQL question, I been trying to find the best/optimal solution for this one.

Say we have this theoritical table

-----------------------------------
ID | DATETIME | Location
11 | 1/27 3:30pm | a
11 | 1/27 3:31pm | b
11 | 1/27 3:32pm | c
22 | 2/14 1:10pm | g
22 | 2/14 1:12pm | i
22 | 2/15 5:48pm | w
55 | 3/18 8:48pm | d
55 | 3/18 9:48pm | e
---------------------------

I want to create a query that return IDs that have been in 2 or more different locations within 5 minutes. In this case if you look at the table, ID: 11 and 22 visits 2 or more different location within 5 minutes, thus it should return ID 11 and 22. How do I develop a query that returns the IDs that been to X amount of location within X amount of time in minutes?

Body:
I suggest using cross apply

select t.*, ca.num_visit
from table1 as t
cross apply (
  select count(*) num_visit
  from table1 as c
  where c.id = t.id
  and c.DATETIME > t.DATETIME
  and c.DATETIME <= dateadd(minute,5,t.DATETIME)
  ) ca
where num_visit >= 2


问:
How do I exit a While(true) loop with a key?
So I have this while loop that looks something like this.

```<code>bool isTrue = true;
while(isTrue)
{
  //Do work over and over
}
</code>```

I'm wondering.. Can I add if statement that checks if a key has been pressed during the current loop to break out of it? WITHOUT INTERRUPTING THE LOOP so some sort of async task maybe? Because it's automating the task over and over again. For the sake of the question let's say it's printing out "Hello World!" to the console every third second.

答:
You'd probably want to set up a class so that you can have a shared property available in different methods.

```<code>public class MyLooper
{
    private bool KeepLooping { get; set; } = true;

    public void OnKeyPressed()
    {
        KeepLooping = false;
    }

    public void StartLoop()
    {
        Task.Factory.StartNew(() => {
            while (KeepLooping)
            {
                Debug.WriteLine("Hello World");
            }
        });
    }
}
</code>```

You haven't indicated where you'd be running this e.g. server, desktop app, console etc but you may encounter and need to tackle thread safety issues.

Body:
So I have this while loop that looks something like this.

bool isTrue = true;
while(isTrue)
{
  //Do work over and over
}

I'm wondering.. Can I add if statement that checks if a key has been pressed during the current loop to break out of it? WITHOUT INTERRUPTING THE LOOP so some sort of async task maybe? Because it's automating the task over and over again. For the sake of the question let's say it's printing out "Hello World!" to the console every third second.

Body:
You'd probably want to set up a class so that you can have a shared property available in different methods.

public class MyLooper
{
    private bool KeepLooping { get; set; } = true;

    public void OnKeyPressed()
    {
        KeepLooping = false;
    }

    public void StartLoop()
    {
        Task.Factory.StartNew(() => {
            while (KeepLooping)
            {
                Debug.WriteLine("Hello World");
            }
        });
    }
}

You haven't indicated where you'd be running this e.g. server, desktop app, console etc but you may encounter and need to tackle thread safety issues.


答:
You need to remember that the callbacks for .on and .end will get executed after the request to the url is fulfilled.

To access that after you can wrap your function in a promise and use .then like below.

PROMISES Check out this link for a better understanding of asynchronous processing.

```<code>function retrieveData() {
  return new Promise((resolve, reject) => {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
          body += chunk;
        });

        res.on('end', function() {
          resolve(JSON.parse(body));
        });

    }).on('error', function(e) {
        reject(e);
    });
  })
}

retrieveData().then(response => {
  console.log(response[0]);
}).catch(error => {
  console.log(error)
})
</code>```

Body:
I'm trying to parse a json retrieved from the web (https://api.coinmarketcap.com/v1/ticker/?limit=3) and be able to select the name and price_usd. For reference:

[
{
    "id": "bitcoin",
    "name": "Bitcoin",
    "symbol": "BTC",
    "rank": "1",
    "price_usd": "16148.3",
    "price_btc": "1.0",
    "24h_volume_usd": "18799600000.0",
    "market_cap_usd": "270147332945",
    "available_supply": "16729150.0",
    "total_supply": "16729150.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "-0.28",
    "percent_change_24h": "-4.64",
    "percent_change_7d": "45.79",
    "last_updated": "1512792553"
},
{
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_usd": "471.833",
    "price_btc": "0.0296001",
    "24h_volume_usd": "2170950000.0",
    "market_cap_usd": "45401368016.0",
    "available_supply": "96223384.0",
    "total_supply": "96223384.0",
    "max_supply": null,
    "percent_change_1h": "0.01",
    "percent_change_24h": "9.29",
    "percent_change_7d": "0.65",
    "last_updated": "1512792556"
},
{
    "id": "bitcoin-cash",
    "name": "Bitcoin Cash",
    "symbol": "BCH",
    "rank": "3",
    "price_usd": "1510.48",
    "price_btc": "0.094759",
    "24h_volume_usd": "2229320000.0",
    "market_cap_usd": "25444318815.0",
    "available_supply": "16845188.0",
    "total_supply": "16845188.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "0.6",
    "percent_change_24h": "1.29",
    "percent_change_7d": "2.64",
    "last_updated": "1512792581"
    }
]

Here's the code I currently have:

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';
var dataResponse = '';
var body = '';

function retrieveData() {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            dataResponse = JSON.parse(body);
        });

    }).on('error', function(e) {
          console.log("Error: ", e);
    });

}

retrieveData();

var temp = (dataResponse[0]);

console.log(temp);

I want to be able to get something like and be able to select the name and price:

        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "16148.3",
        "price_btc": "1.0",
        "24h_volume_usd": "18799600000.0",
        "market_cap_usd": "270147332945",
        "available_supply": "16729150.0",
        "total_supply": "16729150.0",
        "max_supply": "21000000.0",
        "percent_change_1h": "-0.28",
        "percent_change_24h": "-4.64",
        "percent_change_7d": "45.79",
        "last_updated": "1512792553"

The error I get is that it logs an undefined. I'm not sure what I'm doing wrong. How would I go selecting the name also? Would I split each block into an array and select them by indexing?

Body:
You need to remember that the callbacks for .on and .end will get executed after the request to the url is fulfilled.

To access that after you can wrap your function in a promise and use .then like below.

PROMISES Check out this link for a better understanding of asynchronous processing.

function retrieveData() {
  return new Promise((resolve, reject) => {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
          body += chunk;
        });

        res.on('end', function() {
          resolve(JSON.parse(body));
        });

    }).on('error', function(e) {
        reject(e);
    });
  })
}

retrieveData().then(response => {
  console.log(response[0]);
}).catch(error => {
  console.log(error)
})


问:
Python: Spyder figure window - can't copy or save
I am running Spyder v3.2.4 in Windows 10.

I have gone to Tools > Preferences > IPython console > Graphics > Graphics Backend > Automatic to get my graphs/figures in separate windows. My question is, can I change the window type used to display these graphics? For example, in the window style I have I cannot copy or print the graphic directly. Instead having to save first. Is there a way around this?

The window style I have is:

答: (Spyder maintainer here) Plot windows are not generated nor handled by Spyder but by Matplotlib. Unfortunately (as you correctly point out) you can only save plots in them.


问:
BarcodeScanner.GetDefaultAsync() is always returning null
I'm trying to create a simple application in UWP for a Zebra device (Model TC700J) running Windows 8, in which I make use of the built in barcode scanner.

From what I've found, there's plenty of Zebra tutorials for accessing the scanner when programming on Android, but none for Windows due to the fact that Microsoft provide their own generic barcode scanner API found in the Windows.Devices.PointOfService namespace.

The code I currently have looks something like this:

```<code>BarcodeScanner scanner;
ClaimedBarcodeScanner claimedScanner;

scanner = await BarcodeScanner.GetDefaultAsync();

if (scanner != null)
{
    claimedScanner = await scanner.ClaimScannerAsync();
}
</code>```

The problem is that the if statement never evaluates to true as the GetDefaultAsync method always returns null.

Over here there was an answer that seemed to work, stating that it depends where the GetDefaultAsync method is placed. I've tried to put it in all of the suggested places though and to no avail.

There is another method, BarcodeScanner.FromIdAsync() which returns a barcode based on the string representation of that barcode scanner's id sent as a parameter, but I'm not sure that'd be valid here as the barcode scanner is built into the device.

答:
Looking at Zebra's site, TC700J seems to be model number of Windows 10 Mobile IoT Enterprize OS.
And the platform is ARM(Qualcomm snapdragon), not Intel x86/x64.

TC70 / TC75 Touch Computer Series

https://www.zebra.com/us/en/products/mobile-computers/handheld/tc7x-touch-computer-series.html

TC70x Operating System (TC700J) Windows 10 Mobile IoT Enterprise v1.13.02 Release Notes

https://www.zebra.com/us/en/support-downloads/software/release-notes/operating-system/tc70x-operating-system-v1-13-02--release-notes.html

For example, if your Zebra device is old hardware and Windows Phone 8/8.1 is running, Windows Phone does not seem to support Windows.Devices.PointOfService namespace.

It is described in the comment of the following article.
Windows Phone 8.1: Scan Barcodes using Camera

If your Zebra device can update to Windows 10 Mobile IoT Enterprise, please check it after doing it.

If you can update it, you can use the barcode scanner sample for Windows 10.

https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BarcodeScanner

If your device is running on Windows 8 for x86, since Windows.Devices.PointOfService namespace is supported from Windows 8.1, you need to change the OS to Windows 8.1/10 if possible.

In that case you can use following, or above(for Windows10) sample.

Barcode scanner sample for Windows 8.1

https://code.msdn.microsoft.com/windowsapps/Barcode-scanner-sample-f39aa411

If you can not update it, please get the software and documentation for using BarcodeScanner from the vendor on Windows (Phone?) 8.

Body:
I'm trying to create a simple application in UWP for a Zebra device (Model TC700J) running Windows 8, in which I make use of the built in barcode scanner.

From what I've found, there's plenty of Zebra tutorials for accessing the scanner when programming on Android, but none for Windows due to the fact that Microsoft provide their own generic barcode scanner API found in the Windows.Devices.PointOfService namespace.

The code I currently have looks something like this:

BarcodeScanner scanner;
ClaimedBarcodeScanner claimedScanner;

scanner = await BarcodeScanner.GetDefaultAsync();

if (scanner != null)
{
    claimedScanner = await scanner.ClaimScannerAsync();
}

The problem is that the if statement never evaluates to true as the GetDefaultAsync method always returns null.

Over here there was an answer that seemed to work, stating that it depends where the GetDefaultAsync method is placed. I've tried to put it in all of the suggested places though and to no avail.

There is another method, BarcodeScanner.FromIdAsync() which returns a barcode based on the string representation of that barcode scanner's id sent as a parameter, but I'm not sure that'd be valid here as the barcode scanner is built into the device.


问:
Is there any good add-ins in Visual C#2008?
My visual assist x didn't work after I installed visual c# 2008.
Is there any good add-ins like VAX? </p>

答: VAX works perfectly in VS 2008. maybe you need to reinstall or get a newer version.</p>

OwnerDisplayName: Jinx

LastEditorDisplayName: Jinx

OwnerDisplayName: Shy


问:
What mutation-testing frameworks exist for C/C++?
Mutation testing has been out there for a while now, and it seems there are at least one or two commercial mutation testing frameworks for C/C++. Have you used them? What are your experiences? Are there any open source alternatives?</p>

答:
Notice that Parasoft's tool only generate equivalent mutations. That echoes the problem described on Wikipedia article about Mutation Testing - it is hard to distinguish between equivalent and non-equivalent mutations so they decided to stick with equivalent.

I tried another interesting tool that can automatically discover invariants in instrumented C and C++ code - it is called "Daikon". Essentially it is doing same thing as tool that generates equivalent mutations, but instead of identifying problematic code it gives you a set of invariants such as "A == B + 1". I think invariants are more useful because when you look at discovered invariant it gives you assurance that your code is correct if invariant make sense, and then you can convert invariants into asserts and that gives you more confidence when you change code.


问:
Where is onScroll event in material ui
I cannot find any documentation in Material UI that shows a fired function for onScroll. All my components are either functional and stateless or container components which have the mapStateToProps and mapDispatchToProps API.

How has anyone written Material UI List and ListItem components to also include scroll events for a function in mapDispatchToProps to run? There are click events, but no scroll events like onScroll.

答:
You need to implement onScroll handlers on your own and the approach varies, depending on the default behavior of the component.

A component like Drawer can accept onScroll as a prop because its root element will scroll if the content is taller than the viewport and according to the docs:

Any other properties supplied will be spread to the root element.

Other components, like List and ListItem, which you've mentioned, do not scroll by default and would need to be wrapped in an element with an onScroll handler.

Title: Where is onScroll event in material ui


问:
JS add a variable with ++ doesn't work inside a callback function
I'm trying to build my stopwatch for an assignment.

At first, I built my lap function in this way

  handleClickLap: function(){
    $('#lap').click(function(event){
    if (Stopwatch.isRunning) {
      let lapCounter = 0;
      lapCounter = lapCounter + 1;
      console.log(lapCounter);
    })
```

<p>and it was working perfectly.</p>

<p>I read carefully the assignment then I had to rewrite my code like this</p>

<pre class="lang-js prettyprint-override"><code>lap: function(){
    if (Stopwatch.isRunning) {
    let lapCounter = 0;
    lapCounter ++;
     console.log(lapCounter);
    }
  }

  handleClickLap: function(){
$('#lap').click(function(event){
  Stopwatch.lap();

})
</code>```

I call all my function here

window.onload = function(){
  AppController.handleClickStart();
  AppController.handleClickStopReset();
  AppController.handleClickLap();
};
```

The problem is, lap: function() dosen't run lapCounter ++; in never updates the counter i also tried ++ lapcounter.

What am I doing wrong?

答:
oh, no, read the comment. that is almost certainly it heh. credit to @alfasin (as in give him the green check if he leaves an answer). but hold the lap count outside of the function.. e.g.</p>

```<code>  {~/Desktop}$  cat test.js
var obj = {
  lapCount: 0,
  addLap: function() {
    this.lapCount++;
    console.log(this.lapCount);
  }
}
obj.addLap()
obj.addLap()
  {~/Desktop}$  node test.js
1
2
</code>```

Body:
I'm trying to build my stopwatch for an assignment.

At first, I built my lap function in this way

  handleClickLap: function(){
    $('#lap').click(function(event){
    if (Stopwatch.isRunning) {
      let lapCounter = 0;
      lapCounter = lapCounter + 1;
      console.log(lapCounter);
    })

and it was working perfectly.

I read carefully the assignment then I had to rewrite my code like this

lap: function(){
    if (Stopwatch.isRunning) {
    let lapCounter = 0;
    lapCounter ++;
     console.log(lapCounter);
    }
  }

  handleClickLap: function(){
$('#lap').click(function(event){
  Stopwatch.lap();

})

I call all my function here

window.onload = function(){
  AppController.handleClickStart();
  AppController.handleClickStopReset();
  AppController.handleClickLap();
};

The problem is, lap: function() dosen't run lapCounter ++; in never updates the counter i also tried ++ lapcounter.

What am I doing wrong?

Body:
oh, no, read the comment. that is almost certainly it heh. credit to @alfasin (as in give him the green check if he leaves an answer). but hold the lap count outside of the function.. e.g.

  {~/Desktop}$  cat test.js
var obj = {
  lapCount: 0,
  addLap: function() {
    this.lapCount++;
    console.log(this.lapCount);
  }
}
obj.addLap()
obj.addLap()
  {~/Desktop}$  node test.js
1
2


问:
Getting error message "Incorrect syntax near '(' " when running this query

Trying to create a pivot table to display the  policy name and number of customers taken each policies in the year 2000, 2001, 2004, 2005, 2006, 2008, 2010, 2012, 2015

```<code>Select NAME, [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015]
  from (
          select policy.name, year(customer_policy.policy_start_date)
            from policy
            join customer_policy
              on policy.id = customer_policy.policy_id
        group by policy.name, customer_policy.policy_start_date
       ) as SourceTable
  PIVOT
      (
      count(policy.name) for year(customer_policy.policy_start_date)
        in ([2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015])
       ) As PivotTable;
</code>```

I am getting:

```<code>Incorrect syntax near '('
</code>```

答:
I think you just need column aliases and some summarization:</p>

```<code>Select NAME , [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015]
from (select p.name, year(cp.policy_start_date) as yr
      from policy p join
           customer_policy cp
           on p.id = cp.policy_id
      group by p.name, cp.policy_start_date
     ) as SourceTable
PIVOT (count(*)) for yr in ( [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015] ) ) As PivotTable
</code>```

Body:
Trying to create a pivot table to display the  policy name and number of customers taken each policies in the year 2000, 2001, 2004, 2005, 2006, 2008, 2010, 2012, 2015

Select NAME, [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015]
  from (
          select policy.name, year(customer_policy.policy_start_date)
            from policy
            join customer_policy
              on policy.id = customer_policy.policy_id
        group by policy.name, customer_policy.policy_start_date
       ) as SourceTable
  PIVOT
      (
      count(policy.name) for year(customer_policy.policy_start_date)
        in ([2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015])
       ) As PivotTable;

I am getting:

Incorrect syntax near '('

Body:
I think you just need column aliases and some summarization:

Select NAME , [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015]
from (select p.name, year(cp.policy_start_date) as yr
      from policy p join
           customer_policy cp
           on p.id = cp.policy_id
      group by p.name, cp.policy_start_date
     ) as SourceTable
PIVOT (count(*)) for yr in ( [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015] ) ) As PivotTable


问:
How to process POST data from Golang into PHP using Wordpress
I am trying to call a PHP post api in Golang using HTTP package with some post values. After sending these parameters from Golang I am trying to get it into PHP $_POST array in Wordpress. But I am not able to access any index of $_POST array in PHP code.

Here is my code:

```<code>func SaveProviderInGlobalDb(providerId int, providerEmail string, businessName string) (*http.Response, error){
    postValues := url.Values{}
    providerIdString := strconv.Itoa(providerId)
    postValues.Add("provider_id", providerIdString)
    postValues.Add("provider_email", providerEmail)
    postValues.Add("business_name", businessName)
    response, err := http.PostForm("http://localhost/provider.php", postValues)
    return response, err
}
</code>```

PHP code:

```<code>if(isset($_POST) && count($_POST) > 0){
    if(isset($_POST["business_name"]) && $_POST["business_name"] != ''){
        $providersCount = GetProviderCount($_POST["business_name"], $_POST["provider_email"]);
        if($providersCount > 0) {
            $response["response"] = "This provider is already registered for ".$_POST["business_name"];
            $response["code"] = 400;
        }else{
            $result = SaveProvider($_POST);
            if($result){
                $response["response"] = "Provider saved successfully.";
                $response["code"] = 200;
            }else{
                $response["response"] = "Error while saving provider.";
                $response["code"] = 400;
            }
        }
    }else {
        $response["response"] = "No merchant found.";
        $response["code"] = 400;
    }
    echo json_encode($response);
}
</code>```

In the above PHP code I am not able to check if "business_name" is set in $_POST or not. Due to this, It always gives me error message that "No merchant found."

EDITED

```<code>Array
(
    [------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition:_form-data;_name] => \"provider_email\"

john_doe_1234@example.com
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"provider_id\"

54
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"business_name\"

testkom1
------WebKitFormBoundaryGPuoAolbEsWBZnVh--

)
</code>```

It is the response which I am getting after printing $_POST.

Can anyone tell me how do I solve this problem ?

Thanks!

答:
Change your condition statement:

```<code>if(isset($_POST["business_name"]) && $_POST["business_name"] != '')
</code>```

to:

```<code>if(!empty($_POST["business_name"]))
</code>```

I hope it could do the job.

Body:
I am trying to call a PHP post api in Golang using HTTP package with some post values. After sending these parameters from Golang I am trying to get it into PHP $_POST array in Wordpress. But I am not able to access any index of $_POST array in PHP code.

Here is my code:

func SaveProviderInGlobalDb(providerId int, providerEmail string, businessName string) (*http.Response, error){
    postValues := url.Values{}
    providerIdString := strconv.Itoa(providerId)
    postValues.Add("provider_id", providerIdString)
    postValues.Add("provider_email", providerEmail)
    postValues.Add("business_name", businessName)
    response, err := http.PostForm("http://localhost/provider.php", postValues)
    return response, err
}

PHP code:

if(isset($_POST) && count($_POST) > 0){
    if(isset($_POST["business_name"]) && $_POST["business_name"] != ''){
        $providersCount = GetProviderCount($_POST["business_name"], $_POST["provider_email"]);
        if($providersCount > 0) {
            $response["response"] = "This provider is already registered for ".$_POST["business_name"];
            $response["code"] = 400;
        }else{
            $result = SaveProvider($_POST);
            if($result){
                $response["response"] = "Provider saved successfully.";
                $response["code"] = 200;
            }else{
                $response["response"] = "Error while saving provider.";
                $response["code"] = 400;
            }
        }
    }else {
        $response["response"] = "No merchant found.";
        $response["code"] = 400;
    }
    echo json_encode($response);
}

In the above PHP code I am not able to check if "business_name" is set in $_POST or not. Due to this, It always gives me error message that "No merchant found."

EDITED

Array
(
    [------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition:_form-data;_name] => \"provider_email\"

john_doe_1234@example.com
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"provider_id\"

54
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"business_name\"

testkom1
------WebKitFormBoundaryGPuoAolbEsWBZnVh--

)

It is the response which I am getting after printing $_POST.

Can anyone tell me how do I solve this problem ?

Thanks!

Body:
Change your condition statement:

if(isset($_POST["business_name"]) && $_POST["business_name"] != '')

to:

if(!empty($_POST["business_name"]))

I hope it could do the job.


问:
Spell email address for forums
How can I make the code of the mail to spell it  and undetectable for forum when I try to put it in html

Thank's anticipated

Like this ! but more sophisticated

```<code><h>mariaburkke76</h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>@<h><h><h><h><h>g<h><h><h><h><h><h><h><h><h><h><h>m<h><h><h>a<h><h>i<h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>l<h><h><h><h>.<h>com<h><h><h><h><h><h><h><h><h>
</code>```

答: You could use ROT13 simple cipher. It is used to screen out spam bots.</p>

Title: Spell email address for forums

Body:
How can I make the code of the mail to spell it  and undetectable for forum when I try to put it in html

Thank's anticipated

Like this ! but more sophisticated

<h>mariaburkke76</h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>@<h><h><h><h><h>g<h><h><h><h><h><h><h><h><h><h><h>m<h><h><h>a<h><h>i<h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>l<h><h><h><h>.<h>com<h><h><h><h><h><h><h><h><h>


问:
Python Regex multi group pattern findall() returning empty list
I am trying to use Regex multi group pattern to extract different CPU specs from a line, but getting an empty list.When i try individual groups separately, i am able to extract corresponding values. How should i use multi group pattern here? Please help!</p>

```<code>import re

line = "R7000 CPU at 160MHz, Implementation 39, Rev 2.1, 256KB L2, 512KB L3 Cache"

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)(?P<L2>\s+\w+\s+L2)(?P<L3>\s+\w+\s+L3)"
pat_cpu_freq = r"(?P<freq>\s+\w+Hz)"
pat_cpu_l2 = r"(?P<L2>\s+\w+\s+L2)"
pat_cpu_l3 = r"(?P<L3>\s+\w+\s+L3)"

# empty list coming when pat_cpu_values_combined is searched

print re.findall(pat_cpu_values_combined, line)

# below individual group pattern findall are working fine

print re.findall(pat_cpu_freq, line)
print re.findall(pat_cpu_l2, line)
print re.findall(pat_cpu_l3, line)
</code>```

答:
Your combined regex is looking for each of those patterns smashed together, with no intermediate characters.  You can instead combine your patterns with the | separator.

```<code>pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)|(?P<L2>\s+\w+\s+L2)|(?P<L3>\s+\w+\s+L3)"

[''.join(g) for g in  re.findall(pat_cpu_values_combined, line)]
# returns:
[' 160MHz', ' 256KB L2', ' 512KB L3']
</code>```

Body:
I am trying to use Regex multi group pattern to extract different CPU specs from a line, but getting an empty list.When i try individual groups separately, i am able to extract corresponding values. How should i use multi group pattern here? Please help!

import re

line = "R7000 CPU at 160MHz, Implementation 39, Rev 2.1, 256KB L2, 512KB L3 Cache"

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)(?P<L2>\s+\w+\s+L2)(?P<L3>\s+\w+\s+L3)"
pat_cpu_freq = r"(?P<freq>\s+\w+Hz)"
pat_cpu_l2 = r"(?P<L2>\s+\w+\s+L2)"
pat_cpu_l3 = r"(?P<L3>\s+\w+\s+L3)"

# empty list coming when pat_cpu_values_combined is searched

print re.findall(pat_cpu_values_combined, line)

# below individual group pattern findall are working fine

print re.findall(pat_cpu_freq, line)
print re.findall(pat_cpu_l2, line)
print re.findall(pat_cpu_l3, line)

Body:
Your combined regex is looking for each of those patterns smashed together, with no intermediate characters.  You can instead combine your patterns with the | separator.

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)|(?P<L2>\s+\w+\s+L2)|(?P<L3>\s+\w+\s+L3)"

[''.join(g) for g in  re.findall(pat_cpu_values_combined, line)]
# returns:
[' 160MHz', ' 256KB L2', ' 512KB L3']


问:
Getting the index of the leftmost active bit in an integer instantly
How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

```<code>int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}
</code>```

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit
(Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!

答:
iBug's answer is very interesting, and I had never thought of doing it this way. If you're doing huge calculations where you want to find the leftmost digit many many times, I would recomment __builtin_clz in c++11. If you perform the snippet

```<code>for(int i = 31 - __builtin_clz; i >= 0; i--) {
    int left_most_bit = myInt & (1 << i);
}
</code>```

This will start from the left_most_bit and work it's way to the right. Hope this helps!
Implementation of __builtin_clz

Body:
How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit
(Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!

Body:
iBug's answer is very interesting, and I had never thought of doing it this way. If you're doing huge calculations where you want to find the leftmost digit many many times, I would recomment __builtin_clz in c++11. If you perform the snippet

for(int i = 31 - __builtin_clz; i >= 0; i--) {
    int left_most_bit = myInt & (1 << i);
}

This will start from the left_most_bit and work it's way to the right. Hope this helps!
Implementation of __builtin_clz


问:
Can't find file I created
I am new to java and I have a problem with finding a file I created that is usually visible within Eclipse.After running and refreshing multiple times I still don't see it.Here is my code, any help would be welcome.</p>

```<code>    Scanner input = new Scanner(System.in);
    Scanner x= new Scanner(System.in);
    System.out.println("You got a high score!");
    System.out.println();
    System.out.println("Please enter your score: ");

    int score = input.nextInt();
    System.out.println("Please enter your name: ");

    String name = x.nextLine();

    input.close();

    File file = new File("highscore.txt");

    try(BufferedWriter bw = new BufferedWriter(new FileWriter(file))){

        bw.write(score);
        bw.write(name);

    } catch (FileNotFoundException e) {
        System.out.println("File is not found");;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
</code>```

答:
The file will be created where your class file is created.
Ex - Say your file name path is "c:\dinesh\com\dinesh\MyFirstProgram.java". When you compile your file, you will have class file will be in "c:\dinesh\com\dinesh\MyFirstProgram.class". After the program runs, you will find the file in "c:\dinesh\com\dinesh\highscore.txt"

Title: Can't find file I created

Body:
I am new to java and I have a problem with finding a file I created that is usually visible within Eclipse.After running and refreshing multiple times I still don't see it.Here is my code, any help would be welcome.

    Scanner input = new Scanner(System.in);
    Scanner x= new Scanner(System.in);
    System.out.println("You got a high score!");
    System.out.println();
    System.out.println("Please enter your score: ");

    int score = input.nextInt();
    System.out.println("Please enter your name: ");

    String name = x.nextLine();

    input.close();

    File file = new File("highscore.txt");

    try(BufferedWriter bw = new BufferedWriter(new FileWriter(file))){

        bw.write(score);
        bw.write(name);

    } catch (FileNotFoundException e) {
        System.out.println("File is not found");;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}


问:
Which is a better design: store single character or meaningful string in DB row?
Given I have a DB table as follows:

```<code><TableName>
  id: string
  sym: string
  type: string
</code>```

I can store the data into the DB table with two methods:

```<code>Method one:
0001, IBM, Stock
0002, IBM18Jan, Option

Method one:
0001, IBM, '1'
0002, IBM18Jan, '2'
</code>```

For method one, I don't need to make any conversion when I display the data.
However, I need to make a conversion from '1' to Stock and '2' to Option in method two. Basically, I have to maintenance a mapping somewhere in the query code.

Question> Which method is better? Obviously, by using method two, I can save lots of DB space but the conversion is required in later query statements.

答:
This might be perceived as a matter of opinion.  However, I strongly think that inscrutable codes that require magic external knowledge are a big design choice for databases -- and for any software.

Relational databases give you a simple solution -- reference tables.  You can store the "1"s and "2" if you like.  Then you can have another table that expands the definitions into their full names.

Some databases support other types -- such as enums -- that do essentially the same thing.

Body:
Given I have a DB table as follows:

<TableName>
  id: string
  sym: string
  type: string

I can store the data into the DB table with two methods:

Method one:
0001, IBM, Stock
0002, IBM18Jan, Option

Method one:
0001, IBM, '1'
0002, IBM18Jan, '2'

For method one, I don't need to make any conversion when I display the data.
However, I need to make a conversion from '1' to Stock and '2' to Option in method two. Basically, I have to maintenance a mapping somewhere in the query code.

Question> Which method is better? Obviously, by using method two, I can save lots of DB space but the conversion is required in later query statements.


问:
creating a For Loop to fill an empty buffer full of dashes in assembly
So this is what I have so far, and every time I get to the loop part of the code, I get Segmentation fault (core dumped).  Is this because some of my registers are holding things that are an incorrect size?

```<code> .data
   Welcome:
        .ascii "Welcome to League of Legends!!.\n\0"
  Instruction:
        .ascii "Player 1, enter a Champion's name: \0"
  Text:
        .space 12
  Text2:
        .space 12

  Guess:
        .ascii "Guess a letter: \0"
  Letter:
        .space 1
  SecretCharacter:
        .ascii "Your Champion is: \0"

  .text

  .global _start

  _start:
         mov $Welcome, %rax
        call PrintCString

        mov $Instruction, %rax
        call PrintCString
        mov $Text, %rax
        mov $12, %rbx
        call ScanCString
        mov %rax, %rbx
        mov %rax, %rbp
        call LengthCString
        mov %rax, %rcx

        mov $0, %rdi
        mov $45, %ch

Loop:
        cmp %rcx, %rdi
        jge End

        mov $Text2, %eax
        movb %ch, (%rax, %rdi)
        add $1, %rdi
        jmp Loop

End:
        call PrintCString
        call EndProgram
</code>```

答: You're using both rcx and ch at the same time, but ch is part of rcx. Try using dh instead of ch.</p>

Body:
So this is what I have so far, and every time I get to the loop part of the code, I get Segmentation fault (core dumped).  Is this because some of my registers are holding things that are an incorrect size?

 .data
   Welcome:
        .ascii "Welcome to League of Legends!!.\n\0"
  Instruction:
        .ascii "Player 1, enter a Champion's name: \0"
  Text:
        .space 12
  Text2:
        .space 12

  Guess:
        .ascii "Guess a letter: \0"
  Letter:
        .space 1
  SecretCharacter:
        .ascii "Your Champion is: \0"

  .text

  .global _start

  _start:
         mov $Welcome, %rax
        call PrintCString

        mov $Instruction, %rax
        call PrintCString
        mov $Text, %rax
        mov $12, %rbx
        call ScanCString
        mov %rax, %rbx
        mov %rax, %rbp
        call LengthCString
        mov %rax, %rcx

        mov $0, %rdi
        mov $45, %ch

Loop:
        cmp %rcx, %rdi
        jge End

        mov $Text2, %eax
        movb %ch, (%rax, %rdi)
        add $1, %rdi
        jmp Loop

End:
        call PrintCString
        call EndProgram


问:
type error with LabelEncoder.fit_transform()
I was playing with the Titanic dataset on Kaggle (https://www.kaggle.com/c/titanic/data), and I want to use LabelEncoder from sklearn.preprocessing to transform Sex, originally labeled as 'male' or 'female' into '0' or '1'. I had the following four lines of code,

```<code>import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('titanic.csv')
df['Sex'] = LabelEncoder.fit_transform(df['Sex'])
</code>```

But when I ran it I received the following error message:

```<code>TypeError: fit_transform() missing 1 required positional argument: 'y'
</code>```

the error comes from line 4, i.e.,

```<code>df['Sex'] = LabelEncoder.fit_transform(df['Sex'])
</code>```

I wonder what went wrong here. Although I know I could also do the transformation using map, which might be even simpler, but I still want to know what's wrong with my usage of LabelEncoder.

答:
Try using following link to sklearn. LabelEncoder is a utility class and need to create the object with LabelEncoder():

```<code>le = LabelEncoder()
df['Sex'] = le.fit_transform(df['Sex'])
</code>```

Testing with example:

```<code># create test series
gender = pd.Series(['male', 'female', 'male'])

le = LabelEncoder()
transformed_val = le.fit_transform(gender)

# checking result after using label encoder
print(transformed_val)
</code>```

Results:

```<code>[1 0 1]
</code>```

Body:
I was playing with the Titanic dataset on Kaggle (https://www.kaggle.com/c/titanic/data), and I want to use LabelEncoder from sklearn.preprocessing to transform Sex, originally labeled as 'male' or 'female' into '0' or '1'. I had the following four lines of code,

import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('titanic.csv')
df['Sex'] = LabelEncoder.fit_transform(df['Sex'])

But when I ran it I received the following error message:

TypeError: fit_transform() missing 1 required positional argument: 'y'

the error comes from line 4, i.e.,

df['Sex'] = LabelEncoder.fit_transform(df['Sex'])

I wonder what went wrong here. Although I know I could also do the transformation using map, which might be even simpler, but I still want to know what's wrong with my usage of LabelEncoder.

Body:
Try using following link to sklearn. LabelEncoder is a utility class and need to create the object with LabelEncoder():

le = LabelEncoder()
df['Sex'] = le.fit_transform(df['Sex'])

Testing with example:

# create test series
gender = pd.Series(['male', 'female', 'male'])

le = LabelEncoder()
transformed_val = le.fit_transform(gender)

# checking result after using label encoder
print(transformed_val)

Results:

[1 0 1]


问:
Vimscript: how do you map backspace or delete keys?
Does anyone know how to map the backspace and delete keys in Vimscript?</p>

答:
From Normal mode, you can type : then Press Ctrl+k followed by any key, and vim will tell you how to reference it.  For example, from normal mode typing : then pressing Ctrl+k and pressing Backspace results in:

:<BS>

Then you can remap like normal:

```<code>:map <BS> :echo 'You pressed backspace!'<CR>
:map <Del> :echo 'You pressed Delete!'<CR>
</code>```

Obviously you'll want to do something more useful than that, so change the part from :echo onward.  Here is a helpful tutorial to get started if you are new to remapping keys in vim.

Body:
From Normal mode, you can type : then Press Ctrl+k followed by any key, and vim will tell you how to reference it.  For example, from normal mode typing : then pressing Ctrl+k and pressing Backspace results in:

:<BS>

Then you can remap like normal:

:map <BS> :echo 'You pressed backspace!'<CR>
:map <Del> :echo 'You pressed Delete!'<CR>

Obviously you'll want to do something more useful than that, so change the part from :echo onward.  Here is a helpful tutorial to get started if you are new to remapping keys in vim.


答:
If you're interested in the actual fastest answer (at least on a desktop), here it is: use the _bit_scan_reverse intrinsic supported by Intel Compiler and Clang (maybe Visual Studio and GCC as well).

```<code>#include "immintrin.h"
int main() { printf("%i", _bit_scan_reverse(9)); }
</code>```

Result: 3 (because 1<<3 = 8 is the highest bit set in 9).

Documentation

If you're worried about portability (as you should be with all proprietary extensions like this one), just include a fallback function and use the preprocessor to select the implementation you need:

```<code>#ifdef __SSE__ // All SSE processors support bsf/bsr
#include "immintrin.h"
static inline int bit_scan_reverse(int n) { return _bit_scan_reverse(n); }
#else
// Fallback implementation here
#endif
</code>```

Note that the _bit_scan_reverse returns an unspecified value for n=0. If this is a problem you can add a ternary to the code in bit_scan_reverse: return n == 0 ? 0 : _bit_scan_reverse(n);.

Title: Getting the index of the leftmost active bit in an integer instantly

Body:
If you're interested in the actual fastest answer (at least on a desktop), here it is: use the _bit_scan_reverse intrinsic supported by Intel Compiler and Clang (maybe Visual Studio and GCC as well).

#include "immintrin.h"
int main() { printf("%i", _bit_scan_reverse(9)); }

Result: 3 (because 1<<3 = 8 is the highest bit set in 9).

Documentation

If you're worried about portability (as you should be with all proprietary extensions like this one), just include a fallback function and use the preprocessor to select the implementation you need:

#ifdef __SSE__ // All SSE processors support bsf/bsr
#include "immintrin.h"
static inline int bit_scan_reverse(int n) { return _bit_scan_reverse(n); }
#else
// Fallback implementation here
#endif

Note that the _bit_scan_reverse returns an unspecified value for n=0. If this is a problem you can add a ternary to the code in bit_scan_reverse: return n == 0 ? 0 : _bit_scan_reverse(n);.


问:
how to exclude current log file while archiving log files inside a directory
I have to archive a directory in which log file are present(File names are in a format as i.e 2017-12-06.log).I have to archive all files except 2017-12-06.log.

I have a logs directory where all log files are present and a script create-zip.js. When I run following script with node create-zip.js, It creates directories as /archive/<year>/<month_name> and saves here logs.zip folder.

Everything is fine except when I extract logs.zip, my archived log files are found inside /archive/<year>/<month_name>/home/hotam/nodejs_archive_example/logs but I want these files inside /archive/<year>/<month_name>. I googled a lot but couldn't find solution. Thanks in advance.

I have following script(create-zip.js):

```<code>    'use strict';
    var fs = require('fs'),
    path = require('path'),
    archiver = require('archiver'),
    currDate = new Date(),
    year = currDate.getFullYear(),
    month = currDate.toLocaleString("en-us", { month: "long" }),
    dir = path.join(__dirname + '/archive/' + year + '/' + month),
    ignoredFile = currDate.getFullYear()+'-'+('0' + (currDate.getMonth() + 1)).slice(-2)+'-'+('0' + currDate.getDate()).slice(-2)+'.log';

//Function to create directories recursively
exports.createDir = function (dir) {
    const splitPath = dir.split('/');
    splitPath.reduce(function (dirPath, subPath) {
        let currentPath;
        if (subPath != '.') {
            currentPath = dirPath + '/' + subPath;
            if (!fs.existsSync(currentPath)) {
                fs.mkdirSync(currentPath);
            }
        } else {
            currentPath = subPath;
        }
        return currentPath
    }, '');
};
exports.createDir(dir);

var output = fs.createWriteStream(path.join(dir, 'logs.zip'));
var archive = archiver('zip', {});
var logPath = __dirname + '/logs';

output.on('close', function () {
    if (fs.existsSync(logPath)) {
        fs.readdirSync(logPath).forEach(function (file, index) {
            var curPath = logPath + "/" + file;
            if (!fs.lstatSync(logPath).isFile()) {
                // delete file
                if(!(file == ignoredFile)) {
                    fs.unlinkSync(curPath);
                }
            }
        });
    }
});

output.on('end', function () {
    console.log('Data has been drained');
});

archive.on('warning', function (err) {
    if (err.code === 'ENOENT') {
        console.log(err);
    } else {
        // throw error
        console.log(err);
        throw err;
    }
});

archive.on('error', function (err) {
    logger.error(err);
    throw err;
});

archive.pipe(output);

//ignoring 2017-12-06.log
archive
    .glob(__dirname + '/logs/**', {
        ignore: [__dirname + '/logs/'+ignoredFile]
    })
    .finalize();
</code>```

答:
I got the solution of this scenario. I changed archive.glob() and it worked for me.</p>

```<code>`//ignoring 2017-12-06.log
archive
    .glob('./logs/**/*', {
        ignore: ['./logs/**/*' + ignoredFile]
    })
    .finalize();`
</code>```

Body:
I have to archive a directory in which log file are present(File names are in a format as i.e 2017-12-06.log).I have to archive all files except 2017-12-06.log.

I have a logs directory where all log files are present and a script create-zip.js. When I run following script with node create-zip.js, It creates directories as /archive/<year>/<month_name> and saves here logs.zip folder.

Everything is fine except when I extract logs.zip, my archived log files are found inside /archive/<year>/<month_name>/home/hotam/nodejs_archive_example/logs but I want these files inside /archive/<year>/<month_name>. I googled a lot but couldn't find solution. Thanks in advance.

I have following script(create-zip.js):

    'use strict';
    var fs = require('fs'),
    path = require('path'),
    archiver = require('archiver'),
    currDate = new Date(),
    year = currDate.getFullYear(),
    month = currDate.toLocaleString("en-us", { month: "long" }),
    dir = path.join(__dirname + '/archive/' + year + '/' + month),
    ignoredFile = currDate.getFullYear()+'-'+('0' + (currDate.getMonth() + 1)).slice(-2)+'-'+('0' + currDate.getDate()).slice(-2)+'.log';

//Function to create directories recursively
exports.createDir = function (dir) {
    const splitPath = dir.split('/');
    splitPath.reduce(function (dirPath, subPath) {
        let currentPath;
        if (subPath != '.') {
            currentPath = dirPath + '/' + subPath;
            if (!fs.existsSync(currentPath)) {
                fs.mkdirSync(currentPath);
            }
        } else {
            currentPath = subPath;
        }
        return currentPath
    }, '');
};
exports.createDir(dir);

var output = fs.createWriteStream(path.join(dir, 'logs.zip'));
var archive = archiver('zip', {});
var logPath = __dirname + '/logs';

output.on('close', function () {
    if (fs.existsSync(logPath)) {
        fs.readdirSync(logPath).forEach(function (file, index) {
            var curPath = logPath + "/" + file;
            if (!fs.lstatSync(logPath).isFile()) {
                // delete file
                if(!(file == ignoredFile)) {
                    fs.unlinkSync(curPath);
                }
            }
        });
    }
});

output.on('end', function () {
    console.log('Data has been drained');
});

archive.on('warning', function (err) {
    if (err.code === 'ENOENT') {
        console.log(err);
    } else {
        // throw error
        console.log(err);
        throw err;
    }
});

archive.on('error', function (err) {
    logger.error(err);
    throw err;
});

archive.pipe(output);

//ignoring 2017-12-06.log
archive
    .glob(__dirname + '/logs/**', {
        ignore: [__dirname + '/logs/'+ignoredFile]
    })
    .finalize();

Body:
I got the solution of this scenario. I changed archive.glob() and it worked for me.

`//ignoring 2017-12-06.log
archive
    .glob('./logs/**/*', {
        ignore: ['./logs/**/*' + ignoredFile]
    })
    .finalize();`


问:
How can i make navigation bar responsive on mobile devise
here is the link to my css file.this is the image of my navivigation css script

Here is the html file screenshot of my navigation panelThis is the html screenshot of my navigation script

Please i need help to make my navigation respomnsive on any mobile device as it does not work at all currently.

答:
Add these links under the title in head

```<code><meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
</code>```

follow this image

Body:
Add these links under the title in head

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />

follow this image


问:
How to launch a background activity from a widget?
I have an android widget which has a very simple function.  The widget simply launches an activity when pressed, runs through the activity, pops a toast, and closes the activity.

The annoying thing is that when the widget is pressed on the home screen, the screen flickers as it opens and closes the activity.  Is there any way to launch the activity from the background, to avoid this flicker?  I'm kind of looking to do something similar to the ATK widget, which simply pops up a toast after closing all the background processes.

If it's possible to just run a single function in place of a PendingIntent, that would definitely work as well.  Thanks!

答:
I'm doing this kind of thing using Application class. You need to declare your own - e.g. MyApplication class (need to be declared in Android manifest) and during creation MyApplication just launch separate Thread:

```<code>public class MyApplication()
{

    // only lazy initializations here!
    public MyApplication()
    {
        super();
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.d(TAG, "Starting MyApplication"+this.toString());
        Thread myThread=new MyThread();
        myThread.start();
    }
}
</code>```

So in the end you will have "background" application which doesn't contain any activities. Application will be alive while your thread is alive. From those thread you can start whatever you want - for instance popup window, toast or any activity - depending on what you want.

Body:
I'm doing this kind of thing using Application class. You need to declare your own - e.g. MyApplication class (need to be declared in Android manifest) and during creation MyApplication just launch separate Thread:

public class MyApplication()
{

    // only lazy initializations here!
    public MyApplication()
    {
        super();
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.d(TAG, "Starting MyApplication"+this.toString());
        Thread myThread=new MyThread();
        myThread.start();
    }
}

So in the end you will have "background" application which doesn't contain any activities. Application will be alive while your thread is alive. From those thread you can start whatever you want - for instance popup window, toast or any activity - depending on what you want.