问:
Angular-CLI Error: Return type of public method from exported class has or is using name 'ErrorObservable' from external module but cannot be named
After building out an app that is a clone of a working Angular 2 (non-cli) app, I notice several of my files are producing errors (of the same kind) now that the project is built with the Angular-CLI. I'm unclear why these are errors in the CLI version, but not in the other. Is this a Webpack-related issue? Or something to do with how Typescript is processed differently between the two builds? To clarify, the initial app used SystemJS, and the Angular-CLI version uses Webpack. When I say I "built out" the app, I mean I recreated all of the components, directives, modules, routes, etc, that I had in the original app in this clone version. This is the general error message I get (across several files):

Error: Return type of public method from exported class has or is
  using name 'ErrorObservable' from external module but cannot be named

And here's an example of a file that's listed as producing this error:

```<code>import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class StreamCountsService {

    private _url: string = "https://api.somesite.com"

    constructor(private _http: Http) {}

    getCount() {
        return this._http.get(this._url)
            .map((response:Response) => response.json())
            .catch(this._errorsHandler);
    }
    _errorsHandler(error: Response) {
        console.error(error);
        return Observable.throw(error || "Server Error");
    }
}
</code>```

My Setup:
MacBook Air, OS X El Capitan

Angular-CLI Version
Running the Angular-CLI version 1.0.0-beta.22-1

The full error trace looks like this (edited slightly for privacy):

vendor.bundle.js:52455 ./src/app/data/stream.service.ts Module build
  failed: Error:
  /Users/adds/Documents/abc/abc-cli/cli-abc/src/app/data/stream-assign.service.ts
  (20,5): Return type of public method from exported class has or is
  using name 'ErrorObservable' from external module
  "/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/rxjs/observable/ErrorObservable"
  but cannot be named.) at _checkDiagnostics
  (/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:115:15)
  at
  /Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:140:17
  @ ./src/app/views/stream/stream-module.ts 25:0-82 @
  ./src/app/app.module.ts @ ./src/app/index.ts @ ./src/main.ts @ multi
  main vendor.bundle.js:52455 ./src/app/data/stream-assign.service.ts
  Module build failed: Error:
  /Users/adds/Documents/abc/abc-cli/cli-abc/src/app/data/stream-assign-comm.service.ts
  (20,5): Return type of public method from exported class has or is
  using name 'ErrorObservable' from external module
  "/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/rxjs/observable/ErrorObservable"
  but cannot be named.) at _checkDiagnostics
  (/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:115:15)
  at
  /Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:140:17
  @ ./src/app/views/stream/stream-module.ts 25:0-82 @
  ./src/app/app.module.ts @ ./src/app/index.ts @ ./src/main.ts @ multi
  main

Here are my package.json file contents:

```<code>{
  "name": "cli-ark",
  "version": "0.0.1",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.2.3",
    "@angular/compiler": "2.2.3",
    "@angular/core": "2.2.3",
    "@angular/forms": "2.2.3",
    "@angular/http": "2.2.3",
    "@angular/platform-browser": "2.2.3",
    "@angular/platform-browser-dynamic": "2.2.3",
    "@angular/router": "3.2.3",
    "@types/socket.io": "^1.4.27",
    "@types/socket.io-client": "^1.4.29",
    "angular-in-memory-web-api": "~0.1.15",
    "angular2-chartjs": "^0.1.6",
    "chart.js": "^2.4.0",
    "core-js": "^2.4.1",
    "ng2-charts": "^1.4.1",
    "rxjs": "5.0.0-beta.12",
    "socket.io": "^1.7.2",
    "socket.io-client": "^1.7.2",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@angular/compiler-cli": "2.2.3",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.22-1",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "4.0.9",
    "ts-node": "1.2.1",
    "typescript": "~2.0.3",
    "typings": "^1.3.2",
    "webdriver-manager": "10.2.5"
  }
}
</code>```

答:
After rx update to 5+ version, you should use

ErrorObservable

instead of

throw

Your code should update from:

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
...
this.somethingReturnObservable.get()
  .filter( val => val*2)
  .do((val) => {
    // do something for example
  })
  .switchMap(trans => Observable.throw( 'some error' ))
  .catch( (er, c) => dosomething);
</code>```

To:

```<code>import { ErrorObservable } from 'rxjs/observable/errorObservable';
import { switchMap, tap, catchError, filter } from 'rxjs/operators';
...
this.somethingReturnObservable.get()
  .pipe(
    filter( val => val*2)
    tap( (val) => {// do something for example} ),
    switchMap( trans => ErrorObservable.create( 'some error' ) ),
    catchError( (er, c) => dosomething);
  );
</code>```

Body:
After building out an app that is a clone of a working Angular 2 (non-cli) app, I notice several of my files are producing errors (of the same kind) now that the project is built with the Angular-CLI. I'm unclear why these are errors in the CLI version, but not in the other. Is this a Webpack-related issue? Or something to do with how Typescript is processed differently between the two builds? To clarify, the initial app used SystemJS, and the Angular-CLI version uses Webpack. When I say I "built out" the app, I mean I recreated all of the components, directives, modules, routes, etc, that I had in the original app in this clone version. This is the general error message I get (across several files):

Error: Return type of public method from exported class has or is
  using name 'ErrorObservable' from external module but cannot be named

And here's an example of a file that's listed as producing this error:

import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class StreamCountsService {

    private _url: string = "https://api.somesite.com"

    constructor(private _http: Http) {}

    getCount() {
        return this._http.get(this._url)
            .map((response:Response) => response.json())
            .catch(this._errorsHandler);
    }
    _errorsHandler(error: Response) {
        console.error(error);
        return Observable.throw(error || "Server Error");
    }
}

My Setup:
MacBook Air, OS X El Capitan

Angular-CLI Version
Running the Angular-CLI version 1.0.0-beta.22-1

The full error trace looks like this (edited slightly for privacy):

vendor.bundle.js:52455 ./src/app/data/stream.service.ts Module build
  failed: Error:
  /Users/adds/Documents/abc/abc-cli/cli-abc/src/app/data/stream-assign.service.ts
  (20,5): Return type of public method from exported class has or is
  using name 'ErrorObservable' from external module
  "/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/rxjs/observable/ErrorObservable"
  but cannot be named.) at _checkDiagnostics
  (/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:115:15)
  at
  /Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:140:17
  @ ./src/app/views/stream/stream-module.ts 25:0-82 @
  ./src/app/app.module.ts @ ./src/app/index.ts @ ./src/main.ts @ multi
  main vendor.bundle.js:52455 ./src/app/data/stream-assign.service.ts
  Module build failed: Error:
  /Users/adds/Documents/abc/abc-cli/cli-abc/src/app/data/stream-assign-comm.service.ts
  (20,5): Return type of public method from exported class has or is
  using name 'ErrorObservable' from external module
  "/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/rxjs/observable/ErrorObservable"
  but cannot be named.) at _checkDiagnostics
  (/Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:115:15)
  at
  /Users/adds/Documents/abc/abc-cli/cli-abc/node_modules/@ngtools/webpack/src/loader.js:140:17
  @ ./src/app/views/stream/stream-module.ts 25:0-82 @
  ./src/app/app.module.ts @ ./src/app/index.ts @ ./src/main.ts @ multi
  main

Here are my package.json file contents:

{
  "name": "cli-ark",
  "version": "0.0.1",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.2.3",
    "@angular/compiler": "2.2.3",
    "@angular/core": "2.2.3",
    "@angular/forms": "2.2.3",
    "@angular/http": "2.2.3",
    "@angular/platform-browser": "2.2.3",
    "@angular/platform-browser-dynamic": "2.2.3",
    "@angular/router": "3.2.3",
    "@types/socket.io": "^1.4.27",
    "@types/socket.io-client": "^1.4.29",
    "angular-in-memory-web-api": "~0.1.15",
    "angular2-chartjs": "^0.1.6",
    "chart.js": "^2.4.0",
    "core-js": "^2.4.1",
    "ng2-charts": "^1.4.1",
    "rxjs": "5.0.0-beta.12",
    "socket.io": "^1.7.2",
    "socket.io-client": "^1.7.2",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@angular/compiler-cli": "2.2.3",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.22-1",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "4.0.9",
    "ts-node": "1.2.1",
    "typescript": "~2.0.3",
    "typings": "^1.3.2",
    "webdriver-manager": "10.2.5"
  }
}

Body:
After rx update to 5+ version, you should use

ErrorObservable

instead of

throw

Your code should update from:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
...
this.somethingReturnObservable.get()
  .filter( val => val*2)
  .do((val) => {
    // do something for example
  })
  .switchMap(trans => Observable.throw( 'some error' ))
  .catch( (er, c) => dosomething);

To:

import { ErrorObservable } from 'rxjs/observable/errorObservable';
import { switchMap, tap, catchError, filter } from 'rxjs/operators';
...
this.somethingReturnObservable.get()
  .pipe(
    filter( val => val*2)
    tap( (val) => {// do something for example} ),
    switchMap( trans => ErrorObservable.create( 'some error' ) ),
    catchError( (er, c) => dosomething);
  );


来源: stackexchange

问:
call a global function in CoffeeScript
I'm getting a strange behavior with CoffeeScript: the initMap function is correctly called from the loaded script (&callback=initMap), but I have an error triggered by the last line at initMap()

```<code># Declare a global function
@initMap = ->
  restaurantLocation =
    lat: $('#restaurant-map').data("lat")
    lng: $('#restaurant-map').data("lng")
  map = new (google.maps.Map) $('#restaurant-map')[0],
    zoom: 19,
    center: restaurantLocation
  marker = new (google.maps.Marker)
    position: restaurantLocation
    map: map

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0
    if page.included_google_maps_js_api == undefined
      google_maps_api_key = 'xxx'
      # correctly called from here...
      $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
      page.included_google_maps_js_api = true
    initMap() # Uncaught ReferenceError: google is not defined
</code>```

What I find funny is that this other snippet is working flawlessly:

```<code>$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0 && page.included_google_maps_js_api == undefined
    google_maps_api_key = 'xxx'
    $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
    page.included_google_maps_js_api = true
  else if ($('#restaurant-map').length > 0)
    initMap()
</code>```

答:
$.getScript gets the script asynchronously. You're not waiting for the result of that before calling initMap in the case where page.included_google_maps_js_api == undefined is true.

You just need an else (since you're using &callback=initMap to call it in the case where need to load):

```<code>$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0
    if page.included_google_maps_js_api == undefined
      google_maps_api_key = 'xxx'
      # correctly called from here...
      $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
      page.included_google_maps_js_api = true
    else                  # <== Note the else
      initMap()           #     so we only do this if it's loaded
</code>```

ContentLicense: CC BY-SA 3.0

Title: call a global function in CoffeeScript

Body:
I'm getting a strange behavior with CoffeeScript: the initMap function is correctly called from the loaded script (&callback=initMap), but I have an error triggered by the last line at initMap()

# Declare a global function
@initMap = ->
  restaurantLocation =
    lat: $('#restaurant-map').data("lat")
    lng: $('#restaurant-map').data("lng")
  map = new (google.maps.Map) $('#restaurant-map')[0],
    zoom: 19,
    center: restaurantLocation
  marker = new (google.maps.Marker)
    position: restaurantLocation
    map: map

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0
    if page.included_google_maps_js_api == undefined
      google_maps_api_key = 'xxx'
      # correctly called from here...
      $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
      page.included_google_maps_js_api = true
    initMap() # Uncaught ReferenceError: google is not defined

What I find funny is that this other snippet is working flawlessly:

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0 && page.included_google_maps_js_api == undefined
    google_maps_api_key = 'xxx'
    $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
    page.included_google_maps_js_api = true
  else if ($('#restaurant-map').length > 0)
    initMap()

Body:
$.getScript gets the script asynchronously. You're not waiting for the result of that before calling initMap in the case where page.included_google_maps_js_api == undefined is true.

You just need an else (since you're using &callback=initMap to call it in the case where need to load):

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0
    if page.included_google_maps_js_api == undefined
      google_maps_api_key = 'xxx'
      # correctly called from here...
      $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
      page.included_google_maps_js_api = true
    else                  # <== Note the else
      initMap()           #     so we only do this if it's loaded


问:
tkinter: callback not returning the value?
My function is not returning any value which i entered into entry-box on button click:</p>

```<code>from tkinter import *
import os

def onclick2():
    val = box.get()
    return(val)
root = Tk()
box = Entry(root)
box.pack()
buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black', 9), bd=10, width=20,command=onclick2)
buttonfortxtbox.pack(anchor = S)
print(onclick2())
root.mainloop()
</code>```

答:
Nothing is wrong with your code. But your understanding is not exact:

When you run this line: print(onclick2()) you are trying to print the content of the entry widget which is empty when the program first starts. So that is perfectly normal you are not getting anything visible on the Terminal.

To see the content of the entry widget, modify slightly your callback as follows:

```<code>def onclick2():
    val = box.get()
    print(val)
    # You can remove "return val" as it is completely useless for your context
</code>```

With this simple change, you will see None printed on the Terminal, which thing corresponds to what I described above. Now type something within the entry widget and click on the button: what you type appears finally on the output (Terminal).

Body:
My function is not returning any value which i entered into entry-box on button click:

from tkinter import *
import os

def onclick2():
    val = box.get()
    return(val)
root = Tk()
box = Entry(root)
box.pack()
buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black', 9), bd=10, width=20,command=onclick2)
buttonfortxtbox.pack(anchor = S)
print(onclick2())
root.mainloop()

Body:
Nothing is wrong with your code. But your understanding is not exact:

When you run this line: print(onclick2()) you are trying to print the content of the entry widget which is empty when the program first starts. So that is perfectly normal you are not getting anything visible on the Terminal.

To see the content of the entry widget, modify slightly your callback as follows:

def onclick2():
    val = box.get()
    print(val)
    # You can remove "return val" as it is completely useless for your context

With this simple change, you will see None printed on the Terminal, which thing corresponds to what I described above. Now type something within the entry widget and click on the button: what you type appears finally on the output (Terminal).


问:
Delay AWS Code Pipeline:
Current Setup:
I have a Lambda function that is invoked by AWS CodePipeline. The Lambda function dumps some files to a s3 bucket and the CodePipeline continues on to another phase (in this case a testing phase).

Problem:
I need the aforementioned pipeline to wait around 60 seconds after the files are dumped to the s3 bucket (this is to ensure processing has finished within my code base that reads the s3 bucket that was dumped to). After the delay, my tests should execute cleanly.

Question:
Is there a way within code pipeline to wait for a given time?
Could Lambda execute a waiting function?

-

I have done a fair amount of research on implementing delays in Javascript (the language that my Lambda function is written in). I couldn't implement an async sleep function, nor could I find any Lambda documentation on how this is implemented.

答:
I am not sure about JS lambda , but from your JS lambda you can call another Lamda written in Python to wait for 60 sec.

Second approach could be you can use AWS step function to wait for 60 sec after you dump the data in S3 and before you execute the test method.

Python Lambda to wait:

```<code>import boto3, os, time
def lambda_handler(event, context):
    time.sleep(60)
</code>```

Title: Delay AWS Code Pipeline:

Body:
I am not sure about JS lambda , but from your JS lambda you can call another Lamda written in Python to wait for 60 sec.

Second approach could be you can use AWS step function to wait for 60 sec after you dump the data in S3 and before you execute the test method.

Python Lambda to wait:

import boto3, os, time
def lambda_handler(event, context):
    time.sleep(60)


问:
Visual Studio 2010 Make and Install Templates
I am using F# and i found that the available templates were a bit to sparse for my liking, and i want to make more. How would i go about doing that? also, how would i install these templates after I've made them?</p>

答: You can get the complete example implemented here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample</p>

ContentLicense: CC BY-SA 2.5


问:
Return arrow and text using ax.annotate in matplotlib
Using the object-oriented approach to matplotlib, is there a way to get access to the arrow that is drawn when using ax.annotate.

It seems this command returns the text as an object, but not the arrow. I also can't find the arrow when using the show_children command.

Can this arrow be accessed please? I simply want to get all arrows on my plot and change their color.

```<code>plt.plot(np.arange(5), 2* np.arange(5))
plt.plot(np.arange(5), 3*np.arange(5))
ax = plt.gca()

text = ax.annotate('TEST', xytext=(2,10), xy=(2,2), arrowprops=dict(arrowstyle="->"))

ax.get_children()
</code>```

returns

```<code>[<matplotlib.lines.Line2D at 0x207dcdba978>,
 <matplotlib.lines.Line2D at 0x207de1e47f0>,
 Text(2,10,'TEST'),
 <matplotlib.spines.Spine at 0x207dcb81518>,
 <matplotlib.spines.Spine at 0x207de05b320>,
 <matplotlib.spines.Spine at 0x207de0b7828>,
 <matplotlib.spines.Spine at 0x207de1d9080>,
  <matplotlib.axis.XAxis at 0x207de1d9f28>,
 <matplotlib.axis.YAxis at 0x207de049358>,
 Text(0.5,1,''),
 Text(0,1,''),
 Text(1,1,''),
 <matplotlib.patches.Rectangle at 0x207de049d30>]
</code>```

Thanks

答:
First note that the color of an arrow can be set at creation of the annotation using the color argument in the arrowprops:

```<code>ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2),
             arrowprops=dict(arrowstyle="->", color="blue"))
</code>```

If there is really the need to change the color afterwards, you need to obtain the patch of the arrow from the text.

In case an arrow is produced with an Annotation, the Annotation object has an attribute arrow_patch. You can use it to access the arrow patch, as

```<code>text = ax.annotate( ... )
text.arrow_patch.set_color("red")
</code>```

Of course you could then loop over all children and check if they contain an arrow. Complete example:

```<code>import matplotlib.pyplot as plt
ax = plt.gca()

text = ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2), arrowprops=dict(arrowstyle="->"))
text2 = ax.annotate('TEST2', xytext=(.5,.5), xy=(.2,.2), arrowprops=dict(arrowstyle="->"))

# access each object individually
#text.arrow_patch.set_color("red")
# or

for child in ax.get_children():
    if isinstance(child,type(text)):
        if hasattr(child, "arrow_patch"):
            child.arrow_patch.set_color("red")

plt.show()
</code>```

Body:
Using the object-oriented approach to matplotlib, is there a way to get access to the arrow that is drawn when using ax.annotate.

It seems this command returns the text as an object, but not the arrow. I also can't find the arrow when using the show_children command.

Can this arrow be accessed please? I simply want to get all arrows on my plot and change their color.

plt.plot(np.arange(5), 2* np.arange(5))
plt.plot(np.arange(5), 3*np.arange(5))
ax = plt.gca()

text = ax.annotate('TEST', xytext=(2,10), xy=(2,2), arrowprops=dict(arrowstyle="->"))

ax.get_children()

returns

[<matplotlib.lines.Line2D at 0x207dcdba978>,
 <matplotlib.lines.Line2D at 0x207de1e47f0>,
 Text(2,10,'TEST'),
 <matplotlib.spines.Spine at 0x207dcb81518>,
 <matplotlib.spines.Spine at 0x207de05b320>,
 <matplotlib.spines.Spine at 0x207de0b7828>,
 <matplotlib.spines.Spine at 0x207de1d9080>,
  <matplotlib.axis.XAxis at 0x207de1d9f28>,
 <matplotlib.axis.YAxis at 0x207de049358>,
 Text(0.5,1,''),
 Text(0,1,''),
 Text(1,1,''),
 <matplotlib.patches.Rectangle at 0x207de049d30>]

Thanks

Body:
First note that the color of an arrow can be set at creation of the annotation using the color argument in the arrowprops:

ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2),
             arrowprops=dict(arrowstyle="->", color="blue"))

If there is really the need to change the color afterwards, you need to obtain the patch of the arrow from the text.

In case an arrow is produced with an Annotation, the Annotation object has an attribute arrow_patch. You can use it to access the arrow patch, as

text = ax.annotate( ... )
text.arrow_patch.set_color("red")

Of course you could then loop over all children and check if they contain an arrow. Complete example:

import matplotlib.pyplot as plt
ax = plt.gca()

text = ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2), arrowprops=dict(arrowstyle="->"))
text2 = ax.annotate('TEST2', xytext=(.5,.5), xy=(.2,.2), arrowprops=dict(arrowstyle="->"))

# access each object individually
#text.arrow_patch.set_color("red")
# or

for child in ax.get_children():
    if isinstance(child,type(text)):
        if hasattr(child, "arrow_patch"):
            child.arrow_patch.set_color("red")

plt.show()


问:
I can't perform "click()" to skip a screen
Espresso recorder wrote me the next code:

```<code>ViewInteraction appCompatTextView2 = onView(allOf(withId(R.id.skipBtnTextView_BirthdayActivity), withText("Skip this step"), childAtPosition(allOf(withId(R.id.skipLayout_BirthdayActivity), childAtPosition(withClassName(is("android.widget.LinearLayout")),4)),1),isDisplayed()));
appCompatTextView2.perform(click());
</code>```

It does not work after running. I replaced it with:

```<code>onView(withId(R.id.skipBtnTextView_BirthdayActivity)).check(matches(withText("Skip this step")));
onView(withId(R.id.skipBtnTextView_BirthdayActivity)).perform(click());
</code>```

But it fails too.

```<code>android.support.test.espresso.PerformException: Error performing
'single click - At Coordinates: 539, 1359 and precision: 16, 16' on
view 'with id: com.ingenio.keen:id/skipBtnTextView_BirthdayActivity'.
</code>```

Can anybody help me?

答:
first of all you should define your button/textView etc like this:

```<code>Button button=(Button)findViewById(R.id.button);
</code>```

you should give an id to your button in your layout.xml

then you should write a setOnClickListener:

```<code>    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Intent intent=new Intent(YourActivity.this,DestanationActivity.class);
          startactivity(intent);//you will go to home screen activity with this

        }
    });
</code>```

Body:
Espresso recorder wrote me the next code:

ViewInteraction appCompatTextView2 = onView(allOf(withId(R.id.skipBtnTextView_BirthdayActivity), withText("Skip this step"), childAtPosition(allOf(withId(R.id.skipLayout_BirthdayActivity), childAtPosition(withClassName(is("android.widget.LinearLayout")),4)),1),isDisplayed()));
appCompatTextView2.perform(click());

It does not work after running. I replaced it with:

onView(withId(R.id.skipBtnTextView_BirthdayActivity)).check(matches(withText("Skip this step")));
onView(withId(R.id.skipBtnTextView_BirthdayActivity)).perform(click());

But it fails too.

android.support.test.espresso.PerformException: Error performing
'single click - At Coordinates: 539, 1359 and precision: 16, 16' on
view 'with id: com.ingenio.keen:id/skipBtnTextView_BirthdayActivity'.

Can anybody help me?

Body:
first of all you should define your button/textView etc like this:

Button button=(Button)findViewById(R.id.button);

you should give an id to your button in your layout.xml

then you should write a setOnClickListener:

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Intent intent=new Intent(YourActivity.this,DestanationActivity.class);
          startactivity(intent);//you will go to home screen activity with this

        }
    });


问:
Audio.js HTML5 volume control
I'm using the audio.js library for a project I'm working on and I'm having a hard time implementing a volume controller. I've tried contacting the developer who built the library, but haven't been able to reach him. I've built a volume slider using jQuery UI and I'm now trying to parse the value of the slider to all players in my instance using the .setVolume function. I can't make it work though. Here's my code:</p>

```<code>audiojs.events.ready(function() {

    var audio = audiojs.createAll(),
        slider = $('#slider');

    tooltip.hide();

    slider.slider({
        range: 'min',
        min: 1,
        value: 35,

        start: function(event,ui) {
            // Start
        },

        slide: function(event, ui) {

            var value = slider.slider('value');

            // Slide

        },

        stop: function(event,ui) {
            // Stop
        },

        change: function(event,ui) {
            audio.setVolume(ui.value / 100);
        },

    });

});
</code>```

答:
Without using audio.js library you can simply do it by using volume attribute of the audio element of HTML5.

For that, you can go with the below lines.

```<code>var myAudio = document.getElementById('myAudio');
myAudio.volume = 0.32;
</code>```

Where Volume 1.0 is highest and 0.0 is the lowest volume.

Title: Audio.js HTML5 volume control

Body:
I'm using the audio.js library for a project I'm working on and I'm having a hard time implementing a volume controller. I've tried contacting the developer who built the library, but haven't been able to reach him. I've built a volume slider using jQuery UI and I'm now trying to parse the value of the slider to all players in my instance using the .setVolume function. I can't make it work though. Here's my code:

audiojs.events.ready(function() {

    var audio = audiojs.createAll(),
        slider = $('#slider');

    tooltip.hide();

    slider.slider({
        range: 'min',
        min: 1,
        value: 35,

        start: function(event,ui) {
            // Start
        },

        slide: function(event, ui) {

            var value = slider.slider('value');

            // Slide

        },

        stop: function(event,ui) {
            // Stop
        },

        change: function(event,ui) {
            audio.setVolume(ui.value / 100);
        },

    });

});

Body:
Without using audio.js library you can simply do it by using volume attribute of the audio element of HTML5.

For that, you can go with the below lines.

var myAudio = document.getElementById('myAudio');
myAudio.volume = 0.32;

Where Volume 1.0 is highest and 0.0 is the lowest volume.


问:
Creating an gauge chart in Angular 4
I need to create the chart in angular 4 app like in mockup:
mockup

So which library do I need to use to create such a chart? Before the question i saw all libraries but i did not find something that looked like this mockup.

答:
You can produce the chart that looks exactly the same as your mockup using Highcharts solid gauge series: https://www.highcharts.com/demo/gauge-solid

Edit

Here are few things that need to be done:

set proper value for pane.startAngle and pane.endAngle

configure the style and values of ticks (tickPositions option
can be used for irregular tick positions)

change innerRadius and outerRadius to make the pane thinner

use the coloring solution from this post:
Highcharts solid gauge, show colors of previous stops in gauge

Title: Creating an gauge chart in Angular 4


问:
Can I access metadata annotations of a type or parameter in flutter?
Or is that capability lost with the loss of the reflect package?

What I'm curious about is can I use annotations in my own flutter app? Or is that a feature only available in dart, but not flutter?

答:
Yes, of course you can use metadata annotations in flutter. Flutter has a meta-library, which you can look into to know about available annotations that can be used with flutter.

Hope this helped!


问:
swift case falling through
Does swift have fall through statement? e.g if I do the following

```<code>var testVar = "hello"
var result = 0

switch(testVal)
{
case "one":
    result = 1
case "two":
    result = 1
default:
    result = 3
}
</code>```

is it possible to have  the same code executed for case "one" and case "two"?

答:
Here is example for you easy to understand:

```<code>let value = 0

switch value
{
case 0:
    print(0) // print 0
    fallthrough
case 1:
    print(1) // print 1
case 2:
    print(2) // Doesn't print
default:
    print("default")
}
</code>```

Conclusion: Use fallthrough to execute next case (only one) when the previous one that have fallthrough is match or not.

Title: swift case falling through

Body:
Does swift have fall through statement? e.g if I do the following

var testVar = "hello"
var result = 0

switch(testVal)
{
case "one":
    result = 1
case "two":
    result = 1
default:
    result = 3
}

is it possible to have  the same code executed for case "one" and case "two"?

Body:
Here is example for you easy to understand:

let value = 0

switch value
{
case 0:
    print(0) // print 0
    fallthrough
case 1:
    print(1) // print 1
case 2:
    print(2) // Doesn't print
default:
    print("default")
}

Conclusion: Use fallthrough to execute next case (only one) when the previous one that have fallthrough is match or not.


问:
git delete pushed commit and remove history entry
I have pushed some changes to the repository.

I want to delete the last commit from the repository and permanently remove the history entry as well.

How can I do this?

答:
Try:

```<code>git checkout <branch> // replace branch with a name of the branch you worked on
git reset --hard HEAD~1 // this command removes the latest commit
git push --force-with-lease origin <branch> // push the changes to the remote
</code>```

If nobody modified the remote while doing the operation above your push will be accepted, otherwise it may be rejected. Further steps are dependant on if you can use -f instead of --force-with-lease. If so do it, but it will overwrite other's changes. If not - it can't be done without changing the history.

Body:
Try:

git checkout <branch> // replace branch with a name of the branch you worked on
git reset --hard HEAD~1 // this command removes the latest commit
git push --force-with-lease origin <branch> // push the changes to the remote

If nobody modified the remote while doing the operation above your push will be accepted, otherwise it may be rejected. Further steps are dependant on if you can use -f instead of --force-with-lease. If so do it, but it will overwrite other's changes. If not - it can't be done without changing the history.


问:
Why I get error when I submit login form using jQuery Post?
I have this partial view:

```<code>@model GeomindEnterprise.Models.LoginViewModel

<div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <!-- /SOCIAL LOGIN -->
        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">
                <div class="row">
                    <div class="col-md-10 col-md-offset-1">
                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-envelope"></i>
                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                        </label>

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-lock"></i>
                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                        </label>

                        <label class="form-group">
                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)
                        </label>

                        <footer>
                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"><i class="fa fa-check"></i> OK, LOG IN</button>
                        </footer>
                    </div>
                </div>

            </fieldset>

        }
    </div>
</div>
</code>```

When I click button submit, this javascript method is called:

```<code> function myFunction() {
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }
</code>```

The javascript method above calls this action:

```<code>//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}
</code>```

When the acction Login is called I get this error:

```<code>    The required anti-forgery form field "__RequestVerificationToken" is not present.
</code>```

Any idea why I get this error?And how to fix it?

答:
What you want to do is.

```<code>contentType: "application/json; charset=utf-8"
</code>```

And by doing that (which changes the kind of post request being made), to get the Json content of the actual data property to bind correctly to your T model type DO NOT JSON.stringify() or  jQuery('form').serialize() the data.

Body:
I have this partial view:

@model GeomindEnterprise.Models.LoginViewModel

        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">

                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)

                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"> OK, LOG IN</button>

            </fieldset>

        }

When I click button submit, this javascript method is called:

 function myFunction() {
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }

The javascript method above calls this action:

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}

When the acction Login is called I get this error:

    The required anti-forgery form field "__RequestVerificationToken" is not present.

Any idea why I get this error?And how to fix it?

Body:
What you want to do is.

contentType: "application/json; charset=utf-8"

And by doing that (which changes the kind of post request being made), to get the Json content of the actual data property to bind correctly to your T model type DO NOT JSON.stringify() or  jQuery('form').serialize() the data.


问:
JavaScript: Changing innerHtml to a radio button value
in our html we have a document with a radio button and a value.

This Code opens a popup:

```<code><tr>
      <td><input id="vname" name="vname"></td>
      <td>Cell</td>
      <td id="eins"><button id="a1" class="button button-block"/ onclick="popup1()" name="button1">Eintragen</button></td>
    </tr>

function popup1(){
    a1.name = "b1"
    window.open('schadensausmass.html', "popup", "width=700,height=600");
    alert("t")
    }
</code>```

This is the separate Html File (popup):

```<code><form name="myForm">
    <td><input type="radio" id = "radio1" name= "gleich" value="2"></td>
    <td><input type="radio" id = "radio2" name= "gleich" value="1"></td>
    <td><input type="radio" id = "radio3" name= "gleich" value="3"></td>
</form>
</table>
  <button type="button" onclick="meineFunktion()"></button>
</code>```

We want the radio button value to be set in the innerhtml of . So we tried this.

```<code>    function meineFunktion() {
    if (opener.document.getElementById("a1").name == "b1"){
    window.close('schadensausmass.html')
    opener.document.getElementById("eins").innerHTML= document.myForm.elements[1].value
}
</code>```

Unfortunately the innerHtml doesnt change. If we do it like this

```<code>opener.document.getElementById("eins").innerHTML="Foo"
</code>```

the innerHTML does change.
So the problem has something to do with document.myForm.elements[1].value
Any tips what could be wrong here?

答:
```<code><input id="rdBtnDigitize" type="radio" name= "gleich" value="1">
</code>```

Script

```<code>$(function () {
    $('#rdBtnDigitize')[0].nextSibling.data = 'Foo'
});
</code>```

Body:
in our html we have a document with a radio button and a value.

This Code opens a popup:

      <input id="vname" name="vname">
      Cell
      <button id="a1" class="button button-block"/ onclick="popup1()" name="button1">Eintragen</button>

function popup1(){
    a1.name = "b1"
    window.open('schadensausmass.html', "popup", "width=700,height=600");
    alert("t")
    }

This is the separate Html File (popup):

<form name="myForm">
    <input type="radio" id = "radio1" name= "gleich" value="2">
    <input type="radio" id = "radio2" name= "gleich" value="1">
    <input type="radio" id = "radio3" name= "gleich" value="3">
</form>

  <button type="button" onclick="meineFunktion()"></button>

We want the radio button value to be set in the innerhtml of . So we tried this.

    function meineFunktion() {
    if (opener.document.getElementById("a1").name == "b1"){
    window.close('schadensausmass.html')
    opener.document.getElementById("eins").innerHTML= document.myForm.elements[1].value
}

Unfortunately the innerHtml doesnt change. If we do it like this

opener.document.getElementById("eins").innerHTML="Foo"

the innerHTML does change.
So the problem has something to do with document.myForm.elements[1].value
Any tips what could be wrong here?

Body:
<input id="rdBtnDigitize" type="radio" name= "gleich" value="1">

Script

$(function () {
    $('#rdBtnDigitize')[0].nextSibling.data = 'Foo'
});


问:
UPDATE multiple table with same column name with condition for each value on MYSQL
I've a column "pid" and a lot of table on each database , then I want to update all table from every database with column "pid" and set 'pid' = 5 where 'pid' = 3 and set 'pid' = 6 where 'pid = '7' on 1 query .

I've find post like this and try to apply it:

```<code>Select 'UPDATE ' + TABLE_NAME + ' SET pid = ''5'' '
From INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'pid'
</code>```

Without condition for try it , then MYSQL just return me a select with value 0 .

```<code>'UPDATE ' + TABLE_NAME + ' SET pid = ''5'' '
                                           0
</code>```

Need a little help and explain for make this query work and understand how its work .

Really thanks everyone :)

答:
```<code>UPDATE table_name
SET pid = 5
WHERE pid = 3;
</code>```

It should be implemented like this. You simply tell to update the table named table_name to set pid as '5' wherever it finds it as '3'.

Read also here. ;)

Body:
I've a column "pid" and a lot of table on each database , then I want to update all table from every database with column "pid" and set 'pid' = 5 where 'pid' = 3 and set 'pid' = 6 where 'pid = '7' on 1 query .

I've find post like this and try to apply it:

Select 'UPDATE ' + TABLE_NAME + ' SET pid = ''5'' '
From INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'pid'

Without condition for try it , then MYSQL just return me a select with value 0 .

'UPDATE ' + TABLE_NAME + ' SET pid = ''5'' '
                                           0

Need a little help and explain for make this query work and understand how its work .

Really thanks everyone :)

Body:
UPDATE table_name
SET pid = 5
WHERE pid = 3;

It should be implemented like this. You simply tell to update the table named table_name to set pid as '5' wherever it finds it as '3'.

Read also here. ;)


问:
Visual Studio solution explorer out of memory exception
When I open the visual studio 2010 premium, Solution explorer doesn't show up.
It was working and now its not.

It is showing a out of memory exception. Any help would be greatly appreciated.

Attached is the screen shot

答:
This exception can have more than one cause.  It isn't very likely that Visual Studio is actually running out of memory, the system might be running low on resources.  The desktop heap is one of them.  A simple reboot will fix that.

If this reoccurs, use Taskmgr.exe to try to find the processes that are hogging resources.  View + Select Columns, tick Handles, USER objects and GDI objects.  If it is Explorer then you have a misbehaving shell extension handler.


问:
Javascript sort algorithm for linked sections objects array
I have the following array of objects which need to be sorted in a special way:

```<code>var sections = [
    {begin:"test3", end:"test4"},
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
];
</code>```

All sections are linked together via sectionA.end == sectionB.begin so the result of the sort operation should be:

```<code>var sectionsSorted = [
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
    {begin:"test3", end:"test4"}
];
</code>```

I want to do this in the Array.prototype.sort() method. I realised that the beginning section could be found if the begin is not an end in any section but from there on I am lot. Has anybody an idea how to implement something like this?

I did a JSFiddle: https://jsfiddle.net/fxmnxh8L/1/

答:
try :

```<code>function compare(a,b) {
 if (a.end < b.end)
    return -1;
 if (a.end > b.end)
    return 1;
      }

sections.sort(compare);
</code>```

https://jsfiddle.net/Micio/Lu3wqt0v/1/

Body:
I have the following array of objects which need to be sorted in a special way:

var sections = [
    {begin:"test3", end:"test4"},
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
];

All sections are linked together via sectionA.end == sectionB.begin so the result of the sort operation should be:

var sectionsSorted = [
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
    {begin:"test3", end:"test4"}
];

I want to do this in the Array.prototype.sort() method. I realised that the beginning section could be found if the begin is not an end in any section but from there on I am lot. Has anybody an idea how to implement something like this?

I did a JSFiddle: https://jsfiddle.net/fxmnxh8L/1/

Body:
try :

function compare(a,b) {
 if (a.end < b.end)
    return -1;
 if (a.end > b.end)
    return 1;
      }

sections.sort(compare);

https://jsfiddle.net/Micio/Lu3wqt0v/1/


问:
Json POST request works in java but not PHP?
I have an odd problem that i cannot seem to solve at all. We have a rest service that is supposed to accept submission data as a JSON object.

I have been going round in circles using curl. The command works with any service off the corporate network, and any EXTERNAL one when i use the curl proxy option but nothing is accessible (get or post) on the internal network. I always get a "false" comming back  as response. Here is the PHP code:

```<code>$data_string =  "{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}";
$ch = curl_init('http://xxx.xxx.com/fashionnewssignup');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
//curl_setopt($ch, CURLOPT_PROXY, "http://proxy.xxxx.com");
//curl_setopt($ch, CURLOPT_PROXYPORT, "8080");
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, CRED);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);

//execute post
$result = curl_exec($ch);
echo "```";
var_dump( curl_getinfo($ch) ) . '
';
echo curl_errno($ch) . '
';
echo curl_error($ch) . '
';
//close connection
curl_close($ch);
var_dump ($result);
die;
```

<hr>

<h2>and it's output:</h2>

```array(26) {
  'url' =>
  string(59) "http://xxx.xxx.com/fashionnewssignup"
  'content_type' =>
  NULL
  'http_code' =>
  int(0)
  'header_size' =>
  int(0)
  'request_size' =>
  int(251)
  'filetime' =>
  int(-1)
  'ssl_verify_result' =>
  int(0)
  'redirect_count' =>
  int(0)
  'total_time' =>
  double(0.031)
  'namelookup_time' =>
  double(0)
  'connect_time' =>
  double(0.016)
  'pretransfer_time' =>
  double(0.016)
  'size_upload' =>
  double(0)
  'size_download' =>
  double(0)
  'speed_download' =>
  double(0)
  'speed_upload' =>
  double(0)
  'download_content_length' =>
  double(-1)
  'upload_content_length' =>
  double(-1)
  'starttransfer_time' =>
  double(0.031)
  'redirect_time' =>
  double(0)
  'redirect_url' =>
  string(0) ""
  'primary_ip' =>
  string(12) "XX.XX.XXX.12"
  'certinfo' =>
  array(0) {
  }
  'primary_port' =>
  int(1080)
  'local_ip' =>
  string(13) "XX.XX.XXX.196"
  'local_port' =>
  int(56107)
}
52
Empty reply from server
C:\xampp\htdocs\at\test.php:46:
bool(false)

Process finished with exit code 0
```

<hr>

<p>"Empty reply from server" 52 is what i get regardless of what URL i feed in. As i said above this code works fine off the network with other sites.</p>

<p>A git-bash curl gives this:</p>

```    curl -H "Content-Type: application/json" -X POST -d '{"fashionNewsSignups":[{"                                    corporateBrandId":0,"vendorId":null,"countryCode":"pt","languageCode":"pt","emai                                    l":"test@ytDessddefwwt.com","genderCode":0,"hasChildren":0,"zipcode":"12345"}]}'                                     http://xxx.xxx.com/fashionnewssignup
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   184    0     0  100   184      0   5935 --:--:-- --:--:-- --:--:-- 12266
curl: (52) Empty reply from server
```

<p><strong>The strange part is, when i try the same thing in JAVA on the same machine on the same network using this code, it works 100% fine, no proxy or anything required.</strong></p>

<p>This JAVA code works:</p>

```HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://xxx.xxx.com/fashionnewssignup");
    StringEntity params =new StringEntity("{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}");
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
    String s = response.getStatusLine()+" " + response.toString();
    System.out.println(s);
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}
```

Anyone know what i am doing wrong? The service i am trying to access is written in JAVA if that is important :/

答:
```<code>$data_string =  '{"fashionSignups":[{"corporateBrandId":0,"vendorId":null,"countryCode":"pt","languageCode":"pt","email":"test@ytDessddefwwt.com","genderCode":0,"hasChildren":0,"zipcode":"12345"}]}';

$data_string = json_decode($data_string,true);
</code>```

<p>$data_string is a string in your case, while your content-type is JSON
So the above code will convert your string to a JSON Object and it should solve your problem.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have an odd problem that i cannot seem to solve at all. We have a rest service that is supposed to accept submission data as a JSON object.

I have been going round in circles using curl. The command works with any service off the corporate network, and any EXTERNAL one when i use the curl proxy option but nothing is accessible (get or post) on the internal network. I always get a "false" comming back  as response. Here is the PHP code:

$data_string =  "{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}";
$ch = curl_init('http://xxx.xxx.com/fashionnewssignup');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
//curl_setopt($ch, CURLOPT_PROXY, "http://proxy.xxxx.com");
//curl_setopt($ch, CURLOPT_PROXYPORT, "8080");
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, CRED);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);

//execute post
$result = curl_exec($ch);
echo "
";
var_dump( curl_getinfo($ch) ) . '
';
echo curl_errno($ch) . '
';
echo curl_error($ch) . '
';
//close connection
curl_close($ch);
var_dump ($result);
die;

and it's output:

array(26) {
  'url' =>
  string(59) "http://xxx.xxx.com/fashionnewssignup"
  'content_type' =>
  NULL
  'http_code' =>
  int(0)
  'header_size' =>
  int(0)
  'request_size' =>
  int(251)
  'filetime' =>
  int(-1)
  'ssl_verify_result' =>
  int(0)
  'redirect_count' =>
  int(0)
  'total_time' =>
  double(0.031)
  'namelookup_time' =>
  double(0)
  'connect_time' =>
  double(0.016)
  'pretransfer_time' =>
  double(0.016)
  'size_upload' =>
  double(0)
  'size_download' =>
  double(0)
  'speed_download' =>
  double(0)
  'speed_upload' =>
  double(0)
  'download_content_length' =>
  double(-1)
  'upload_content_length' =>
  double(-1)
  'starttransfer_time' =>
  double(0.031)
  'redirect_time' =>
  double(0)
  'redirect_url' =>
  string(0) ""
  'primary_ip' =>
  string(12) "XX.XX.XXX.12"
  'certinfo' =>
  array(0) {
  }
  'primary_port' =>
  int(1080)
  'local_ip' =>
  string(13) "XX.XX.XXX.196"
  'local_port' =>
  int(56107)
}
52
Empty reply from server
C:\xampp\htdocs\at\test.php:46:
bool(false)

Process finished with exit code 0

"Empty reply from server" 52 is what i get regardless of what URL i feed in. As i said above this code works fine off the network with other sites.

A git-bash curl gives this:

    curl -H "Content-Type: application/json" -X POST -d '{"fashionNewsSignups":[{"                                    corporateBrandId":0,"vendorId":null,"countryCode":"pt","languageCode":"pt","emai                                    l":"test@ytDessddefwwt.com","genderCode":0,"hasChildren":0,"zipcode":"12345"}]}'                                     http://xxx.xxx.com/fashionnewssignup
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   184    0     0  100   184      0   5935 --:--:-- --:--:-- --:--:-- 12266
curl: (52) Empty reply from server

The strange part is, when i try the same thing in JAVA on the same machine on the same network using this code, it works 100% fine, no proxy or anything required.

This JAVA code works:

HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://xxx.xxx.com/fashionnewssignup");
    StringEntity params =new StringEntity("{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}");
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
    String s = response.getStatusLine()+" " + response.toString();
    System.out.println(s);
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}

Anyone know what i am doing wrong? The service i am trying to access is written in JAVA if that is important :/

Body:
$data_string =  '{"fashionSignups":[{"corporateBrandId":0,"vendorId":null,"countryCode":"pt","languageCode":"pt","email":"test@ytDessddefwwt.com","genderCode":0,"hasChildren":0,"zipcode":"12345"}]}';

$data_string = json_decode($data_string,true);

$data_string is a string in your case, while your content-type is JSON
So the above code will convert your string to a JSON Object and it should solve your problem.


问:
Installing kubernetes on localhost using LXD
I am trying to install kubernetes on localhost using LXD but facing issue. I am using conjure-up for this but on proceeding localhost option is not highlighted stating that LXD not found.

[Error]

I have installed LXD as per commands given. Do I need to provide path somewhere so that conjure-up finds the path or is there some other issue?

答:
Edit:  I had to sudo apt purge lxd first

Then
sudo apt upgrade

After installing lxd as suggested on conjure

sudo snap install lxd

/snap/bin/lxd init

Disabled IPV6 with the wizard

And then conjure-up

Don't forget to logout and login after adding the user to the group
(I actually did a reboot)


问:
Parsing JSON string with jsoncpp
I'm trying to parse a JSON string encoded with PHP and sent over TCP to a C++ client.

My JSON strings are like this:

```<code>{"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}}
</code>```

On the C++ client I'm using the jsoncpp libraries:

```<code>void decode()
{
    string text =     {"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}};
    Json::Value root;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( text, root );
    if ( !parsingSuccessful )
    {
        cout << "Error parsing the string" << endl;
    }
    const Json::Value mynames = root["name"];
    for ( int index = 0; index < mynames.size(); ++index )
    {
        cout << mynames[index] << endl;
    }
}
</code>```

The problem is that I'm not getting anything as output, not even the error about the parsing(if any).
Could you possibly help me to understand what I'm doing wrong ?

答:
Your problem is: there is no root["name"]. Your document should be like this:

```<code>{ "people": [{"id": 1, "name":"MIKE","surname":"TAYLOR"}, {"id": 2, "name":"TOM","surname":"JERRY"} ]}
</code>```

And your code like this:

```<code>void decode()
{
    string text ="{ \"people\": [{\"id\": 1, \"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, {\"id\": 2, \"name\":\"TOM\",\"surname\":\"JERRY\"} ]}";
    Json::Value root;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( text, root );
    if ( !parsingSuccessful )
    {
        cout << "Error parsing the string" << endl;
    }

    const Json::Value mynames = root["people"];

    for ( int index = 0; index < mynames.size(); ++index )
    {
        cout << mynames[index] << endl;
    }
}
</code>```

If you want to keep your data as is:

```<code>void decode()
{
  //string text ="{ \"people\": [{\"id\": 1, \"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, {\"id\": 2, \"name\":\"TOM\",\"surname\":\"JERRY\"} ]}";
  string text ="{ \"1\": {\"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, \"2\": {\"name\":\"TOM\",\"surname\":\"JERRY\"} }";
  Json::Value root;
  Json::Reader reader;
  bool parsingSuccessful = reader.parse( text, root );
  if ( !parsingSuccessful )
  {
    cout << "Error parsing the string" << endl;
  }

  for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ )
  {
    for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ )
    {
      cout << inner.key() << ": " << *inner << endl;
    }
  }
}
</code>```

Traverse the root object directly, using iterators (don't treat it as it was an array.

If Json::Reader doesn't work, try Json::CharReader instead:

```<code>void decode()
{
  string text ="{\"1\":{\"name\":\"MIKE\",\"surname\":\"TAYLOR\"},\"2\":{\"name\":\"TOM\",\"surname\":\"JERRY\"}}";

  Json::CharReaderBuilder builder;
  Json::CharReader * reader = builder.newCharReader();

  Json::Value root;
  string errors;

  bool parsingSuccessful = reader->parse(text.c_str(), text.c_str() + text.size(), &root, &errors);
  delete reader;

  if ( !parsingSuccessful )
  {
    cout << text << endl;
    cout << errors << endl;
  }

  for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ )
  {
    for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ )
    {
      cout << inner.key() << ": " << *inner << endl;
    }
  }
}
</code>```

Title: Parsing JSON string with jsoncpp

Body:
I'm trying to parse a JSON string encoded with PHP and sent over TCP to a C++ client.

My JSON strings are like this:

{"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}}

On the C++ client I'm using the jsoncpp libraries:

void decode()
{
    string text =     {"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}};
    Json::Value root;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( text, root );
    if ( !parsingSuccessful )
    {
        cout << "Error parsing the string" << endl;
    }
    const Json::Value mynames = root["name"];
    for ( int index = 0; index < mynames.size(); ++index )
    {
        cout << mynames[index] << endl;
    }
}

The problem is that I'm not getting anything as output, not even the error about the parsing(if any).
Could you possibly help me to understand what I'm doing wrong ?

Body:
Your problem is: there is no root["name"]. Your document should be like this:

{ "people": [{"id": 1, "name":"MIKE","surname":"TAYLOR"}, {"id": 2, "name":"TOM","surname":"JERRY"} ]}

And your code like this:

void decode()
{
    string text ="{ \"people\": [{\"id\": 1, \"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, {\"id\": 2, \"name\":\"TOM\",\"surname\":\"JERRY\"} ]}";
    Json::Value root;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( text, root );
    if ( !parsingSuccessful )
    {
        cout << "Error parsing the string" << endl;
    }

    const Json::Value mynames = root["people"];

    for ( int index = 0; index < mynames.size(); ++index )
    {
        cout << mynames[index] << endl;
    }
}

If you want to keep your data as is:

void decode()
{
  //string text ="{ \"people\": [{\"id\": 1, \"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, {\"id\": 2, \"name\":\"TOM\",\"surname\":\"JERRY\"} ]}";
  string text ="{ \"1\": {\"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, \"2\": {\"name\":\"TOM\",\"surname\":\"JERRY\"} }";
  Json::Value root;
  Json::Reader reader;
  bool parsingSuccessful = reader.parse( text, root );
  if ( !parsingSuccessful )
  {
    cout << "Error parsing the string" << endl;
  }

  for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ )
  {
    for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ )
    {
      cout << inner.key() << ": " << *inner << endl;
    }
  }
}

Traverse the root object directly, using iterators (don't treat it as it was an array.

If Json::Reader doesn't work, try Json::CharReader instead:

void decode()
{
  string text ="{\"1\":{\"name\":\"MIKE\",\"surname\":\"TAYLOR\"},\"2\":{\"name\":\"TOM\",\"surname\":\"JERRY\"}}";

  Json::CharReaderBuilder builder;
  Json::CharReader * reader = builder.newCharReader();

  Json::Value root;
  string errors;

  bool parsingSuccessful = reader->parse(text.c_str(), text.c_str() + text.size(), &root, &errors);
  delete reader;

  if ( !parsingSuccessful )
  {
    cout << text << endl;
    cout << errors << endl;
  }

  for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ )
  {
    for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ )
    {
      cout << inner.key() << ": " << *inner << endl;
    }
  }
}


问:
python re any unicode word except if it contains digits
I need to match a string of words such as "Miguel Tiago", but do not want strings that may contain numbers. For example I do not want strings such as "Miguel10 Tiago". Also all strings may contain unicode.

I can't simple do:

```<code>re.match(ur'^[a-zA-Z ]+',string,re.UNICODE)
</code>```

because for such case words with unicode such as 'ç' won't be recognized.

How can I use the rule [\w ]+ and exclude the digits?

答: I think the solution you are looking for is: (([^\W\d]+(?![\w\d])\s?)+)

Body:
I need to match a string of words such as "Miguel Tiago", but do not want strings that may contain numbers. For example I do not want strings such as "Miguel10 Tiago". Also all strings may contain unicode.

I can't simple do:

re.match(ur'^[a-zA-Z ]+',string,re.UNICODE)

because for such case words with unicode such as 'ç' won't be recognized.

How can I use the rule [\w ]+ and exclude the digits?


问:
How can I convert following code to a vue js code?
```<code>     <script type="text/javascript">
    navigator.geolocation.getCurrentPosition(success, error);

    function success(position) {

        var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

        $.getJSON(GEOCODING).done(function(location) {
            $('#country').html(location.results[0].address_components[5].long_name);
            $('#state').html(location.results[0].address_components[4].long_name);
            $('#city').html(location.results[0].address_components[2].long_name);
            $('#address').html(location.results[0].formatted_address);
            $('#latitude').html(position.coords.latitude);
            $('#longitude').html(position.coords.longitude);
        })
         $.ajax({
          url: 'post/filter/',
          data: {
            lat: position.coords.latitude,
            lon: position.coords.longitude,
          },
          type: "POST",
          dataType: 'json',

        });
    }

    function error(err) {
        console.log(err)
    }
</code>```

This is my code. I need to pass latitude and longitude as an ajax request to the server side to get values.. By using this code I am able to do so.

My vue js code is

```<code><div id="categorie">
  <div>{{vector.name}}</div>
</div>
<script>
categorie = new Vue({
    el: '#categorie',
    data: {
        vector: {},
    },
 methods: {

            search_category: function success(position) {
              navigator.geolocation.getCurrentPosition(success, error);
            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                $('#country').html(location.results[0].address_components[5].long_name);
                $('#state').html(location.results[0].address_components[4].long_name);
                $('#city').html(location.results[0].address_components[2].long_name);
                $('#address').html(location.results[0].formatted_address);
                $('#latitude').html(position.coords.latitude);
                $('#longitude').html(position.coords.longitude);
            })
             var filter = {};
             var self=this;
             filter['category'] = position.coords.latitude;
            filter['subcategory'] = position.coords.longitude;
            $.ajax({
              "url": "post/filter",
               data: filter,
              dataType: "JSON",
              type: "POST",
              success: function(e) {
                  self.vector = e.data;
                console.log(e);
              },

            });
          }
        }

})
</script>
</code>```

But when I use vue js code I am not able to send ajax request? Can any body please solve my issue Can someone please help me to solve this issue?

答:
The vue way of working with async request for your problem is shown below:

```<code>this.$http.get(GEOCODING).then(response=> {
   // here your data is in response
}).catch(error => {
   // TODO: handle your error here...
})
</code>```

But thing to remember, above feature is available in vue-resource package. I suggest you go through this very nice tutorial in @laracasts website: https://laracasts.com/series/learning-vue-step-by-step/episodes/11

Now I hope you'll have no further issues in async request in vue. And the conversion of your code in vue js is here in jsfiddle: https://jsfiddle.net/jcuytpx2/ Happy Coding :)

category = new Vue({
    el: '#category',
    data: () => ({
        vector: {},
        address: {
            country: '',
            state: '',
            city: '',
            address: ''
        },
    }),

    methods: {
        search_category(position) {
                navigator.geolocation.getCurrentPosition(position => {
                    var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
                    this.google_response(GEOCODING).then(response => {
                        this.address.country = response.results[0].address_components[5].long_name
                        this.address.state = response.results[0].address_components[4].long_name
                        this.address.city = response.results[0].address_components[2].long_name
                        this.address.address = response.results[0].formatted_address

                        let filter = {}
                        filter.category = response.coords.latitude
                        filter.subcategory = response.coords.longitude

                        /**** implement your methods here....
       this.$http.post('post/filter', filter).then(response => {
         this.vector = response.data
       }).catch(error => {
        // TODO: Handle error here
       })
       *****/
                    }).catch(error => {
                        // TODO: Handle error here
                    })
                })
            },

            google_response(GEOCODING) {
                return new Promise((resolve, reject) => {
                    this.$http.get(GEOCODING).then(response => {
                        resolve(JSON.parse(response.bodyText))
                    }).catch(error => {
                        reject(error)
                    })
                })
            }
    }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.min.js"></script>
<script src="https://unpkg.com/vue"></script>

<div id="category">
    <div>{{vector.name}}</div>
    <hr>
    <strong>
  Country: {{ address.country }}<br>
  State: {{ address.state }}<br>
  City: {{ address.city }}<br>
  Address: {{ address.address }}
 </strong>
    <hr>
    <button @click="search_category">
        Search
    </button>
</div></code>```

Body:
The vue way of working with async request for your problem is shown below:

this.$http.get(GEOCODING).then(response=> {
   // here your data is in response
}).catch(error => {
   // TODO: handle your error here...
})

But thing to remember, above feature is available in vue-resource package. I suggest you go through this very nice tutorial in @laracasts website: https://laracasts.com/series/learning-vue-step-by-step/episodes/11

Now I hope you'll have no further issues in async request in vue. And the conversion of your code in vue js is here in jsfiddle: https://jsfiddle.net/jcuytpx2/ Happy Coding :)

category = new Vue({
    el: '#category',
    data: () => ({
        vector: {},
        address: {
            country: '',
            state: '',
            city: '',
            address: ''
        },
    }),

    methods: {
        search_category(position) {
                navigator.geolocation.getCurrentPosition(position => {
                    var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
                    this.google_response(GEOCODING).then(response => {
                        this.address.country = response.results[0].address_components[5].long_name
                        this.address.state = response.results[0].address_components[4].long_name
                        this.address.city = response.results[0].address_components[2].long_name
                        this.address.address = response.results[0].formatted_address

                        let filter = {}
                        filter.category = response.coords.latitude
                        filter.subcategory = response.coords.longitude

                        /**** implement your methods here....
       this.$http.post('post/filter', filter).then(response => {
         this.vector = response.data
       }).catch(error => {
        // TODO: Handle error here
       })
       *****/
                    }).catch(error => {
                        // TODO: Handle error here
                    })
                })
            },

            google_response(GEOCODING) {
                return new Promise((resolve, reject) => {
                    this.$http.get(GEOCODING).then(response => {
                        resolve(JSON.parse(response.bodyText))
                    }).catch(error => {
                        reject(error)
                    })
                })
            }
    }

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.min.js"></script>
<script src="https://unpkg.com/vue"></script>

<div id="category">
    <div>{{vector.name}}</div>
    <hr>
    <strong>
  Country: {{ address.country }}<br>
  State: {{ address.state }}<br>
  City: {{ address.city }}<br>
  Address: {{ address.address }}
 </strong>
    <hr>
    <button @click="search_category">
        Search
    </button>
</div>


问:
Execution part of an infinite list in Haskell?
I'm a little confused about how exactly Haskell execution works on infinite lists. for example, consider below sum function :

```<code>sum (takeWhile (<10000) (filter odd (map (^2) [1..])))
</code>```

here the code for finding Sum of all odd squares that are smaller than 10000  and I know how these takewhile, filter, map functions work. my doubt is, here the map function is taking one element from the infinite list and squaring it and returning the list of squared elements to the filter function right? in that case it would run infinitely for squaring that infinite list of elements isn't it? or is it taking just one element squaring it and then returning to the filter?

答:
You can imagine a dialogue between functions.

GHCi asks sum to give a result. sum wakes up and asks takeWhile to give at least one element. Wakes up takeWhile and asks filter to give at least one element. Wakes up filter and asks map to give at least one element. Wakes up map and asks [1..] to give at least one element.

[1..] gives 1. map applies (^2) and gives (1^2). filter checks odd (1^2) and gives 1. takeWhile checks (1 < 10000) and gives 1. sum adds 1 to accumulator and continue asks takeWhile to give at least one element. And so on, until the takeWhile check is successful. Then sum returns the accumulator to GHCi.

Body:
I'm a little confused about how exactly Haskell execution works on infinite lists. for example, consider below sum function :

sum (takeWhile (<10000) (filter odd (map (^2) [1..])))

here the code for finding Sum of all odd squares that are smaller than 10000  and I know how these takewhile, filter, map functions work. my doubt is, here the map function is taking one element from the infinite list and squaring it and returning the list of squared elements to the filter function right? in that case it would run infinitely for squaring that infinite list of elements isn't it? or is it taking just one element squaring it and then returning to the filter?


问:
Angular 4+ httpClient best practice to use service
Hello I would like to know how to organize my code:

I have a simple user interface:

```<code>export interface User {
Account: string;
Name: string;
EMail: string;
PictureURL: string;
Department: string;
JobTitle: string;
Initials: string;
Skype: string;
Office: string;
MobileNumber: string;
DirectLine: string;
IsChecked: boolean;
IsIDTitleOnly: boolean;
ID: string;
CreatedAt: string;
CreatedBy: this;
ModifiedAt: string;
ModifiedBy: this;}
</code>```

I have a simple service to get my data:

```<code>  getCurrentUser(): Observable<User> {
const serviceUrl: string = environment.apiUrl + 'Users/Current';

return this.http.get(serviceUrl)
.map((res: User) => {
  return res;
});}
</code>```

And finally a simple component:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { User } from '../../interfaces/user';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
  user: User;

  constructor(
    private userService: UserService
  ) { }

  ngOnInit() {
    this.getCurrentUser()
  }

  getCurrentUser() {
    this
      .userService
      .getCurrentUser()
      .subscribe(
     res => { console.log(res); this.user = res },
     err => { console.log(err); }
  )
  }
}
</code>```

I do not have a class or constructor for my user should I always create a class or interface enough?

When I display my "user.Name" I have an error: "Cannot read property 'Name' of undefined" because the user did not have time to recover the data.

I would really like to know how to initialize my user properly, and to know if I need a class or not (if one day I have to create a new user).

Many thanks in advance

答:
It is preferable to have an interface or a class (shape) which describes the object. This is the one of the main features which Typescript gives us to make our code strict typed in its level.

What about the undefined error, you can check your field when showing in the markup. Just add ? mark after the field - user?.Name.

Body:
Hello I would like to know how to organize my code:

I have a simple user interface:

export interface User {
Account: string;
Name: string;
EMail: string;
PictureURL: string;
Department: string;
JobTitle: string;
Initials: string;
Skype: string;
Office: string;
MobileNumber: string;
DirectLine: string;
IsChecked: boolean;
IsIDTitleOnly: boolean;
ID: string;
CreatedAt: string;
CreatedBy: this;
ModifiedAt: string;
ModifiedBy: this;}

I have a simple service to get my data:

  getCurrentUser(): Observable<User> {
const serviceUrl: string = environment.apiUrl + 'Users/Current';

return this.http.get(serviceUrl)
.map((res: User) => {
  return res;
});}

And finally a simple component:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { User } from '../../interfaces/user';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
  user: User;

  constructor(
    private userService: UserService
  ) { }

  ngOnInit() {
    this.getCurrentUser()
  }

  getCurrentUser() {
    this
      .userService
      .getCurrentUser()
      .subscribe(
     res => { console.log(res); this.user = res },
     err => { console.log(err); }
  )
  }
}

I do not have a class or constructor for my user should I always create a class or interface enough?

When I display my "user.Name" I have an error: "Cannot read property 'Name' of undefined" because the user did not have time to recover the data.

I would really like to know how to initialize my user properly, and to know if I need a class or not (if one day I have to create a new user).

Many thanks in advance


问:
Partially clearing workspace in MATLAB
I have a question on the clear function in MATLAB. I would like to use the function to remove items from my workspace, in order to freeing up system memory. Just performing the code, I would run into an error otherwise.

Therefore, I'm clearing all the variables that are no longer required. This is especially true for variables used to calculate another one. Let's assume I'd have:

```<code>a = 2;
b = 3;
c = a + b;
</code>```

Thereafter, I would just continue to work with c. Is there an alternative to clear the workspace for a and b other than adding clear a; clear b; In other words, is there a function that allows to delete any variable that is just used to compute another variable?

答:
Not realy but you can utilise some of the features of clear, e.g.

```<code>a = 2;
b = 3;
c = a + b
clearvars -except c
</code>```

will leave just c

Or you could use similar names and wildcards in the clear statement

```<code>temp_a = 2;
temp_b = 3;
c = temp_a + temp_b
clearvars temp*
</code>```

Also its worth reminding you that you can do:

```<code>clearvars a b etc
</code>```

Title: Partially clearing workspace in MATLAB

Body:
I have a question on the clear function in MATLAB. I would like to use the function to remove items from my workspace, in order to freeing up system memory. Just performing the code, I would run into an error otherwise.

Therefore, I'm clearing all the variables that are no longer required. This is especially true for variables used to calculate another one. Let's assume I'd have:

a = 2;
b = 3;
c = a + b;

Thereafter, I would just continue to work with c. Is there an alternative to clear the workspace for a and b other than adding clear a; clear b; In other words, is there a function that allows to delete any variable that is just used to compute another variable?

Body:
Not realy but you can utilise some of the features of clear, e.g.

a = 2;
b = 3;
c = a + b
clearvars -except c

will leave just c

Or you could use similar names and wildcards in the clear statement

temp_a = 2;
temp_b = 3;
c = temp_a + temp_b
clearvars temp*

Also its worth reminding you that you can do:

clearvars a b etc


问:
How to add System.Data.SqlClient nuget package into .Net Portable (PCL)4.5 profile
I am writing a crossplatform (iOS and android) Xamarin app and I need a sql connection to my database. I found out that I need System.Data.SqlClient to achieve this. But when I try to add System.Data.SqlClient to my core project I get:

Could not install package 'System.Data.SqlClient 4.4.0'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

I get that apparently this .NETPortable version is compatible, but what is the solution to this? There must be a way to access a SQL database. Also I found that other posts asked to add System.Data first, but this package doesn't even show up in nuget.

答:
In case that you change your pcl project into .NET Standard you should be able to install this nuget package.

Follow this awesome snack pack!

In Visual Studio Preview there is template to create xamarin project using .netstandard. I can confirm that it works.


问:
How to undo git rm -rf dirname without a first commit?
I did:

```<code>git init
git add .
git rm -rf dirname
</code>```

Looking at other answsers, git reset --hard HEAD, git checkout -f and git reflog did not work, apparently because there is no HEAD to go back to, nor a commit to get the files back from.

Is there a way to get the files back?

答:
Warning: Running git prune without the -n option (1) will erase your unreachable data.

There may be a way, using git prune and git cat-file.

Running git prune -n will list which objects would be removed by pruning:

```<code>$ git prune -n
9cc84ea9b4d95453215d0c26489d6a78694e0bc6 blob
c315143703752ef4d11ca7d93f2c324872b2ebff blob
</code>```

Each line corresponds to a deleted file.

Now, using git cat-file, we are able to restore the contents of the removed file to a new file:

```<code>git cat-file -p 9cc84ea9b4d95453215d0c26489d6a78694e0bc6 > restored-filename
</code>```

(1) From the git prune docs:

NAME

 git-prune - Prune all unreachable objects from the object database

 OPTIONS

-n

--dry-run

Do not remove anything; just report what it would remove.

Body:
I did:

git init
git add .
git rm -rf dirname

Looking at other answsers, git reset --hard HEAD, git checkout -f and git reflog did not work, apparently because there is no HEAD to go back to, nor a commit to get the files back from.

Is there a way to get the files back?

Body:
Warning: Running git prune without the -n option (1) will erase your unreachable data.

There may be a way, using git prune and git cat-file.

Running git prune -n will list which objects would be removed by pruning:

$ git prune -n
9cc84ea9b4d95453215d0c26489d6a78694e0bc6 blob
c315143703752ef4d11ca7d93f2c324872b2ebff blob

Each line corresponds to a deleted file.

Now, using git cat-file, we are able to restore the contents of the removed file to a new file:

git cat-file -p 9cc84ea9b4d95453215d0c26489d6a78694e0bc6 > restored-filename

(1) From the git prune docs:

NAME

 git-prune - Prune all unreachable objects from the object database

 OPTIONS

-n

--dry-run

Do not remove anything; just report what it would remove.


问:
XmlSerializer and IEnumerable: Serialization possible w/o parameterless constructor: Bug?
In our project we extensivly use the XmlSerializer. By chance I found a class w/o a parameterless contructor. I thought this must break the serialization process but it did not.

By investigating this issue I found out, that the XmlSerializer behaves strange when serializing/deserializing an IEnumerable:

All elements of the enumerable are serialized

The class is required to implement an Add(object) method

It ignores all other properties that may be in this class.

It calls a getter with this property and reuses the returned instance for serialization (which allows the XmlSerializer to work w/o a parameterless constructor).

Please have a look at the example that follows. Intersting parts are ODD1, ODD2. Note that good5 and good6 are false, when I expected them to be true.

Is there a reason for this behaviour?

Can I make XmlSerializer reuse an instance returned by a property for deserialization when implementing IXmlSerializable by hand?

```<code>using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Test
{
    public static class Program
    {
        public static void Main()
        {
            HostingClass host = new HostingClass();

            host.AutomaticSerialization.StringProperty = "AUTO";
            host.SelfImplementedSerialization.StringProperty = "SELF";

            bool good1 = host.AutomaticSerialization.FromConstructor == "PARAMETER";
            bool good2 = host.SelfImplementedSerialization.FromConstructor == "PARAMETER";
            bool good3 = host.AutomaticSerialization.StringProperty == "AUTO";
            bool good4 = host.SelfImplementedSerialization.StringProperty == "SELF";

            XmlSerializer serializer = new XmlSerializer(typeof(HostingClass));

            using (StringWriter sw = new StringWriter())
            {
                serializer.Serialize(sw, host);

                using (StringReader sr = new StringReader(sw.ToString()))
                {
                    host = (HostingClass)serializer.Deserialize(sr);
                }
            }

            bool good5 = host.AutomaticSerialization.FromConstructor == null; //is false
            bool good6 = host.AutomaticSerialization.StringProperty == "AUTO"; //is false

            bool good7 = host.SelfImplementedSerialization.FromConstructor == null;
            bool good8 = host.SelfImplementedSerialization.StringProperty == "SELF";

        }
    }

    public class HostingClass
    {
        private SelfImplementedSerialization _selfImplementedSerialization;
        public SelfImplementedSerialization SelfImplementedSerialization
        {
            get
            {
                return _selfImplementedSerialization
                       ?? (_selfImplementedSerialization = new SelfImplementedSerialization("PARAMETER"));
            }
            set { _selfImplementedSerialization = value; }
        }

        private AutomaticSerialization _automaticSerialization;
        public AutomaticSerialization AutomaticSerialization
        {
            get
            {
                return _automaticSerialization
                       ?? (_automaticSerialization = new AutomaticSerialization("PARAMETER")); //the returned object is used while deserializing
            }
            set { _automaticSerialization = value; }
        }
    }

    public class SelfImplementedSerialization : IXmlSerializable, IEnumerable<int>
    {
        public SelfImplementedSerialization() { }
        public SelfImplementedSerialization(string parameter)
        {
            FromConstructor = parameter;
        }

        public string StringProperty { get; set; }
        [XmlIgnore]
        public string FromConstructor { get; set; }

        public void ReadXml(XmlReader reader)
        {
            reader.ReadStartElement();
            StringProperty = reader.ReadElementString("StringProperty");
            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("StringProperty", StringProperty);
        }

        public IEnumerator<int> GetEnumerator()
        {
            yield return 1;
            yield return 2;
        }

        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
        public XmlSchema GetSchema() { return null; }
    }

    public class AutomaticSerialization : IEnumerable<int>
    {
        //ODD1: Serialization possible w/o public parameterless constructor
        //public AutomaticSerialization() {}
        public AutomaticSerialization(string parameter)
        {
            FromConstructor = parameter;
        }

        //ODD2: Element not serialized, only the IEnumerable Interface is serialized
        [XmlElement("SP")]
        public string StringProperty { get; set; }
        [XmlIgnore]
        public string FromConstructor { get; set; }

        public IEnumerator<int> GetEnumerator()
        {
            yield return 1;
            yield return 2;
        }

        public void Add(object o)
        {
            //requirement of XmlSerializer when serializing IEnumerables
        }

        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    }
}
</code>```

答:
The reason for the behavior is that this is the way it has always worked.

From XmlSerializer class:

Note

The XmlSerializer gives special
  treatment to classes that implement
  IEnumerable or ICollection. A class
  that implements IEnumerable must
  implement a public Add method that
  takes a single parameter. The Add
  method's parameter must be of the same
  type as is returned from the Current
  property on the value returned from
  GetEnumerator, or one of that type's
  bases. A class that implements
  ICollection (such as CollectionBase)
  in addition to IEnumerable must have a
  public Item indexed property (indexer
  in C#) that takes an integer, and it
  must have a public Count property of
  type integer. The parameter to the Add
  method must be the same type as is
  returned from the Item property, or
  one of that type's bases. For classes
  that implement ICollection, values to
  be serialized are retrieved from the
  indexed Item property, not by calling
  GetEnumerator.

Body:
In our project we extensivly use the XmlSerializer. By chance I found a class w/o a parameterless contructor. I thought this must break the serialization process but it did not.

By investigating this issue I found out, that the XmlSerializer behaves strange when serializing/deserializing an IEnumerable:

All elements of the enumerable are serialized

The class is required to implement an Add(object) method

It ignores all other properties that may be in this class.

It calls a getter with this property and reuses the returned instance for serialization (which allows the XmlSerializer to work w/o a parameterless constructor).

Please have a look at the example that follows. Intersting parts are ODD1, ODD2. Note that good5 and good6 are false, when I expected them to be true.

Is there a reason for this behaviour?

Can I make XmlSerializer reuse an instance returned by a property for deserialization when implementing IXmlSerializable by hand?

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Test
{
    public static class Program
    {
        public static void Main()
        {
            HostingClass host = new HostingClass();

            host.AutomaticSerialization.StringProperty = "AUTO";
            host.SelfImplementedSerialization.StringProperty = "SELF";

            bool good1 = host.AutomaticSerialization.FromConstructor == "PARAMETER";
            bool good2 = host.SelfImplementedSerialization.FromConstructor == "PARAMETER";
            bool good3 = host.AutomaticSerialization.StringProperty == "AUTO";
            bool good4 = host.SelfImplementedSerialization.StringProperty == "SELF";

            XmlSerializer serializer = new XmlSerializer(typeof(HostingClass));

            using (StringWriter sw = new StringWriter())
            {
                serializer.Serialize(sw, host);

                using (StringReader sr = new StringReader(sw.ToString()))
                {
                    host = (HostingClass)serializer.Deserialize(sr);
                }
            }

            bool good5 = host.AutomaticSerialization.FromConstructor == null; //is false
            bool good6 = host.AutomaticSerialization.StringProperty == "AUTO"; //is false

            bool good7 = host.SelfImplementedSerialization.FromConstructor == null;
            bool good8 = host.SelfImplementedSerialization.StringProperty == "SELF";

        }
    }

    public class HostingClass
    {
        private SelfImplementedSerialization _selfImplementedSerialization;
        public SelfImplementedSerialization SelfImplementedSerialization
        {
            get
            {
                return _selfImplementedSerialization
                       ?? (_selfImplementedSerialization = new SelfImplementedSerialization("PARAMETER"));
            }
            set { _selfImplementedSerialization = value; }
        }

        private AutomaticSerialization _automaticSerialization;
        public AutomaticSerialization AutomaticSerialization
        {
            get
            {
                return _automaticSerialization
                       ?? (_automaticSerialization = new AutomaticSerialization("PARAMETER")); //the returned object is used while deserializing
            }
            set { _automaticSerialization = value; }
        }
    }

    public class SelfImplementedSerialization : IXmlSerializable, IEnumerable<int>
    {
        public SelfImplementedSerialization() { }
        public SelfImplementedSerialization(string parameter)
        {
            FromConstructor = parameter;
        }

        public string StringProperty { get; set; }
        [XmlIgnore]
        public string FromConstructor { get; set; }

        public void ReadXml(XmlReader reader)
        {
            reader.ReadStartElement();
            StringProperty = reader.ReadElementString("StringProperty");
            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("StringProperty", StringProperty);
        }

        public IEnumerator<int> GetEnumerator()
        {
            yield return 1;
            yield return 2;
        }

        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
        public XmlSchema GetSchema() { return null; }
    }

    public class AutomaticSerialization : IEnumerable<int>
    {
        //ODD1: Serialization possible w/o public parameterless constructor
        //public AutomaticSerialization() {}
        public AutomaticSerialization(string parameter)
        {
            FromConstructor = parameter;
        }

        //ODD2: Element not serialized, only the IEnumerable Interface is serialized
        [XmlElement("SP")]
        public string StringProperty { get; set; }
        [XmlIgnore]
        public string FromConstructor { get; set; }

        public IEnumerator<int> GetEnumerator()
        {
            yield return 1;
            yield return 2;
        }

        public void Add(object o)
        {
            //requirement of XmlSerializer when serializing IEnumerables
        }

        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    }
}