答:
Check this simple example, it will clear your doubt:

var a = null;

console.log(typeof a, typeof a === 'object')

var b = function (){};

console.log(typeof b, typeof b === 'function')

var c = "";

console.log(typeof c, typeof c === 'string')```
</div>
</div>
</p>

<p><strong>Reason</strong>: <code>typeof</code> returns a string, of the type of the value you provided, When you check the value returned by <code>typeof</code>, it will be in string form, like:</p>

```'object', 'function', 'string' etc.
```

And you are checking the typeof "object", that's why it returned string.

Title: typeof typeof x returns string and not object since type of null is object

Body:
Check this simple example, it will clear your doubt:

var a = null;

console.log(typeof a, typeof a === 'object')

var b = function (){};

console.log(typeof b, typeof b === 'function')

var c = "";

console.log(typeof c, typeof c === 'string')

Reason: typeof returns a string, of the type of the value you provided, When you check the value returned by typeof, it will be in string form, like:

'object', 'function', 'string' etc.

And you are checking the typeof "object", that's why it returned string.


来源: stackexchange

问:
Dealing with service configuration in Angular 2 DIC
Coming from a Java background, it's being hard for me to understand a few things about Angular, specially the dependency injection mechanism. It's quite different from what i'm used to. Right now i'm trying to understand how it's possible to inject configuration variables into a service i'm creating:

```<code>@Injectable()
export class MyBackendService {
    constructor(url: string, version: string, token: string, secret: string) { }
}
</code>```

All those strings are stored in my environment.{env}.ts files. But i have no idea how to tell Angular to fetch those variables and inject into my service class. Does anyone have any tip on the idiomatic way of doing this?

答:
In order to inject a dependency from the Angular DIC the dependency should be registered in it.

The way to register an Injectable entities in the DIC is through an @NgModule. and then import this one from the module which uses it.

In order to register a service or a value to the DIC it should be in the providers array of the NgModule.

In this concrete example ( if you need to add it to the DIC ) I would prefer to inject a config value to the BackendService with all the data required for that service taken from a config file of the app:

1 Configuration

Config Module

```<code>import { NgModule } from '@angular/core';
import { CONFIG } from "...";

@NgModule({
    providers: [
        { provide: CONFIG, useValue: CONFIG }
    ]
})
export class ConfigModule{}
</code>```

Config value

```<code>export const CONFIG = {

     endpoint: {
        service1: {
            url: 'http://api.your-app.com/service1/',
            withCredentials: true,
            ...
        },
    }
}
</code>```

2 Service (consumer of the config)

Module:

```<code>import { NgModule } from '@angular/core';
import { Service1 } from "...";
import { CONFIG } from "...";
import { ConfigModule } from "...";

@NgModule({
    imports: [
        ConfigModule // Import the config module to make the config available for the services in this module
    ]
    providers: [
        {
            provide: Service1 // Register your service in the DIC the one that performs the requests to that server endpoint,
            useFactory: (config) => new Service1(config),
            deps:[
                CONFIG
            ]
        }
    ]
})
export class ApiModule{}
</code>```

Service

```<code>import { NgModule } from '@angular/core';

export class Service1{

    private _endpointUrl:string;

    constructor(config) {
        this._endpointUrl = config.endpoint.service1.url;
    }
}
</code>```

3 Module of the app that consumes the Service 1

```<code>    import { NgModule } from '@angular/core';
    import { ApiModule } from "...";

    @NgModule({
        imports: [
            ApiModule
        ]
        ...
    })
    export class AppComponent{}
</code>```

So then your injection chain would be

```<code>AppComponent <- Service1 <- CONFIG
</code>```

All this assumes that we want the config to be an injectable

but

Do we really need the config to be injected ?

In general the config is just a JSON structure and it use to be a constant that the app consumes and in this case I would just import it where it is needed using typescript import and avoiding adding it to the DIC. eg:

Service

```<code>import {CONFIG} from '...';

export class Service1{

    private config;

    constructor() {
        this._config = CONFIG;
    }
}
</code>```

Later on if it needs to be loaded from an endpoint that can be solved with the module loader ( SystemJS, Webpack ... ) you use in your app.

The down side of this shows up if you want to update the app configuration without reloading the browser and in that case in my opinion the config values should be provided by a configuration service provided by the DIC

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
Coming from a Java background, it's being hard for me to understand a few things about Angular, specially the dependency injection mechanism. It's quite different from what i'm used to. Right now i'm trying to understand how it's possible to inject configuration variables into a service i'm creating:

@Injectable()
export class MyBackendService {
    constructor(url: string, version: string, token: string, secret: string) { }
}

All those strings are stored in my environment.{env}.ts files. But i have no idea how to tell Angular to fetch those variables and inject into my service class. Does anyone have any tip on the idiomatic way of doing this?

Body:
In order to inject a dependency from the Angular DIC the dependency should be registered in it.

The way to register an Injectable entities in the DIC is through an @NgModule. and then import this one from the module which uses it.

In order to register a service or a value to the DIC it should be in the providers array of the NgModule.

In this concrete example ( if you need to add it to the DIC ) I would prefer to inject a config value to the BackendService with all the data required for that service taken from a config file of the app:

1 Configuration

Config Module

import { NgModule } from '@angular/core';
import { CONFIG } from "...";

@NgModule({
    providers: [
        { provide: CONFIG, useValue: CONFIG }
    ]
})
export class ConfigModule{}

Config value

export const CONFIG = {

     endpoint: {
        service1: {
            url: 'http://api.your-app.com/service1/',
            withCredentials: true,
            ...
        },
    }
}

2 Service (consumer of the config)

Module:

import { NgModule } from '@angular/core';
import { Service1 } from "...";
import { CONFIG } from "...";
import { ConfigModule } from "...";

@NgModule({
    imports: [
        ConfigModule // Import the config module to make the config available for the services in this module
    ]
    providers: [
        {
            provide: Service1 // Register your service in the DIC the one that performs the requests to that server endpoint,
            useFactory: (config) => new Service1(config),
            deps:[
                CONFIG
            ]
        }
    ]
})
export class ApiModule{}

Service

import { NgModule } from '@angular/core';

export class Service1{

    private _endpointUrl:string;

    constructor(config) {
        this._endpointUrl = config.endpoint.service1.url;
    }
}

3 Module of the app that consumes the Service 1

    import { NgModule } from '@angular/core';
    import { ApiModule } from "...";

    @NgModule({
        imports: [
            ApiModule
        ]
        ...
    })
    export class AppComponent{}

So then your injection chain would be

AppComponent <- Service1 <- CONFIG

All this assumes that we want the config to be an injectable

but

Do we really need the config to be injected ?

In general the config is just a JSON structure and it use to be a constant that the app consumes and in this case I would just import it where it is needed using typescript import and avoiding adding it to the DIC. eg:

Service

import {CONFIG} from '...';

export class Service1{

    private config;

    constructor() {
        this._config = CONFIG;
    }
}

Later on if it needs to be loaded from an endpoint that can be solved with the module loader ( SystemJS, Webpack ... ) you use in your app.

The down side of this shows up if you want to update the app configuration without reloading the browser and in that case in my opinion the config values should be provided by a configuration service provided by the DIC

Hope this helps.


问:
How to unpack a list?
When extracting data from a list this way

```<code>line[0:3], line[3][:2], line[3][2:]
</code>```

I receive an array and two variables after it, as should be expected:

```<code>(['a', 'b', 'c'], 'd', 'e')
</code>```

I need to manipulate the list so the end result is

```<code>('a', 'b', 'c', 'd', 'e')
</code>```

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

答:
Try this.

```<code>line = ['a', 'b', 'c', 'de']
tuple(line[0:3] + [line[3][:1]] + [line[3][1:]])
('a', 'b', 'c', 'd', 'e')
</code>```

NOTE:
I think there is some funny business in your slicing logic.
If [2:] returns any characters, [:2] must return 2 characters.
Please provide your input line.

ContentLicense: CC BY-SA 2.5

Title: How to unpack a list?

Body:
When extracting data from a list this way

line[0:3], line[3][:2], line[3][2:]

I receive an array and two variables after it, as should be expected:

(['a', 'b', 'c'], 'd', 'e')

I need to manipulate the list so the end result is

('a', 'b', 'c', 'd', 'e')

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

Body:
Try this.

line = ['a', 'b', 'c', 'de']
tuple(line[0:3] + [line[3][:1]] + [line[3][1:]])
('a', 'b', 'c', 'd', 'e')

NOTE:
I think there is some funny business in your slicing logic.
If [2:] returns any characters, [:2] must return 2 characters.
Please provide your input line.


问:
Get the second largest number in a list in linear time
I'm learning Python and the simple ways to handle lists is presented as an advantage. Sometimes it is, but look at this:

```<code>>>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
>>> numbers.remove(max(numbers))
>>> max(numbers)
74
</code>```

A very easy, quick way of obtaining the second largest number from a list. Except that the easy list processing helps write a program that runs through the list twice over, to find the largest and then the 2nd largest. It's also destructive - I need two copies of the data if I wanted to keep the original. We need:

```<code>>>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
>>> if numbers[0]>numbers[1]):
...    m, m2 = numbers[0], numbers[1]
... else:
...    m, m2 = numbers[1], numbers[0]
...
>>> for x in numbers[2:]:
...    if x>m2:
...       if x>m:
...          m2, m = m, x
...       else:
...          m2 = x
...
>>> m2
74
</code>```

Which runs through the list just once, but isn't terse and clear like the previous solution.

So: is there a way, in cases like this, to have both? The clarity of the first version, but the single run through of the second?

答:
If you do not mind using numpy (import numpy as np):

```<code>np.partition(numbers, -2)[-2]
</code>```

gives you the 2nd largest element of the list with a guaranteed worst-case O(n) running time.

The partition(a, kth) methods returns an array where the kth element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.

Body:
I'm learning Python and the simple ways to handle lists is presented as an advantage. Sometimes it is, but look at this:

>>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
>>> numbers.remove(max(numbers))
>>> max(numbers)
74

A very easy, quick way of obtaining the second largest number from a list. Except that the easy list processing helps write a program that runs through the list twice over, to find the largest and then the 2nd largest. It's also destructive - I need two copies of the data if I wanted to keep the original. We need:

>>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
>>> if numbers[0]>numbers[1]):
...    m, m2 = numbers[0], numbers[1]
... else:
...    m, m2 = numbers[1], numbers[0]
...
>>> for x in numbers[2:]:
...    if x>m2:
...       if x>m:
...          m2, m = m, x
...       else:
...          m2 = x
...
>>> m2
74

Which runs through the list just once, but isn't terse and clear like the previous solution.

So: is there a way, in cases like this, to have both? The clarity of the first version, but the single run through of the second?

Body:
If you do not mind using numpy (import numpy as np):

np.partition(numbers, -2)[-2]

gives you the 2nd largest element of the list with a guaranteed worst-case O(n) running time.

The partition(a, kth) methods returns an array where the kth element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.


问:
Completely remove a div if screen width is less than 800 (mobile device)
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

```<code>    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);
</code>```

答:
In this case, you can get the device's screen width as shown below and do your operations accordingly.</p>

```<code>var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
</code>```

Body:
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);

Body:
In this case, you can get the device's screen width as shown below and do your operations accordingly.

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;


问:
ionic 2 grid problems with col-* / respnosive
I've got this code

```<code><ion-grid>
      <ion-row wrap>
        <ion-col col-2>
          <h3>Adresse</h3>
        </ion-col>
        <ion-col col-1 offset-1>
          <h3>Telefon</h3>
        </ion-col>
        <ion-col col-4>
          <h3>Geb./Fam./Adelspräd.</h3>
        </ion-col>
        <ion-col col-2>
          <h3>Beruf/Stellung/Titel</h3>
        </ion-col>
        <ion-col col-2>
          <h3>KNR/Inhaber</h3>
        </ion-col>
      </ion-row>
    </ion-grid>
</code>```

but it doesn't do anything with col-* attributes, like it's described in here
https://ionicframework.com/docs/v2/api/components/grid/Grid/
I can't find any called css-classes. There just 5 cols with the same width

Bet when I take width-10, it reacts to what I'm doing.

At the end, I want something like this

```<code><ion-col col-12 col-sm>
  1 of 4
</ion-col>
</code>```

to get it responsive.

Thanks for your help!

答:
It seams, that ionic doesn't support the whole flexbox-grid, and just knows the classes like width-*.

To use the whole power of the flexbox-grid, I imported the original flexbox css-file and everything works fine.

website of the flexbox-grid

Body:
I've got this code

<ion-grid>
      <ion-row wrap>
        <ion-col col-2>

Adresse

        </ion-col>
        <ion-col col-1 offset-1>

Telefon

        </ion-col>
        <ion-col col-4>

Geb./Fam./Adelspräd.

        </ion-col>
        <ion-col col-2>

Beruf/Stellung/Titel

        </ion-col>
        <ion-col col-2>

KNR/Inhaber

        </ion-col>
      </ion-row>
    </ion-grid>

but it doesn't do anything with col-* attributes, like it's described in here
https://ionicframework.com/docs/v2/api/components/grid/Grid/
I can't find any called css-classes. There just 5 cols with the same width

Bet when I take width-10, it reacts to what I'm doing.

At the end, I want something like this

<ion-col col-12 col-sm>
  1 of 4
</ion-col>

to get it responsive.

Thanks for your help!


问:
How to quickly deploy React / Redux app as a sample?
It seems one way is to deploy the React app to Heroku, but is there a simple way to deploy to our own website or to GitHub page feature so that you can see the page off from GitHub? (just as a sample, not for production)

Details:

It seems that one possible way may be to use

```<code>wget -r --no-parent http://localhost:8080 -P sample -nH
cp -rf images any_needed_folder sample
</code>```

and now you can git add sample and git commit and push to github and turn on the GitHub page for your repo and be able to see your React app inside of sample.

You also need to change the paths in the index.html, from /bundle.js to bundle.js, etc, because you need relative path instead of going to the root of your website.

(I used wget to recursively download index.html, bundle.js, and style/ (the CSS files) because bundle.js cannot be found in the whole directory on the local hard drive. I used wget because curl doesn't seem to be able to download recursively)

答:
Ok, I found that the latest React, it will tell you to use

```<code>create-react-app hello-world
</code>```

to create the app, and then there is an official

```<code>npm run build
</code>```

to build it to host it as a Gthub page, or on your own website.

Body:
It seems one way is to deploy the React app to Heroku, but is there a simple way to deploy to our own website or to GitHub page feature so that you can see the page off from GitHub? (just as a sample, not for production)

Details:

It seems that one possible way may be to use

wget -r --no-parent http://localhost:8080 -P sample -nH
cp -rf images any_needed_folder sample

and now you can git add sample and git commit and push to github and turn on the GitHub page for your repo and be able to see your React app inside of sample.

You also need to change the paths in the index.html, from /bundle.js to bundle.js, etc, because you need relative path instead of going to the root of your website.

(I used wget to recursively download index.html, bundle.js, and style/ (the CSS files) because bundle.js cannot be found in the whole directory on the local hard drive. I used wget because curl doesn't seem to be able to download recursively)

Body:
Ok, I found that the latest React, it will tell you to use

create-react-app hello-world

to create the app, and then there is an official

npm run build

to build it to host it as a Gthub page, or on your own website.


问:
Binding list of paragraphs to RichTextBlock
Right now, I have the data I need binding to a RichTextBlock, but I'm unable to format it, since I'm just using one long string bound to the run on a paragraph setup in my RichTextBlock. Obviously, this isn't ideal. I would like to be able to change font sizes or font weights for some words, but can't see of a way to do that with my current method.

```<code><RichTextBlock TextAlignment="Justify" TextWrapping="WrapWholeWords" Name="richTB">
    <Paragraph>
        <Run Text="{Binding}" />
    </Paragraph>
</RichTextBlock>
</code>```

I know I can create a RichTextBlock in my code behind, and add paragraphs manually to that, but how would I bind it? Since it's in my page.resources?

答:
I believe you are {binding} the source and hence inside the Code, you can take help from this code:

```<code>Paragraph para = new Paragraph();
            para.Inlines.Add(new Run { Text = sample, FontSize = 15 });
            rtb.Blocks.Add(para);
</code>```

where rtb is a richtextblock.

Body:
Right now, I have the data I need binding to a RichTextBlock, but I'm unable to format it, since I'm just using one long string bound to the run on a paragraph setup in my RichTextBlock. Obviously, this isn't ideal. I would like to be able to change font sizes or font weights for some words, but can't see of a way to do that with my current method.

<RichTextBlock TextAlignment="Justify" TextWrapping="WrapWholeWords" Name="richTB">
    <Paragraph>
        <Run Text="{Binding}" />
    </Paragraph>
</RichTextBlock>

I know I can create a RichTextBlock in my code behind, and add paragraphs manually to that, but how would I bind it? Since it's in my page.resources?

Body:
I believe you are {binding} the source and hence inside the Code, you can take help from this code:

Paragraph para = new Paragraph();
            para.Inlines.Add(new Run { Text = sample, FontSize = 15 });
            rtb.Blocks.Add(para);

where rtb is a richtextblock.


问:
Tensorflow - How to ignore certain labels
I'm trying to implement a fully convolutional network and train it on the Pascal VOC dataset, however after reading up on the labels in the set, I see that I need to somehow ignore the "void" label. In Caffe their softmax function has an argument to ignore labels, so I'm wondering what the mechanic is, so I can implement something similar in tensorflow.

Thanks

答:
In tensorflow you're feeding the data in feed_dict right? Generally you'd want to just pre-process the data and remove the unwanted samples - don't give them to tensorflow for processing.

My prefered approach is a producer-consumer model where you fire up a tensorflow queue and load it with samples from a loader thread which just skips enqueuing your void samples.

In training your model dequeue samples in the model (you don't use feed_dict in the optimize step). This way you're not bothering to write out a whole new dataset with the specific preprocessing step you're interested in today (tomorrow you're likely to find you want to do some other preprocessing step).

As a side comment, I think tensorflow is a little more do-it-yourself than some other frameworks. But I tend to like that, it abstracts enough to be convenient, but not so much that you don't understand what's happening. When you implement it you understand it, that's the motto that comes to mind with tensorflow.


问:
Shell script to mount windows network location in linux machine
I have two questions here. I am able to mount a windows network path in my Ubuntu machine by doing following:

```<code>sudo mount -t cifs -o username=user \\\\my_windows\\test /net/loc
</code>```

All the files and folders present in Windows machine is now available in Ubuntu machine with path '/net/loc'.

Here are my doubts:

I can see all files of windows in linux path. Is it possible to create files/folders in Linux path(the mount path where windows path is mounted) and it will be reflected in Windows machine? I am not able to write in Linux machine where windows network location is mounted. It throws me error "Can't open file for writing".

I am trying to write a shell script (a ksh file) which will mount the windows network path. I wrote the below mount command in my file but this command prompts for password. Is there any way, I can write the command in shell script that it will not ask me for password and I can pass it as either as a parameter or some other mechanism?

mount -t cifs -o username=user \\my_windows\test /net/loc

Thank you

答:
Password can be passed as below

sudo mount -t cifs -o username=${USER},password=${PASSWORD},uid=,gid= //server-address/folder /mount/path/on/ubuntu

And with root access I am able to write in Linux path.

More information is here https://unix.stackexchange.com/questions/68079/mount-cifs-network-drive-write-permissions-and-chown

Body:
I have two questions here. I am able to mount a windows network path in my Ubuntu machine by doing following:

sudo mount -t cifs -o username=user \\\\my_windows\\test /net/loc

All the files and folders present in Windows machine is now available in Ubuntu machine with path '/net/loc'.

Here are my doubts:

I can see all files of windows in linux path. Is it possible to create files/folders in Linux path(the mount path where windows path is mounted) and it will be reflected in Windows machine? I am not able to write in Linux machine where windows network location is mounted. It throws me error "Can't open file for writing".

I am trying to write a shell script (a ksh file) which will mount the windows network path. I wrote the below mount command in my file but this command prompts for password. Is there any way, I can write the command in shell script that it will not ask me for password and I can pass it as either as a parameter or some other mechanism?

mount -t cifs -o username=user \\my_windows\test /net/loc

Thank you


问:
What is the benefit of the mergeMap in this @ngrx example?
The following example is taken from the @ngrx example.

I understand this observable this way. The first map function gets the payload which is the book to be added, again processed by the mergeMap where it saves to the database.

Original Code:

```<code>  @Effect()
  addBookToCollection$: Observable<Action> = this.actions$
    .ofType(collection.ActionTypes.ADD_BOOK)
    .map((action: collection.AddBookAction) => action.payload)
    .mergeMap(book =>
      this.db.insert('books', [ book ])
        .map(() => new collection.AddBookSuccessAction(book))
        .catch(() => of(new collection.AddBookFailAction(book)))
    );
</code>```

Can the below code do the same thing as the above? Why there is a mergeMap required?

Modified Code:

```<code>@Effect()
  addBookToCollection$: Observable<Action> = this.actions$
    .ofType(collection.ActionTypes.ADD_BOOK)
    .map((action: collection.AddBookAction) =>
      this.db.insert('books', [ action.payload ])
        .map(() => new collection.AddBookSuccessAction(action.payload))
        .catch(() => of(new collection.AddBookFailAction(action.payload)))
    );
</code>```

答:
Although @cartant added the first answer, the answer as well as comments are hard to understand. Here is how I can explain this code.

In the original code, this.actions$ is the originating observable. The observable created by the first map is the outer observable. The inner observable is the observable created by this.db.insert. Thus there are 3 observables here.

The effect is addBookToCollection$.

The purpose of this code (original code) is to generate a addBookToCollection$ observable of type Observable<action>. The first map will create a Observable<Book>. This type is not what the effect is, so simply can't end with the first map. This Observable<Book> need to be converted to Observable<Action>.

We can use switchMap or mergeMap to convert the Observable<Book> to Observable<action>. Both of these convert a high order observable to a first order like below:

Observable<Observable<Book> ----> Observable<Action>

The switchMap is beneficial for the async operations where the latest inner observable will be emitted and that can be subscribed by @ngrx. But mergeMap is used to let all the inner observables go through as concurrent. So it will allow all the books selected by the user to generate observables from this.db.insert. In essence, the mergeMap takes the outer observable from map and merges with the inner observable from this.db.insert to generate a new first order observable.

The mergeMap takes the book (action.payload from the previous map) and pass it to this.db.insert. this.db.insert will generate an action via collection.AddBookSuccessAction(book) of type Observable<Action>. The map of this.db.insert returns that to the mergeMap and the mergeMap returns a first order Observable<Action>.

What's wrong with the Modified Code? The modified code uses only map which returns a high order observable of type Observable<Observable<AddBookSuccessAction>>>. This is not of the correct type of effect addBookToCollection$ which should be of type Observable<Action>.

Body:
The following example is taken from the @ngrx example.

I understand this observable this way. The first map function gets the payload which is the book to be added, again processed by the mergeMap where it saves to the database.

Original Code:

  @Effect()
  addBookToCollection$: Observable<Action> = this.actions$
    .ofType(collection.ActionTypes.ADD_BOOK)
    .map((action: collection.AddBookAction) => action.payload)
    .mergeMap(book =>
      this.db.insert('books', [ book ])
        .map(() => new collection.AddBookSuccessAction(book))
        .catch(() => of(new collection.AddBookFailAction(book)))
    );

Can the below code do the same thing as the above? Why there is a mergeMap required?

Modified Code:

@Effect()
  addBookToCollection$: Observable<Action> = this.actions$
    .ofType(collection.ActionTypes.ADD_BOOK)
    .map((action: collection.AddBookAction) =>
      this.db.insert('books', [ action.payload ])
        .map(() => new collection.AddBookSuccessAction(action.payload))
        .catch(() => of(new collection.AddBookFailAction(action.payload)))
    );


问:
unhighlight the row background when another row is clicked
I am using jQuery-contextMenu. I am trying to highlight the row background on left or right click.

```<code>$('body').on('mousedown', 'tr', function() {
   $(this).css('backgroundColor', '#000');
});
</code>```

Somehow the contextMenu is making it unstable. Could you please suggest me how can I triger the background Color before contextMenu?
PLease see the jsfiddle below to have a better idea. I also need to unhighlight the previous row background when another row is clicked.

http://jsfiddle.net/0f9Ljfjr/904/

答:
If you only want to have one row with a background color at any given time, it's not that the jQuery plugin is messing your code. It's just that you never "unpaint" it. This is how I'd do it:

```<code>var highlighted;
$('body').on('mousedown', 'tr', function() {
    if(highlighted) highlighted.css('backgroundColor', 'white');
  $(this).css('backgroundColor', 'lightseagreen');
  highlighted = $(this);
});
</code>```

You store the element that's highlighted and you change it back everytime you paint some other row.

I've updated your jsfiddle: http://jsfiddle.net/0f9Ljfjr/909/

Body:
I am using jQuery-contextMenu. I am trying to highlight the row background on left or right click.

$('body').on('mousedown', 'tr', function() {
   $(this).css('backgroundColor', '#000');
});

Somehow the contextMenu is making it unstable. Could you please suggest me how can I triger the background Color before contextMenu?
PLease see the jsfiddle below to have a better idea. I also need to unhighlight the previous row background when another row is clicked.

http://jsfiddle.net/0f9Ljfjr/904/

Body:
If you only want to have one row with a background color at any given time, it's not that the jQuery plugin is messing your code. It's just that you never "unpaint" it. This is how I'd do it:

var highlighted;
$('body').on('mousedown', 'tr', function() {
    if(highlighted) highlighted.css('backgroundColor', 'white');
  $(this).css('backgroundColor', 'lightseagreen');
  highlighted = $(this);
});

You store the element that's highlighted and you change it back everytime you paint some other row.

I've updated your jsfiddle: http://jsfiddle.net/0f9Ljfjr/909/


问:
Making multiple coloured line segment in Python according to a list of integers coding for a specific color
I want to make a line segment with multiple colours according to the input of colour codes given as the list of integers. For example, suppose there is a list of integers n and tuple containing colour code

```<code>n= [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]

codes=([1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Blue'])
</code>```

Then, I want a line segment which is made up of multiple colours according to the colour codes in the sequence of the given integers. Please find this image for reference

The given image has input sequence length of about 100 integers and corresponding colour codes. How can something like this be constructed?

答:
A good solution for this sort of thing in python is the PIL library:

Code:

```<code>from PIL import Image, ImageDraw

def colored_bar(data, colors, height=10, width=5):
    # Create a blank image
    im = Image.new('RGBA', (width * len(data), height), (0, 0, 0, 0))

    # Create a draw object
    draw = ImageDraw.Draw(im)

    for i, val in enumerate(data):
        draw.rectangle((i * width, 0, (i+1) * width, height),
                       fill=colors[val])
    return im
</code>```

Test Code:

```<code>n = [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]
codes = dict(([1, 'red'], [2, 'yellow'], [3, 'green'], [4, 'blue']))

image = colored_bar(n, codes)
image.show()
</code>```

Results:

Body:
I want to make a line segment with multiple colours according to the input of colour codes given as the list of integers. For example, suppose there is a list of integers n and tuple containing colour code

n= [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]

codes=([1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Blue'])

Then, I want a line segment which is made up of multiple colours according to the colour codes in the sequence of the given integers. Please find this image for reference

The given image has input sequence length of about 100 integers and corresponding colour codes. How can something like this be constructed?

Body:
A good solution for this sort of thing in python is the PIL library:

Code:

from PIL import Image, ImageDraw

def colored_bar(data, colors, height=10, width=5):
    # Create a blank image
    im = Image.new('RGBA', (width * len(data), height), (0, 0, 0, 0))

    # Create a draw object
    draw = ImageDraw.Draw(im)

    for i, val in enumerate(data):
        draw.rectangle((i * width, 0, (i+1) * width, height),
                       fill=colors[val])
    return im

Test Code:

n = [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]
codes = dict(([1, 'red'], [2, 'yellow'], [3, 'green'], [4, 'blue']))

image = colored_bar(n, codes)
image.show()

Results:


问:
When does PHP's opcache re-parse a file?
Just what the subject says - when does PHP's opcache re-parse a file? Is it based on file timestamp, or file hash or what?

Edit: If my question is not clear then I'll try again:) Say a file "xyz.php" is already in OPCache. Now I modify the file - and it obviously has to be parsed again and updated in the cache. How PHP knows it should do it?

答:
It is based on your opcache configuration in your php.ini file.

opcache.revalidate_freq - Basically put, how often (in seconds) should the code cache expire and check if your code has changed. 0 means it checks your PHP code every single request (which adds lots of stat syscalls). Set it to 0 in your development environment. Production doesn't matter because of the next setting.

opcache.validate_timestamps - When this is enabled, PHP will check the file timestamp per your opcache.revalidate_freq value.

When it's disabled, opcache.revaliate_freq is ignored and PHP files are NEVER checked for updated code. So, if you modify your code, the changes won't actually run until you restart or reload PHP.


问:
VSix deployment fails- Is VS SDK required on target machine?
I have a vsix package that has been built and installed on my machine and works well.   I tried a double click install on a machine that does not have the VS Sdk.  When I click on the icon in the View-OtherWindow I get an error that says "exception has been thrown by the target of the invocation".     Any thoughts?</p>

答:
The VS SDK is not required on the target machine to deploy a VSIX.  It is possible that you are relying on DLL's from the SDK which need to be deployed with the VSIX.  That's just idle speculation though because the exception message is very vague. </p>

<p>The best way to tackle this problem is to hook up a debugger on the target machine and see what the root cause exception is.  Knowing that will help us track down this issue. </p>

Body:
The VS SDK is not required on the target machine to deploy a VSIX.  It is possible that you are relying on DLL's from the SDK which need to be deployed with the VSIX.  That's just idle speculation though because the exception message is very vague.

The best way to tackle this problem is to hook up a debugger on the target machine and see what the root cause exception is.  Knowing that will help us track down this issue.


问:
Is there any differences between this two ways of looping and which one is preferable to be used?
I was coding under netbeans 8.1 I was using a for loop and I was curious to see what will the IDE suggest as code formating, so my original loop was :

```<code>    List<Produit> produits = pjc.findProduitEntities();
    for (Produit produit : produits) {
        System.out.println("p ="+produit.getTitre());
        observableArrayList.add(new FXProduit(produit));
    }
</code>```

I got finally two suggestion that I want to understand if they are the same or there is some performance or memory management differences.

the first suggestion was named use functional operation based on lambda expression:

```<code>    List<Produit> produits = pjc.findProduitEntities();
    produits.stream().map((produit) -> {
        System.out.println("p ="+produit.getTitre());
        return produit;
    }).forEach((produit) -> {
        observableArrayList.add(new FXProduit(produit));
    });
</code>```

the second one uses the inner class paradigm

```<code>    List<Produit> produits = pjc.findProduitEntities();
    produits.stream().map(new Function<Produit, Produit>() {
        @Override
        public Produit apply(Produit produit) {
            System.out.println("p ="+produit.getTitre());
            return produit;
        }
    }).forEach((produit) -> {
        observableArrayList.add(new FXProduit(produit));
    });
</code>```

答:
The anonymous class version is the least attractive, because it creates a new class and new instances with every invocation that require garbage collection.

The stream version can be cleaned up and improved considerably using peek(), parallel stream and method references:

```<code>pjc.findProduitEntities().parallelStream()
    .peek(produit -> System.out.println("p ="+produit.getTitre()))
    .map(FXProduit::new)
    .forEach(observableArrayList::add);
</code>```

I have assumed that parallel processing is OK, since the objects end up in an observable context, in which order makes no difference. Even without the parallel stream (ie just using .stream()) the code is still a lot cleaner.

Body:
I was coding under netbeans 8.1 I was using a for loop and I was curious to see what will the IDE suggest as code formating, so my original loop was :

    List<Produit> produits = pjc.findProduitEntities();
    for (Produit produit : produits) {
        System.out.println("p ="+produit.getTitre());
        observableArrayList.add(new FXProduit(produit));
    }

I got finally two suggestion that I want to understand if they are the same or there is some performance or memory management differences.

the first suggestion was named use functional operation based on lambda expression:

    List<Produit> produits = pjc.findProduitEntities();
    produits.stream().map((produit) -> {
        System.out.println("p ="+produit.getTitre());
        return produit;
    }).forEach((produit) -> {
        observableArrayList.add(new FXProduit(produit));
    });

the second one uses the inner class paradigm

    List<Produit> produits = pjc.findProduitEntities();
    produits.stream().map(new Function<Produit, Produit>() {
        @Override
        public Produit apply(Produit produit) {
            System.out.println("p ="+produit.getTitre());
            return produit;
        }
    }).forEach((produit) -> {
        observableArrayList.add(new FXProduit(produit));
    });

Body:
The anonymous class version is the least attractive, because it creates a new class and new instances with every invocation that require garbage collection.

The stream version can be cleaned up and improved considerably using peek(), parallel stream and method references:

pjc.findProduitEntities().parallelStream()
    .peek(produit -> System.out.println("p ="+produit.getTitre()))
    .map(FXProduit::new)
    .forEach(observableArrayList::add);

I have assumed that parallel processing is OK, since the objects end up in an observable context, in which order makes no difference. Even without the parallel stream (ie just using .stream()) the code is still a lot cleaner.


问:
Circleci tests passing but then sitting there until timing out
I'm running Jasmine tests which are passing, but then nothing happens until eventual timeout. What am I missing?</p>

```<code>PhantomJS 2.1.1 (Linux 0.0.0): Executed 49 of 61 SUCCESS (0 secs / 0.539 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 50 of 61 SUCCESS (0 secs / 0.542 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 51 of 61 SUCCESS (0 secs / 0.546 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 52 of 61 SUCCESS (0 secs / 0.549 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 53 of 61 SUCCESS (0 secs / 0.553 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 54 of 61 SUCCESS (0 secs / 0.562 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 55 of 61 SUCCESS (0 secs / 0.567 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 56 of 61 SUCCESS (0 secs / 0.573 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 57 of 61 SUCCESS (0 secs / 0.575 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 58 of 61 SUCCESS (0 secs / 0.583 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 59 of 61 SUCCESS (0 secs / 0.588 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 60 of 61 SUCCESS (0 secs / 0.593 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 61 of 61 SUCCESS (0 secs / 0.621 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 61 of 61 SUCCESS (0.446 secs / 0.621 secs)

command ((npm :test)) took more than 10 minutes since last output
</code>```

答:
```<code>// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
</code>```

Set singleRun to true in your karma config file. This would return 1 or 0 depending on if the test passed or failed when it ended as opposed to watching for changes infinitely in the spec file.

Body:
I'm running Jasmine tests which are passing, but then nothing happens until eventual timeout. What am I missing?

PhantomJS 2.1.1 (Linux 0.0.0): Executed 49 of 61 SUCCESS (0 secs / 0.539 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 50 of 61 SUCCESS (0 secs / 0.542 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 51 of 61 SUCCESS (0 secs / 0.546 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 52 of 61 SUCCESS (0 secs / 0.549 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 53 of 61 SUCCESS (0 secs / 0.553 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 54 of 61 SUCCESS (0 secs / 0.562 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 55 of 61 SUCCESS (0 secs / 0.567 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 56 of 61 SUCCESS (0 secs / 0.573 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 57 of 61 SUCCESS (0 secs / 0.575 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 58 of 61 SUCCESS (0 secs / 0.583 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 59 of 61 SUCCESS (0 secs / 0.588 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 60 of 61 SUCCESS (0 secs / 0.593 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 61 of 61 SUCCESS (0 secs / 0.621 secs)
PhantomJS 2.1.1 (Linux 0.0.0): Executed 61 of 61 SUCCESS (0.446 secs / 0.621 secs)

command ((npm :test)) took more than 10 minutes since last output

Body:
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,

Set singleRun to true in your karma config file. This would return 1 or 0 depending on if the test passed or failed when it ended as opposed to watching for changes infinitely in the spec file.


问:
Append Date Created stamp to filename
I'm trying to create a bash script that will run on a folder and check the last modified stamp for each file in that folder then append that date to each file in the folder as it goes through them. For example:

IMG1_movie.mov

becomes

IMG1_movie_02032015.mov

There are a few examples online but the ones I've found don't cover the last modified date only appending the current date and none have batch capabilities. Any guidance is appreciated thanks.

答:
You could write that part of the code as

```<code>new_filename="$(date -r $filename +%Y%m%d)"
</code>```

where the date command arguments does the formatting for you. I made the format as YYYYMMDD. You could change the arguments to the order in which you want the date to appear.

Title: Append Date Created stamp to filename

Body:
You could write that part of the code as

new_filename="$(date -r $filename +%Y%m%d)"

where the date command arguments does the formatting for you. I made the format as YYYYMMDD. You could change the arguments to the order in which you want the date to appear.


问:
How to get both the word embeddings vector and context vector of a given word by using word2vec?
```<code>from gensim.models import word2vec

sentences = word2vec.Text8Corpus('TextFile')
model = word2vec.Word2Vec(sentences, size=200, min_count = 2, workers = 4)
print model['king']
</code>```

Is the output vector the context vector of 'king' or the word embedding vector of 'king'? How can I get both context vector of 'king' and the word embedding vector of 'king'? Thanks!

答:
'Context vector' is also a 'word embedding' vector. Word embedding means how vocabulary are mapped to vectors of real numbers.

I assume you meant center word's vector when you said 'word embedding' vector.

In word2vec algorithm, when you train the model, it creates two different vectors for one word (when 'king' is used for center word and when it's used for context words.)

I don't know about how gensim is treating these two vectors, but normally, people average both context and center words, or concatinate two vectors. It might not be the most beautiful way to treat the vectors, but it works very well that way.

So when you call model['king'] on some pre-trained vector, the vector you see is probably the averaged version of two vectors.

Body:
from gensim.models import word2vec

sentences = word2vec.Text8Corpus('TextFile')
model = word2vec.Word2Vec(sentences, size=200, min_count = 2, workers = 4)
print model['king']

Is the output vector the context vector of 'king' or the word embedding vector of 'king'? How can I get both context vector of 'king' and the word embedding vector of 'king'? Thanks!


问:
ruby uniq on the first two columns of two dimensional array
I have a two dimensional array with three fields in the second dimension.

Is it possible to use uniq on the first two fields of the second dimension?

I have seen array.uniq! {|c| c.first}. When I am correct, this apply uniq on the first field of the array.

Is it possible to use something like array.uniq! {|c| c.first c.second}?

@array = Array.new()

@array << Array.new([journal.from_account_number, journal.from_account,
                                journal.buchungsart])
There are several entries in @array.

The question was how to get unique values from array not considering journal.buchungsart.

The answer was: @array = @array.uniq! {|c| [c.first, c.second]}

答:
Yes, put the values in an array:</p>

```<code>array.uniq! {|c| [c.first, c.second]}
</code>```

Body:
Yes, put the values in an array:

array.uniq! {|c| [c.first, c.second]}


问:
Is there a way to get the React / Redux's bundle.js on the local hard drive?
When the Reach / Redux app is finally running, there is a file bindle.js, but if I use

```<code>find . -name '*bundle.js*' | xargs ls -l
</code>```

all the bundle.js files in the repo are not the one that was just built (meaning, those are older files and do not have a current timestamp if I just edited my project 10 seconds ago).

Is the only way to get this file from http://localhost:8080/bundle.js ? This file should have been made and sit inside the hard drive, and I think the server doesn't make it every time when the browser requests it.

答:
One more option if you are using a more recent version of React:

I found that the latest React, it will tell you to use

```<code>create-react-app hello-world
</code>```

to create the app, and then there is an official

```<code>npm run build
</code>```

to build it to host it as a Gthub page, or on your own website.  The bundle.js will then be inside the build/static/js directory. (with a different filename such as main.54f24123.js that seems to be used for busting the cache).

Body:
When the Reach / Redux app is finally running, there is a file bindle.js, but if I use

find . -name '*bundle.js*' | xargs ls -l

all the bundle.js files in the repo are not the one that was just built (meaning, those are older files and do not have a current timestamp if I just edited my project 10 seconds ago).

Is the only way to get this file from http://localhost:8080/bundle.js ? This file should have been made and sit inside the hard drive, and I think the server doesn't make it every time when the browser requests it.

Body:
One more option if you are using a more recent version of React:

I found that the latest React, it will tell you to use

create-react-app hello-world

to create the app, and then there is an official

npm run build

to build it to host it as a Gthub page, or on your own website.  The bundle.js will then be inside the build/static/js directory. (with a different filename such as main.54f24123.js that seems to be used for busting the cache).


问:
JSON.NET JsonConvert vs .NET JavaScriptSerializer
What is better to use when it comes to encoding and decoding of JSON in .NET? I have tried both and upto this point JsonConvert seems to be doing a good job. I have used JavaScriptSerializer in the past successfully but have had some problems in the recent past with it. Is it better to use JSON.NET than the .NET class?

What are the preferred functions for encoding/decoding json using the appropriate library? I use SerializeObject/DeSerializeObject from JSON.NET and Serialize/DeSerialize from .NET.

Thanks

答:
For a very long time, my app used JavascriptSerializer and saw no real reason to migrate. Even if performance comparisons claim huge percentage gains, we're talking milliseconds.

But here's one very very good reason to migrate: JavascriptSerializer isn't available in .Net Core because it's part of System.Web So if you're using JavascriptSerializer, you're stuck and have to migrate to JSON.net


问:
NSWindow maximized?
does anybody know a correct solution for this code?</p>

```<code>BOOL maximized = [myWindow isMaximized];
</code>```

答: Maybe take a look at isZoomed

Title: NSWindow maximized?

Body:
does anybody know a correct solution for this code?

BOOL maximized = [myWindow isMaximized];

Body: Maybe take a look at isZoomed


问:
High Score not Working in unity
I have a high score script in my game. I use the same code in my other game and it works but in this game it gives me an error :

input string was not in the correct format

this is my code :

```<code>private Rigidbody2D Rigid;
public float Speed;
public float Power;
public GameObject Panel;
public Text ScorePoint;
private int Point = 0;
public Text HighScorePoint;

void Start()
{
    Rigid = GetComponent<Rigidbody2D> ();
    Panel.SetActive (false);
    HighScorePoint.text = PlayerPrefs.GetString ("Scores");
}

void Update()
{
    transform.Translate (Vector2.right * Speed * Time.deltaTime);

    foreach (Touch touch in Input.touches)
    {
        if (touch.phase == TouchPhase.Began)
        {
            Rigid.AddForce (Vector2.up * Power * Time.deltaTime);
        }
    }

// !!!!!!!!!!!!!!!!!! this is were it gives me an error !!!!!!!!!!!!!!!!!

    **if (int.Parse(ScorePoint.text) > int.Parse(HighScorePoint.text))**
    {
        PlayerPrefs.SetString ("Scores", ScorePoint.text);
        PlayerPrefs.Save ();
    }
}

void OnCollisionEnter2D(Collision2D Col)
{
    if (Col.gameObject.tag == "Pipe")
    {
        Panel.SetActive (true);
        Time.timeScale = 0;
    }
}

void OnTriggerEnter2D(Collider2D Col)
{
    if (Col.gameObject.tag == "ScoreCollider")
    {
        Point++;
        ScorePoint.text = Point.ToString ();
    }
}
</code>```

I have this code in my other game and it works correctly :

```<code>public float Speed;
private Rigidbody2D Rigid;
public float JumpPower;
public Text ScorePoint;
private int Point = 0;
public Text HighScorePoint;
public AudioSource CoinCollect;
public AudioSource Jump;
public AudioSource Laugh;
public AudioSource Scream;
private AudioSource[] Audios;

void Start()
{
    DontDestroyOnLoad (Scream);
    Audios = GetComponents<AudioSource> ();
    CoinCollect = Audios [0];
    Jump = Audios [1];
    Laugh = Audios [2];
    Scream = Audios [3];
    Rigid = GetComponent<Rigidbody2D> ();
    ScorePoint = GameObject.FindGameObjectWithTag ("ScorePoint").GetComponent<Text> ();
    HighScorePoint = GameObject.FindGameObjectWithTag ("HighScorePoint").GetComponent<Text> ();
    HighScorePoint.text = PlayerPrefs.GetString ("Scores");
}

void Update()
{
    transform.Translate (Vector2.right * Speed * Time.deltaTime);
    if (transform.position.y < -2.1)
    {
        foreach (Touch touch in Input.touches)
        {
            Rigid.AddForce (Vector2.up * JumpPower * Time.deltaTime);
            Jump.Play ();
        }
    }

    if (int.Parse(ScorePoint.text) > int.Parse(HighScorePoint.text))
    {
        PlayerPrefs.SetString ("Scores", ScorePoint.text);
        PlayerPrefs.Save ();
    }
}

void OnCollisionEnter2D(Collision2D Col)
{
    if (Col.gameObject.tag == "Enemies")
    {
        SceneManager.LoadScene ("CharacterSelection");
        Scream.Play ();
    }

    if (Col.gameObject.tag == "Coins")
    {
        Point++;
        ScorePoint.text = Point.ToString ();
        Destroy (Col.gameObject);
        CoinCollect.Play ();
    }

    if (Col.gameObject.tag == "Girls")
    {
        Point += 10;
        ScorePoint.text = Point.ToString ();
        Destroy (Col.gameObject);
        Laugh.Play ();
    }
}
</code>```

答:
Make sure that HighScorePoint.text is not null or empty before calling int.Parse.

```<code>if (!String.IsNullOrEmpty(ScorePoint.text) && !String.IsNullOrEmpty(HighScorePoint.text))
{
    if (int.Parse(ScorePoint.text) > int.Parse(HighScorePoint.text))
    {
        PlayerPrefs.SetString("Scores", ScorePoint.text);
        PlayerPrefs.Save();
    }
}
</code>```

You can also use TryParse and avoid such error.

```<code>int tempScorePoint = 0;
int tempHighScorePoint = 0;

int.TryParse(ScorePoint.text, out tempScorePoint);
int.TryParse(HighScorePoint.text, out tempHighScorePoint);

if (int.TryParse(ScorePoint.text, out tempScorePoint) &&
    int.TryParse(HighScorePoint.text, out tempHighScorePoint))
{

    if (tempScorePoint > tempHighScorePoint)
    {
        PlayerPrefs.SetString("Scores", ScorePoint.text);
        PlayerPrefs.Save();
    }
}
</code>```

You can easily find out which Text component is null by inserting Debug.Log before that code that is causing the error.

```<code>Debug.Log(ScorePoint.text);
Debug.Log(HighScorePoint.text);
</code>```

Title: High Score not Working in unity

Body:
I have a high score script in my game. I use the same code in my other game and it works but in this game it gives me an error :

input string was not in the correct format

this is my code :

private Rigidbody2D Rigid;
public float Speed;
public float Power;
public GameObject Panel;
public Text ScorePoint;
private int Point = 0;
public Text HighScorePoint;

void Start()
{
    Rigid = GetComponent<Rigidbody2D> ();
    Panel.SetActive (false);
    HighScorePoint.text = PlayerPrefs.GetString ("Scores");
}

void Update()
{
    transform.Translate (Vector2.right * Speed * Time.deltaTime);

    foreach (Touch touch in Input.touches)
    {
        if (touch.phase == TouchPhase.Began)
        {
            Rigid.AddForce (Vector2.up * Power * Time.deltaTime);
        }
    }

// !!!!!!!!!!!!!!!!!! this is were it gives me an error !!!!!!!!!!!!!!!!!

    **if (int.Parse(ScorePoint.text) > int.Parse(HighScorePoint.text))**
    {
        PlayerPrefs.SetString ("Scores", ScorePoint.text);
        PlayerPrefs.Save ();
    }
}

void OnCollisionEnter2D(Collision2D Col)
{
    if (Col.gameObject.tag == "Pipe")
    {
        Panel.SetActive (true);
        Time.timeScale = 0;
    }
}

void OnTriggerEnter2D(Collider2D Col)
{
    if (Col.gameObject.tag == "ScoreCollider")
    {
        Point++;
        ScorePoint.text = Point.ToString ();
    }
}

I have this code in my other game and it works correctly :

public float Speed;
private Rigidbody2D Rigid;
public float JumpPower;
public Text ScorePoint;
private int Point = 0;
public Text HighScorePoint;
public AudioSource CoinCollect;
public AudioSource Jump;
public AudioSource Laugh;
public AudioSource Scream;
private AudioSource[] Audios;

void Start()
{
    DontDestroyOnLoad (Scream);
    Audios = GetComponents<AudioSource> ();
    CoinCollect = Audios [0];
    Jump = Audios [1];
    Laugh = Audios [2];
    Scream = Audios [3];
    Rigid = GetComponent<Rigidbody2D> ();
    ScorePoint = GameObject.FindGameObjectWithTag ("ScorePoint").GetComponent<Text> ();
    HighScorePoint = GameObject.FindGameObjectWithTag ("HighScorePoint").GetComponent<Text> ();
    HighScorePoint.text = PlayerPrefs.GetString ("Scores");
}

void Update()
{
    transform.Translate (Vector2.right * Speed * Time.deltaTime);
    if (transform.position.y < -2.1)
    {
        foreach (Touch touch in Input.touches)
        {
            Rigid.AddForce (Vector2.up * JumpPower * Time.deltaTime);
            Jump.Play ();
        }
    }

    if (int.Parse(ScorePoint.text) > int.Parse(HighScorePoint.text))
    {
        PlayerPrefs.SetString ("Scores", ScorePoint.text);
        PlayerPrefs.Save ();
    }
}

void OnCollisionEnter2D(Collision2D Col)
{
    if (Col.gameObject.tag == "Enemies")
    {
        SceneManager.LoadScene ("CharacterSelection");
        Scream.Play ();
    }

    if (Col.gameObject.tag == "Coins")
    {
        Point++;
        ScorePoint.text = Point.ToString ();
        Destroy (Col.gameObject);
        CoinCollect.Play ();
    }

    if (Col.gameObject.tag == "Girls")
    {
        Point += 10;
        ScorePoint.text = Point.ToString ();
        Destroy (Col.gameObject);
        Laugh.Play ();
    }
}

Body:
Make sure that HighScorePoint.text is not null or empty before calling int.Parse.

if (!String.IsNullOrEmpty(ScorePoint.text) && !String.IsNullOrEmpty(HighScorePoint.text))
{
    if (int.Parse(ScorePoint.text) > int.Parse(HighScorePoint.text))
    {
        PlayerPrefs.SetString("Scores", ScorePoint.text);
        PlayerPrefs.Save();
    }
}

You can also use TryParse and avoid such error.

int tempScorePoint = 0;
int tempHighScorePoint = 0;

int.TryParse(ScorePoint.text, out tempScorePoint);
int.TryParse(HighScorePoint.text, out tempHighScorePoint);

if (int.TryParse(ScorePoint.text, out tempScorePoint) &&
    int.TryParse(HighScorePoint.text, out tempHighScorePoint))
{

    if (tempScorePoint > tempHighScorePoint)
    {
        PlayerPrefs.SetString("Scores", ScorePoint.text);
        PlayerPrefs.Save();
    }
}

You can easily find out which Text component is null by inserting Debug.Log before that code that is causing the error.

Debug.Log(ScorePoint.text);
Debug.Log(HighScorePoint.text);


问:
When to call notify in RecyclerView.Adapter?
Will notify* methods in RecyclerView.Adapter run view's callbacks in UI thread automagically or have I to explicitly switch from my job's thread?

答: If you want to update your  RecyclerView.Adapter you should call method notify in UI thread.</p>


问:
Insert additional fields in JAXB marshalling
When marshaling some objects into XML, I need to insert an additional field in each of the resulting XML objects - sort of flag. The purpose is not modifying the source objects but inserting that information in the output XML.

Any ideas if this is possible?

答:
There are a few possible approaches:

1.  Use an XmlAdapter

You could leverage JAXB's XmlAdapter.  Here you would create a version of the classes with the extra field (the adapted classes could extend the original).  Then convert between them in the adapter.  Since the alternate version of the class would contain the extra field it would marshal out.

http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html

2.  Use Binder

If you marshal target is DOM, then you could leverage JAXB's Binder.  It is intended for infoset preservation, but after a marshal it does maintain a link between the objects and the DOM nodes.  Once the marshal is complete you could use the binder to find an object's associated node and update it.

http://bdoughan.blogspot.com/2010/09/jaxb-xml-infoset-preservation.html

3.  Wrap the Output Target

If your output target is something like a ContentHandler or XMLStreamWriter then when the appropriate state is reached you could trigger additional events to be called on the nested marshal target.


问:
<select> containing time from specific start hour into end another specific hour
i need your help in this problem,

i have this empty dropdownlist:

echo"<select id='time' class='form-control'>";

echo"</select>";```

i have for example 2 hours: 8:30 and 12:30, i want to fill it by using PHP, with time from 8:30 into 12 just like this:

8:30

9

9:30

10

10:30

11

11:30

12

答:
You can use DateTime class.</p>

```<code>$date = new DateTime();
$date->setTime(8, 0);
$h = 8;
while($h <= 12){
   $date->add(date_interval_create_from_date_string('30 minutes'));
   echo '<option>' . $date->format("H:i") . '</option>';
   $h = (int)$date->format("H");
}
</code>```

Body:
i need your help in this problem,

i have this empty dropdownlist:

echo"<select id='time' class='form-control'>";

echo"</select>";

i have for example 2 hours: 8:30 and 12:30, i want to fill it by using PHP, with time from 8:30 into 12 just like this:

8:30

9

9:30

10

10:30

11

11:30

12

Body:
You can use DateTime class.

$date = new DateTime();
$date->setTime(8, 0);
$h = 8;
while($h <= 12){
   $date->add(date_interval_create_from_date_string('30 minutes'));
   echo '<option>' . $date->format("H:i") . '</option>';
   $h = (int)$date->format("H");
}


问:
Trying to install Magento, get error msgs about PHP version & extensions
I've downloaded and installed XAMPP.

Now I'm trying to install Magento on my Windows10 laptop.
The problem is, Magento Installer is giving me this error,

So I downloaded and extracted PHP 7.0.6. But I don't know how to install it.

Another problem is about the extension as shown in the picture below,

How to solve these problems, please help. Thank you.

答:
Step 1 : Open your xampp control

Step 2 : Click config open php.ini or (install xampp location xampp\php\php.ini)

Step 3 : rename ;extension=php_xsl.dll to extension=php_xsl.dll

Step 4 : rename ;extension=php_intl.dll to extension=php_intl.dll


问:
Trying to get a worksheet names from an excel with LinqToExcel
I trying to load worksheet names from an excel using LinqToExcel.

using the following line of code

excelQueryFactory.GetWorksheetNames();

The worksheet names are ["$2,00","$5.00"].

but load ["2,00" , "5,00"]. The $ sign is missing.

What i do wrong? . How could i load the sush as they are?

Thank you.

答: I was having a similar issue and looking a bit at the code I found that the function "GetWorksheetNames()" replaces some symbols including "$". You can see it here</p>


问:
how to add many selected items from checkboxes to listbox at same time in vb.net
I want to be able to add many selected items from a checkbox to a listbox at the same time. This is a sample of the code

```<code>If CheckBox1.Checked Then
choice = "Potato soup"
quantity = Val(txtapp1.Text)
price = "80"
If CheckBox2.Checked Then
choice = "Mini tacos"
quantity = Val(txtapp2.Text)
price = "95"
</code>```

I want to be able to add choice, quantity, and price for each checkbox to the listbox at the same time.

答:
Assuming that your listbox is named ListBoxChoices, the code would be following:</p>

```<code>If CheckBox1.Checked Then
choice = "Potato soup"
quantity = Val(txtapp1.Text)
price = "80"
ListBoxChoices.Items.Add(choice)
ListBoxChoices.Items.Add(quantity)
ListBoxChoices.Items.Add(price)
End If
If CheckBox2.Checked Then
choice = "Mini tacos"
quantity = Val(txtapp2.Text)
price = "95"
ListBoxChoices.Items.Add(choice)
ListBoxChoices.Items.Add(quantity)
ListBoxChoices.Items.Add(price)
End If
</code>```

Body:
I want to be able to add many selected items from a checkbox to a listbox at the same time. This is a sample of the code

If CheckBox1.Checked Then
choice = "Potato soup"
quantity = Val(txtapp1.Text)
price = "80"
If CheckBox2.Checked Then
choice = "Mini tacos"
quantity = Val(txtapp2.Text)
price = "95"

I want to be able to add choice, quantity, and price for each checkbox to the listbox at the same time.

Body:
Assuming that your listbox is named ListBoxChoices, the code would be following:

If CheckBox1.Checked Then
choice = "Potato soup"
quantity = Val(txtapp1.Text)
price = "80"
ListBoxChoices.Items.Add(choice)
ListBoxChoices.Items.Add(quantity)
ListBoxChoices.Items.Add(price)
End If
If CheckBox2.Checked Then
choice = "Mini tacos"
quantity = Val(txtapp2.Text)
price = "95"
ListBoxChoices.Items.Add(choice)
ListBoxChoices.Items.Add(quantity)
ListBoxChoices.Items.Add(price)
End If


问:
loading photos and details of a place using google places api
I am displaying image of a place  along with its details using image view and text view which works fine ,when i select a place which has image,but when i select a place with no image my app crashes. If there is no image then i want to only display the details of place but it doesnt....Help would be appreciated .

here is my activity

```<code>package com.example.dell.Swing;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
 import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.os.Build;
    import android.support.annotation.NonNull;
    import android.support.v4.app.ActivityCompat;
    import android.util.Log;
    import android.view.View;
    import android.webkit.WebView;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
    import com.google.android.gms.common.GooglePlayServicesRepairableException;
    import com.google.android.gms.location.places.Place;
    import com.google.android.gms.location.places.PlacePhotoMetadata;
    import com.google.android.gms.location.places.PlacePhotoMetadataBuffer;
    import com.google.android.gms.location.places.PlacePhotoMetadataResult;
    import com.google.android.gms.location.places.Places;
     import com.google.android.gms.location.places.ui.PlacePicker;
    import com.uber.sdk.android.core.UberSdk;
    import com.uber.sdk.android.rides.RideParameters;
    import com.uber.sdk.android.rides.RideRequestButton;
    import com.uber.sdk.core.auth.Scope;
    import com.uber.sdk.rides.client.SessionConfiguration;
    import com.squareup.picasso.Picasso;

import java.util.Random;

    public class aarakuhotels extends AppCompatActivity {
private GoogleApiClient mGoogleApiClient;
RideRequestButton requestButton;
TextView placeNameText;
   ImageView image;
TextView placeAddressText,placeemailtext,placelocaletext,placephonetext;
WebView attributionText;
Button getPlaceButton;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
private final static int PLACE_PICKER_REQUEST = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_aarakuhotels);
    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, new OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                }
            })
            .build();

    requestPermission();
    SessionConfiguration config = new SessionConfiguration.Builder()
            .setClientId("wd9fPCpvtObmPOHBogaVdicLZW5Cos1K") //This is necessary
            .setRedirectUri("YOUR_REDIRECT_URI") //This is necessary if you'll be using implicit grant
            .build();
</code>```

//This is a convenience method and will set the default config to be used in other components without passing it directly.

```<code>      UberSdk.initialize(config);

    placeNameText = (TextView) findViewById(R.id.hotelname);
    placeAddressText = (TextView) findViewById(R.id.hoteladdress);
    placeemailtext =(TextView) findViewById(R.id.email);
    placelocaletext =(TextView) findViewById(R.id.locale);
    placephonetext =(TextView) findViewById(R.id.phone);
    image =(ImageView) findViewById(R.id.hotelsimage);
   // attributionText = (WebView) findViewById(R.id.attribution);
    getPlaceButton = (Button) findViewById(R.id.gethotels);
    getPlaceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
            try {
                Intent intent = builder.build(aarakuhotels.this);
                startActivityForResult(intent, PLACE_PICKER_REQUEST);
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }

        }
    });
}

private void requestPermission() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case MY_PERMISSION_FINE_LOCATION:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "This app requires location permissions to be granted", Toast.LENGTH_LONG).show();
                finish();
            }
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PLACE_PICKER_REQUEST){
        if (resultCode == RESULT_OK){

            Place place = PlacePicker.getPlace(aarakuhotels.this, data);
            //Log.d("TAG",data.toString()); wait check karru ok
            Log.d("TAG",place.toString());
            final String placeId = place.getId();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    PlacePhotoMetadataResult result = Places.GeoDataApi
                            .getPlacePhotos(mGoogleApiClient, placeId).await();

                    if (result != null && result.getStatus().isSuccess()) {
                        PlacePhotoMetadataBuffer photoMetadataBuffer = result.getPhotoMetadata();

                //getting error here when i select a place with no photo and app crashes  --> PlacePhotoMetadata photo = photoMetadataBuffer.get(0);

                        final Bitmap locationimg = photo.getPhoto(mGoogleApiClient).await()
                                .getBitmap();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                image.setImageBitmap(locationimg);
                            }
                        });

                    }
                }
            }).start();

           // Picasso.with(this).load("https://lh5.googleusercontent.com/-_jVRD4o6K20/VrAgjefDtCI/AAAAAAABoTw/TH6pNjEcU-MelyMU8ZzLikO1HVpMyHDPQCJkC/s544-k-no/").into(image);
            placeNameText.setText("Name:"+place.getName());
            placephonetext.setText("Phone:"+place.getPhoneNumber());
            placeemailtext.setText("Website:"+place.getWebsiteUri());
            placelocaletext.setText("Rating:"+place.getRating());
            placeAddressText.setText("Address:"+place.getAddress());
           // if (place.getAttributions() == null) {
             //   attributionText.loadData("no attribution", "text/html; charset=utf-8", "UFT-8");
            //} else {
              //  attributionText.loadData(place.getAttributions().toString(), "text/html; charset=utf-8", "UFT-8");
            //}
        }
    }
}
 }
</code>```

答: Found the Problem I replaced Threads with normal code...Worked</p>

Body:
I am displaying image of a place  along with its details using image view and text view which works fine ,when i select a place which has image,but when i select a place with no image my app crashes. If there is no image then i want to only display the details of place but it doesnt....Help would be appreciated .

here is my activity

package com.example.dell.Swing;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
 import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.os.Build;
    import android.support.annotation.NonNull;
    import android.support.v4.app.ActivityCompat;
    import android.util.Log;
    import android.view.View;
    import android.webkit.WebView;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
    import com.google.android.gms.common.GooglePlayServicesRepairableException;
    import com.google.android.gms.location.places.Place;
    import com.google.android.gms.location.places.PlacePhotoMetadata;
    import com.google.android.gms.location.places.PlacePhotoMetadataBuffer;
    import com.google.android.gms.location.places.PlacePhotoMetadataResult;
    import com.google.android.gms.location.places.Places;
     import com.google.android.gms.location.places.ui.PlacePicker;
    import com.uber.sdk.android.core.UberSdk;
    import com.uber.sdk.android.rides.RideParameters;
    import com.uber.sdk.android.rides.RideRequestButton;
    import com.uber.sdk.core.auth.Scope;
    import com.uber.sdk.rides.client.SessionConfiguration;
    import com.squareup.picasso.Picasso;

import java.util.Random;

    public class aarakuhotels extends AppCompatActivity {
private GoogleApiClient mGoogleApiClient;
RideRequestButton requestButton;
TextView placeNameText;
   ImageView image;
TextView placeAddressText,placeemailtext,placelocaletext,placephonetext;
WebView attributionText;
Button getPlaceButton;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
private final static int PLACE_PICKER_REQUEST = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_aarakuhotels);
    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, new OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                }
            })
            .build();

    requestPermission();
    SessionConfiguration config = new SessionConfiguration.Builder()
            .setClientId("wd9fPCpvtObmPOHBogaVdicLZW5Cos1K") //This is necessary
            .setRedirectUri("YOUR_REDIRECT_URI") //This is necessary if you'll be using implicit grant
            .build();

//This is a convenience method and will set the default config to be used in other components without passing it directly.

      UberSdk.initialize(config);

    placeNameText = (TextView) findViewById(R.id.hotelname);
    placeAddressText = (TextView) findViewById(R.id.hoteladdress);
    placeemailtext =(TextView) findViewById(R.id.email);
    placelocaletext =(TextView) findViewById(R.id.locale);
    placephonetext =(TextView) findViewById(R.id.phone);
    image =(ImageView) findViewById(R.id.hotelsimage);
   // attributionText = (WebView) findViewById(R.id.attribution);
    getPlaceButton = (Button) findViewById(R.id.gethotels);
    getPlaceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
            try {
                Intent intent = builder.build(aarakuhotels.this);
                startActivityForResult(intent, PLACE_PICKER_REQUEST);
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }

        }
    });
}

private void requestPermission() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case MY_PERMISSION_FINE_LOCATION:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "This app requires location permissions to be granted", Toast.LENGTH_LONG).show();
                finish();
            }
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PLACE_PICKER_REQUEST){
        if (resultCode == RESULT_OK){

            Place place = PlacePicker.getPlace(aarakuhotels.this, data);
            //Log.d("TAG",data.toString()); wait check karru ok
            Log.d("TAG",place.toString());
            final String placeId = place.getId();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    PlacePhotoMetadataResult result = Places.GeoDataApi
                            .getPlacePhotos(mGoogleApiClient, placeId).await();

                    if (result != null && result.getStatus().isSuccess()) {
                        PlacePhotoMetadataBuffer photoMetadataBuffer = result.getPhotoMetadata();

                //getting error here when i select a place with no photo and app crashes  --> PlacePhotoMetadata photo = photoMetadataBuffer.get(0);

                        final Bitmap locationimg = photo.getPhoto(mGoogleApiClient).await()
                                .getBitmap();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                image.setImageBitmap(locationimg);
                            }
                        });

                    }
                }
            }).start();

           // Picasso.with(this).load("https://lh5.googleusercontent.com/-_jVRD4o6K20/VrAgjefDtCI/AAAAAAABoTw/TH6pNjEcU-MelyMU8ZzLikO1HVpMyHDPQCJkC/s544-k-no/").into(image);
            placeNameText.setText("Name:"+place.getName());
            placephonetext.setText("Phone:"+place.getPhoneNumber());
            placeemailtext.setText("Website:"+place.getWebsiteUri());
            placelocaletext.setText("Rating:"+place.getRating());
            placeAddressText.setText("Address:"+place.getAddress());
           // if (place.getAttributions() == null) {
             //   attributionText.loadData("no attribution", "text/html; charset=utf-8", "UFT-8");
            //} else {
              //  attributionText.loadData(place.getAttributions().toString(), "text/html; charset=utf-8", "UFT-8");
            //}
        }
    }
}
 }


问:
Auto White Balance, Auto Tone
I came across to different search result from google or bing, I couldn't find a good example of adapting auto white balance for a bitmap file such as jpg.  My goal is to figure out how white balance algorithm works and how to adapt it using c#, java, or any programming language to achieve it.  If anyone could share some snippet or some resource, I would greatly appreciate it!  </p>

答:
The concept that is used in editing RAW format photos is the choose the whitest point in a photograph, then adjust to 255, 255, 255 ... but realistically, I adjust to around 240, 240, 240

I use Adobe bridge a lot for this

Title: Auto White Balance, Auto Tone


问:
Find the 2nd highest element

In a given array how to find the 2nd,  3rd, 4th,  or 5th values?

Also  if we use themax() function in python what is the order of complexity i.e, associated with this function max()?

.

```<code>def nth_largest(li,n):
    li.remove(max(li))
    print max(ele)  //will give me the second largest
    #how to make a general algorithm to find the 2nd,3rd,4th highest value
    #n is the element to be found  below the highest value
</code>```

答:
If you do not mind using numpy (import numpy as np):

```<code>np.partition(numbers, -i)[-i]
</code>```

gives you the ith largest element of the list with a guaranteed worst-case O(n) running time.

The partition(a, kth) methods returns an array where the kth element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.

Title: Find the 2nd highest element

Body:
In a given array how to find the 2nd,  3rd, 4th,  or 5th values?

Also  if we use themax() function in python what is the order of complexity i.e, associated with this function max()?

.

def nth_largest(li,n):
    li.remove(max(li))
    print max(ele)  //will give me the second largest
    #how to make a general algorithm to find the 2nd,3rd,4th highest value
    #n is the element to be found  below the highest value

Body:
If you do not mind using numpy (import numpy as np):

np.partition(numbers, -i)[-i]

gives you the ith largest element of the list with a guaranteed worst-case O(n) running time.

The partition(a, kth) methods returns an array where the kth element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.


问:
Limitation of SQL in BigQuery vs Cloud Spanner
While comparing Cloud Spanner vs BigQuery, Am trying to figure what kind of limitations there are in BigQuery's in SQL, compared to ANSI SQL (select part only) ?

Does BigQuery support all complex joins of ANSI SQL ?

Additionally, is there anything that Cloud Spanner can do and BigQuery cannot?

答:
BigQuery Standard SQL is compliant with the SQL 2011 standard and has extensions that support querying nested and repeated data.

You can see about SELECT and JOINS and other details of the BigQuery Standard SQL in Query Syntax documentation

Additionnally, is there anything than Spanner can do and BigQuery cannot ?

Main difference between BigQuery and Spanner:

```<code>BigQuery - Large scale data warehouse service with append-only tables
Spanner  - A horizontally scalable, globally consistent, relational database service
</code>```

Foreign Keys, Transaction support, Indexes - are good examples of what is supported in Spanner but not in BigQuery

Note: above not supported features are by design and reflect respective purpose of those two products. What is "a must" feature for one is even conceptually not in another. Comparing BigQuery and Spanner is close to comparing Hadoop and mySQL for example if this will make it easier for you to imagine.

I think it would be great if you read respective documentations and then ask specific questions

cloud.google.com/bigquery/docs

cloud.google.com/spanner/docs

Body:
BigQuery Standard SQL is compliant with the SQL 2011 standard and has extensions that support querying nested and repeated data.

You can see about SELECT and JOINS and other details of the BigQuery Standard SQL in Query Syntax documentation

Additionnally, is there anything than Spanner can do and BigQuery cannot ?

Main difference between BigQuery and Spanner:

BigQuery - Large scale data warehouse service with append-only tables
Spanner  - A horizontally scalable, globally consistent, relational database service

Foreign Keys, Transaction support, Indexes - are good examples of what is supported in Spanner but not in BigQuery

Note: above not supported features are by design and reflect respective purpose of those two products. What is "a must" feature for one is even conceptually not in another. Comparing BigQuery and Spanner is close to comparing Hadoop and mySQL for example if this will make it easier for you to imagine.

I think it would be great if you read respective documentations and then ask specific questions

cloud.google.com/bigquery/docs

cloud.google.com/spanner/docs


答:
Just return an array of two elements in the block.

Since Array#second is not defined in the standard library, do

```<code>array.uniq! { |c| [c[0], c[1]] }
</code>```

instead, which can be further simplified to array.uniq! { |c| c[0..1] }

Title: ruby uniq on the first two columns of two dimensional array

Body:
I have a two dimensional array with three fields in the second dimension.

Is it possible to use uniq on the first two fields of the second dimension?

I have seen array.uniq! {|c| c.first}. When I am correct, this apply uniq on the first field of the array.

Is it possible to use something like array.uniq! {|c| c.first c.second}?

@array = Array.new()

@array << Array.new([journal.from_account_number, journal.from_account,
                                journal.buchungsart])
There are several entries in @array.

The question was how to get unique values from array not considering journal.buchungsart.

The answer was: @array = @array.uniq! {|c| [c.first, c.second]}

Body:
Just return an array of two elements in the block.

Since Array#second is not defined in the standard library, do

array.uniq! { |c| [c[0], c[1]] }

instead, which can be further simplified to array.uniq! { |c| c[0..1] }


问:
Different response in my browser vs the API Testing Console
I am currently new in Cognitive services. Yesterday I tried Computer vision API where I got different JSON response for the same image in the API Testing console to that when I used the javascript code in my browser. I have enclosed my javascript code and the screenshot of the two different responses.

```<code><!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    var myKey = "my key";
    var myBody = {url:"http://activeforlife.com/wp/wp-content/uploads/2015/05/co-ed-kids-playing-soccer.jpg"}
    $(function() {
        var params = {
            // Request parameters
            "maxCandidates": "1",

        };

        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
            },
            type: "POST",
            // Request body
            data: JSON.stringify(myBody),
        })
        .done(function(data) {
            document.getElementById("ans").innerHTML = JSON.stringify(data);
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>

<h4 id="ans"></h4>

</body>
</html>
</code>```

Screenshot for the different outputs

答:
The Cognitive Service Vision API will perform different visual classifications depending on the visualFeatures query parameter.  You can find more details here.

If you don't specify any features, you are performing the equivalent of visualFeatures=Categories (your example).  The console appears to have been executed with visualFeatures=Description.  You can set the feature list in your param object.

Body:
I am currently new in Cognitive services. Yesterday I tried Computer vision API where I got different JSON response for the same image in the API Testing console to that when I used the javascript code in my browser. I have enclosed my javascript code and the screenshot of the two different responses.

<!DOCTYPE html>

    <title>JSSample</title>

Screenshot for the different outputs


问:
Swift 'use of undeclared type'
I'm currently trying to write a little iOS application in swift, where I have these Classes:
 masterTableViewController addViewController and deleteViewController, each of them is connected to a, like the name already tells, viewController. The masterTableViewController should sent some data using the predefined function:

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

  if(segue.identifier == "showDetails") {
    var selectedIndexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()!

    var deleteViewController:deleteViewController = segue!.destinationViewController as deleteViewController

    deleteViewController.todoData = todoItems.objectAtIndex(selectedIndexPath.row) as NSDictionary
}
</code>```

I want to send the data of the current row to the next, by segue referenced controller.

This is where I get an error message stating that deleteViewController is not a type that can be assigned to a variable.

But I don't really understand what the problem s right now. Basically this should work because I just want to create a new object of the type my class is of and pass this one to my view controller.

In the reference I got this code from everything worked just fine.

答:
This can occur if the class you are compiling is included in a unit test module, but the class that is not defined is not.

You will find that the app compiles and runs, but compilation errors may be shown in the source.

Open the right bar and check the Target Membership settings. They should be consistent for both classes.

Title: Swift 'use of undeclared type'

Body:
I'm currently trying to write a little iOS application in swift, where I have these Classes:
 masterTableViewController addViewController and deleteViewController, each of them is connected to a, like the name already tells, viewController. The masterTableViewController should sent some data using the predefined function:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

  if(segue.identifier == "showDetails") {
    var selectedIndexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()!

    var deleteViewController:deleteViewController = segue!.destinationViewController as deleteViewController

    deleteViewController.todoData = todoItems.objectAtIndex(selectedIndexPath.row) as NSDictionary
}

I want to send the data of the current row to the next, by segue referenced controller.

This is where I get an error message stating that deleteViewController is not a type that can be assigned to a variable.

But I don't really understand what the problem s right now. Basically this should work because I just want to create a new object of the type my class is of and pass this one to my view controller.

In the reference I got this code from everything worked just fine.


问:
lex - how to match escape characters for / and \
i'm looking for a way to way to match / and \
for example: if i get the string "hello\sir/!" i'd like to get hello\sir/!</p>

答:
Maybe try using (.*\\.*\/.*):

.* Should match every single character or nothing

\\ Should match a backslash (Two of them since you need to escape)

\/ Should match a common slash (With a backslash since you need to escape)

(...) Should be the capture group

Watch out for multiline tags (Depending on the text you want to match with)...

https://regex101.com/r/HY0NXI/3


问:
Elasticsearch-PHP needs curl or custom http handler
i'm deploy laravel 5.2 to ubuntu and installed elasticquent lib and elasticsearch 2.3.4 , when i try to figure the result of aggregation :

```<code>RuntimeException in ClientBuilder.php line 144:
Elasticsearch-PHP requires cURL, or a custom HTTP handler.
</code>```

I already install curl using command sudo apt-get install php5-curl and its still display the same error

How to fix it?

Thank you

答:
```<code>sudo apt-get install php-curl
</code>```

Try this, it will install curl as per your version of php.

Body:
i'm deploy laravel 5.2 to ubuntu and installed elasticquent lib and elasticsearch 2.3.4 , when i try to figure the result of aggregation :

RuntimeException in ClientBuilder.php line 144:
Elasticsearch-PHP requires cURL, or a custom HTTP handler.

I already install curl using command sudo apt-get install php5-curl and its still display the same error

How to fix it?

Thank you

Body:
sudo apt-get install php-curl

Try this, it will install curl as per your version of php.


问:
Sum over cell array of sparse matrices
I have 100 sparse matrices of size N-by-N, where N=65536.

They have about 5.5M nonzero elements(0.13% of N^2) close to the diagonal.

They are stored in a cell array, S{1}, ... , S{100}, and I want to compute the sum S{1}+...+S{100}.

```<code>Sum=sparse(N,N);
for i=1:100
    Sum=Sum+S{i};
end
</code>```

The above for loop code took about 25 seconds. Is there any way to optimize this code?

答:
This doesn't use loops, and also avoids converting the matrices into full:</p>

```<code>[ii, jj, vv] = find(vertcat(S{:})); % concatenate matrices vertically.
    % Get nonzero values (vv) with their row (ii) and column (jj) indices
ii = mod(ii-1, N) + 1; % convert ii to original row indices
Sum = sparse(ii, jj, vv); % this automatically adds values at the same ii, jj
</code>```

Title: Sum over cell array of sparse matrices

Body:
I have 100 sparse matrices of size N-by-N, where N=65536.

They have about 5.5M nonzero elements(0.13% of N^2) close to the diagonal.

They are stored in a cell array, S{1}, ... , S{100}, and I want to compute the sum S{1}+...+S{100}.

Sum=sparse(N,N);
for i=1:100
    Sum=Sum+S{i};
end

The above for loop code took about 25 seconds. Is there any way to optimize this code?

Body:
This doesn't use loops, and also avoids converting the matrices into full:

[ii, jj, vv] = find(vertcat(S{:})); % concatenate matrices vertically.
    % Get nonzero values (vv) with their row (ii) and column (jj) indices
ii = mod(ii-1, N) + 1; % convert ii to original row indices
Sum = sparse(ii, jj, vv); % this automatically adds values at the same ii, jj


问:
PostgreSQL multiple counts query performance
I'm writing a query in postgres to select the posts with more comments.

The following works but I'm wondering if it could become a performance problem with many posts.

Query:

```<code>SELECT
    po.*,
    (SELECT count(id) FROM comments WHERE post_id = po.id) AS comments_count
    FROM posts AS po
    ORDER BY comments_count DESC
    LIMIT 10;
</code>```

Result:

```<code>id   title  body  comments_count
2    Foo    Bar   5
1    Click  Bait  4
</code>```

Is there something I can do to improve this query performance or is it ok?

答:
You can use join instead of correlated subquery. Assuming id is PK in posts table:

```<code>select p.*,
    count(c.id) as comments_count
from posts p join comments c on p.id = c.post_id
group by p.id
order by comments_count desc limit 10;
</code>```

or

```<code>select p.*,
    c.comments_count
from posts p
join (
    select post_id,
        count(id) as comments_count
    from comments
    order by comments_count desc LIMIT 10
    ) c on p.id = c.post_id;
</code>```

Body:
I'm writing a query in postgres to select the posts with more comments.

The following works but I'm wondering if it could become a performance problem with many posts.

Query:

SELECT
    po.*,
    (SELECT count(id) FROM comments WHERE post_id = po.id) AS comments_count
    FROM posts AS po
    ORDER BY comments_count DESC
    LIMIT 10;

Result:

id   title  body  comments_count
2    Foo    Bar   5
1    Click  Bait  4

Is there something I can do to improve this query performance or is it ok?

Body:
You can use join instead of correlated subquery. Assuming id is PK in posts table:

select p.*,
    count(c.id) as comments_count
from posts p join comments c on p.id = c.post_id
group by p.id
order by comments_count desc limit 10;

or

select p.*,
    c.comments_count
from posts p
join (
    select post_id,
        count(id) as comments_count
    from comments
    order by comments_count desc LIMIT 10
    ) c on p.id = c.post_id;