问:
Graphql Query Returning a null value (Apollo Server)
I created a mock programmatically for testing at my query but it only returns a null value what am i doing wrong. I am using the casual library for generating values for my mock

Here are my files:

index.js

```<code>   import express from 'express'
import bodyParser from 'body-parser'
import { graphqlExpress,graphiqlExpress } from 'graphql-server-express'
import { makeExecutableSchema } from 'graphql-tools'
import mock from './mock'
import schema from './schema'
const app = express()
const executableSchema = makeExecutableSchema({
    typeDefs: schema,
    mock
})

app.post(
    '/graphql',
    bodyParser.json(),
    graphqlExpress(() => ({
        schema: executableSchema
    }))
)

app.use('/graphiql',graphiqlExpress({
    endpointURL: '/graphql',
}))
app.listen(8080)
console.log("listening at 8080")
</code>```

schema.js

```<code>const schema = `
interface Novel {
    artist: String
    author: String
    chapters: [Chapter]
    description: String
    genre: [String]
    id: String
    image: String
    language: String
    modified: String!
    name: String!
    status: String
    tags: [String]
    type: String
    year: String
}

interface Chapter {
chapter: String!
volume: String!
content: String!
}

type NovelCrawler implements Novel{
    artist: String
    author: String
    chapters: [Chapter]
    description: String
    genre: [String]
    id: String
    image: String
    language: String
    modified: String!
    name: String!
    novelurl: String
    status: String
    tags: [String]
    type: String
    year: String
}

type ChapterCrawler implements Chapter {
    chapter: String!
    chapterurl: String
    content: String!
    novelurl: String
    volume: String!
}
`
const Query = `
type Query {
     novels: [Novel]
}
`
export default [schema, Query]
</code>```

mock.js

```<code>import casual from 'casual'
const genre = ['romance', 'comedy', 'action']
const Novel = () => ({
    artist: casual.name,
    author: casual.name,
    description: casual.sentences(3),
    genre: [casual.random_element(genre), casual.random_element(genre)],
    id: casual.url,
    image: 'sdfgrtw3wedfgb2345y675trfdvfbghdsfdssfd',
    language: casual.random_element(['chinese', 'japanese', 'korean']),
    modified: casual.date('YYYY-MM-DD'),
    name: casual.word,
    status: casual.random_element(['Completed', 'Ongoing']),
    tags: [],
    novelurl: casual.url,
    type: casual.random_element(['Web Novel', 'Light Novel']),
    year: casual.year
})

const Chapter = () => ({
    chapter: casual.integer(1, 50),
    chapterurl: casual.url,
    content: casual.sentences(10),
    novelurl: casual.url,
    volume: casual.integer(1, 5)
})

const arrNovel = []
const arrChapter = []
for (let x = 0; x < 20; ++x) {
    arrNovel.push(Novel())
    arrChapter.push(Chapter())
}

const mock = {
    // Query: { novels: () => ({}) },
    Novel: {
        __resolveType(obj, context, info) {
            return 'NovelCrawler'
        }
    },
    Chapter: {
        __resolveType(obj, context, info) {
            return 'ChapterCrawler'
        }
    },
    NovelCrawler: () => arrNovel,
    ChapterCrawler: () => arrChapter
}

export default mock
</code>```

When i run the following query:

```<code>{
  novels{
    description
  }
}
</code>```

it returns:

```<code>{
  "data": {
    "novels": null
  }
}
</code>```

so i tried:

```<code>{
 novels{
 ... on NovelCrawler{
  artist
    }
  }
 }
</code>```

this returns

```<code> {
  "errors": [
    {
      "message": "Unknown operation named \"null\"."
    }
  ]
}
</code>```

what am i doing wrong

答:
Thanks for providing complete code and examples. Here's a few notes to get you going in the right direction:

Make sure you are implementing mocks correctly. I think makeExecutableSchema used to accept a mocks option at one point, but now you have to use addMockFunctionsToSchema in conjunction with it to implement mocking. I would read Apollo's guide to mocking for detailed steps on how to do that.

graphqlExpress is actually middleware, so you should implement it with app.use instead of app.post. GraphQL Server can handle both POST and GET requests.

You probably don't need interfaces for what you're trying to do. An interface requires that every type that implements it also has the fields defined in the interface. They're used when two or more types share fields, which isn't the case here. I would suggest making Chapter a regular type and nesting it inside ChapterCrawler like below. Ditto for Novel.

```<code>type ChapterCrawler {
  chapter: Chapter!
  chapterurl: String
  novelurl: String
}
type Chapter {
  chapter: String!
  content: String!
  volume: String!
}
</code>```

If you go with the above method, you will need to eventually change your query to fetch [NovelCrawler] instead. Wait! Before making things more complicated and harder to debug, I would suggest mocking just Chapter and adding a query to get [Chapters] first. Once you have that working, you'll know you have the basic functionality down and can starting mocking and querying more complex data structures.

If you do need interfaces, make sure you get what function they serve and how to correctly implement them. This article may help clarify things.

Keep in mind makeExecutableSchema takes typeDefs and resolvers separately once you're no longer mocking everything.

Body:
I created a mock programmatically for testing at my query but it only returns a null value what am i doing wrong. I am using the casual library for generating values for my mock

Here are my files:

index.js

   import express from 'express'
import bodyParser from 'body-parser'
import { graphqlExpress,graphiqlExpress } from 'graphql-server-express'
import { makeExecutableSchema } from 'graphql-tools'
import mock from './mock'
import schema from './schema'
const app = express()
const executableSchema = makeExecutableSchema({
    typeDefs: schema,
    mock
})

app.post(
    '/graphql',
    bodyParser.json(),
    graphqlExpress(() => ({
        schema: executableSchema
    }))
)

app.use('/graphiql',graphiqlExpress({
    endpointURL: '/graphql',
}))
app.listen(8080)
console.log("listening at 8080")

schema.js

const schema = `
interface Novel {
    artist: String
    author: String
    chapters: [Chapter]
    description: String
    genre: [String]
    id: String
    image: String
    language: String
    modified: String!
    name: String!
    status: String
    tags: [String]
    type: String
    year: String
}

interface Chapter {
chapter: String!
volume: String!
content: String!
}

type NovelCrawler implements Novel{
    artist: String
    author: String
    chapters: [Chapter]
    description: String
    genre: [String]
    id: String
    image: String
    language: String
    modified: String!
    name: String!
    novelurl: String
    status: String
    tags: [String]
    type: String
    year: String
}

type ChapterCrawler implements Chapter {
    chapter: String!
    chapterurl: String
    content: String!
    novelurl: String
    volume: String!
}
`
const Query = `
type Query {
     novels: [Novel]
}
`
export default [schema, Query]

mock.js

import casual from 'casual'
const genre = ['romance', 'comedy', 'action']
const Novel = () => ({
    artist: casual.name,
    author: casual.name,
    description: casual.sentences(3),
    genre: [casual.random_element(genre), casual.random_element(genre)],
    id: casual.url,
    image: 'sdfgrtw3wedfgb2345y675trfdvfbghdsfdssfd',
    language: casual.random_element(['chinese', 'japanese', 'korean']),
    modified: casual.date('YYYY-MM-DD'),
    name: casual.word,
    status: casual.random_element(['Completed', 'Ongoing']),
    tags: [],
    novelurl: casual.url,
    type: casual.random_element(['Web Novel', 'Light Novel']),
    year: casual.year
})

const Chapter = () => ({
    chapter: casual.integer(1, 50),
    chapterurl: casual.url,
    content: casual.sentences(10),
    novelurl: casual.url,
    volume: casual.integer(1, 5)
})

const arrNovel = []
const arrChapter = []
for (let x = 0; x < 20; ++x) {
    arrNovel.push(Novel())
    arrChapter.push(Chapter())
}

const mock = {
    // Query: { novels: () => ({}) },
    Novel: {
        __resolveType(obj, context, info) {
            return 'NovelCrawler'
        }
    },
    Chapter: {
        __resolveType(obj, context, info) {
            return 'ChapterCrawler'
        }
    },
    NovelCrawler: () => arrNovel,
    ChapterCrawler: () => arrChapter
}

export default mock

When i run the following query:

{
  novels{
    description
  }
}

it returns:

{
  "data": {
    "novels": null
  }
}

so i tried:

{
 novels{
 ... on NovelCrawler{
  artist
    }
  }
 }

this returns

 {
  "errors": [
    {
      "message": "Unknown operation named \"null\"."
    }
  ]
}

what am i doing wrong

Body:
Thanks for providing complete code and examples. Here's a few notes to get you going in the right direction:

Make sure you are implementing mocks correctly. I think makeExecutableSchema used to accept a mocks option at one point, but now you have to use addMockFunctionsToSchema in conjunction with it to implement mocking. I would read Apollo's guide to mocking for detailed steps on how to do that.

graphqlExpress is actually middleware, so you should implement it with app.use instead of app.post. GraphQL Server can handle both POST and GET requests.

You probably don't need interfaces for what you're trying to do. An interface requires that every type that implements it also has the fields defined in the interface. They're used when two or more types share fields, which isn't the case here. I would suggest making Chapter a regular type and nesting it inside ChapterCrawler like below. Ditto for Novel.

type ChapterCrawler {
  chapter: Chapter!
  chapterurl: String
  novelurl: String
}
type Chapter {
  chapter: String!
  content: String!
  volume: String!
}

If you go with the above method, you will need to eventually change your query to fetch [NovelCrawler] instead. Wait! Before making things more complicated and harder to debug, I would suggest mocking just Chapter and adding a query to get [Chapters] first. Once you have that working, you'll know you have the basic functionality down and can starting mocking and querying more complex data structures.

If you do need interfaces, make sure you get what function they serve and how to correctly implement them. This article may help clarify things.

Keep in mind makeExecutableSchema takes typeDefs and resolvers separately once you're no longer mocking everything.


来源: stackexchange

问:
Property 'auth' does not exist on type 'AngularFireModule'
Im Using Angular 4 and Firebase to authentication. I'm getting the error " Property 'auth' does not exist on type 'AngularFireModule'."

The Code is as follows

```<code>import { AngularFireModule} from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css'],
 animations: [moveIn()],
 host: {'[@moveIn]': ''}
})

export class LoginComponent implements OnInit {
error: any;
constructor(public af: AngularFireModule,private router: Router) {
  this.af.auth.subscribe(auth => {
  if(auth) {
    this.router.navigateByUrl('/members');
  }
});

loginFb() {
this.af.auth.login({
  provider: AuthProviders.Facebook,
  method: AuthMethods.Popup,
}).then(
    (success) => {
    this.router.navigate(['/members']);
  }).catch(
    (err) => {
    this.error = err;
  })
  }
   }
</code>```

The version information :
    "@angular/router": "^4.0.0",

```<code>"angularfire2": "^4.0.0-rc.1",

"core-js": "^2.4.1",

"firebase": "^4.1.3",

"rxjs": "^5.1.0",

"zone.js": "^0.8.4"
</code>```

UPDATE:

This worked

```<code>constructor(public af: AngularFireAuth,private router: Router) {
      this.af.authState.subscribe(auth => {
      if(auth) {
        this.router.navigateByUrl('/members');
      }
</code>```

答:
For AngularFireAuth, you should import AngularFireAuthModule at your rootmodule

```<code>import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';

@NgModule({
  imports: [
    ...
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireDatabaseModule,
    AngularFireAuthModule,        // <------ mention here
  ]
})
export class AppModule { }
</code>```

then inject AngularFireAuth at your component

```<code>import { AngularFireAuth } from 'angularfire2/auth';

constructor(private auth: AngularFireAuth, ...
</code>```

use it like below:

```<code>this.auth.auth()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im Using Angular 4 and Firebase to authentication. I'm getting the error " Property 'auth' does not exist on type 'AngularFireModule'."

The Code is as follows

import { AngularFireModule} from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css'],
 animations: [moveIn()],
 host: {'[@moveIn]': ''}
})

export class LoginComponent implements OnInit {
error: any;
constructor(public af: AngularFireModule,private router: Router) {
  this.af.auth.subscribe(auth => {
  if(auth) {
    this.router.navigateByUrl('/members');
  }
});

loginFb() {
this.af.auth.login({
  provider: AuthProviders.Facebook,
  method: AuthMethods.Popup,
}).then(
    (success) => {
    this.router.navigate(['/members']);
  }).catch(
    (err) => {
    this.error = err;
  })
  }
   }

The version information :
    "@angular/router": "^4.0.0",

"angularfire2": "^4.0.0-rc.1",

"core-js": "^2.4.1",

"firebase": "^4.1.3",

"rxjs": "^5.1.0",

"zone.js": "^0.8.4"

UPDATE:

This worked

constructor(public af: AngularFireAuth,private router: Router) {
      this.af.authState.subscribe(auth => {
      if(auth) {
        this.router.navigateByUrl('/members');
      }

Body:
For AngularFireAuth, you should import AngularFireAuthModule at your rootmodule

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';

@NgModule({
  imports: [
    ...
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireDatabaseModule,
    AngularFireAuthModule,        // <------ mention here
  ]
})
export class AppModule { }

then inject AngularFireAuth at your component

import { AngularFireAuth } from 'angularfire2/auth';

constructor(private auth: AngularFireAuth, ...

use it like below:

this.auth.auth()


问:
composer.json error: "./composer.json" does not contain valid JSON
I made a composer.json script.

When I run sudo composer install, I get this error:

```<code>[Seld\JsonLint\ParsingException]
"./composer.json" does not contain valid JSON
Parse error on line 1:
"repositories": [    {        "t
--------------^
Expected one of: 'EOF', '}', ',', ']'
</code>```

Here is the JSON:

```<code>"repositories": [
    {
        "type":"package",
        "package": {
          "name": "AdamKyle/Aisis-Core",
          "version":"development",
          "source": {
              "url": "https://github.com/AdamKyle/Aisis-Core.git",
              "type": "git",
              "reference":"development"
            }
        }
    }
],
"require": {
    "AdamKyle/Aisis-Core": "development"
}
</code>```

How can I get a better description of how this JSON is wrong?

答:
Here you can use it like this. </p>

<p>Try with this it will helps you to recover your error. </p>

```<code>{
   "repositories": [{
     "type": "package",
     "package": {
        "name": "AdamKyle/Aisis-Core",
        "version": "development",
        "source": {
            "url": "https://github.com/AdamKyle/Aisis-Core.git",
            "type": "git",
            "reference": "development"
        }
    }
  }],
  "require": {
      "AdamKyle/Aisis-Core": "development"
  }
}
</code>```

Body:
I made a composer.json script.

When I run sudo composer install, I get this error:

[Seld\JsonLint\ParsingException]
"./composer.json" does not contain valid JSON
Parse error on line 1:
"repositories": [    {        "t
--------------^
Expected one of: 'EOF', '}', ',', ']'

Here is the JSON:

"repositories": [
    {
        "type":"package",
        "package": {
          "name": "AdamKyle/Aisis-Core",
          "version":"development",
          "source": {
              "url": "https://github.com/AdamKyle/Aisis-Core.git",
              "type": "git",
              "reference":"development"
            }
        }
    }
],
"require": {
    "AdamKyle/Aisis-Core": "development"
}

How can I get a better description of how this JSON is wrong?

Body:
Here you can use it like this.

Try with this it will helps you to recover your error.

{
   "repositories": [{
     "type": "package",
     "package": {
        "name": "AdamKyle/Aisis-Core",
        "version": "development",
        "source": {
            "url": "https://github.com/AdamKyle/Aisis-Core.git",
            "type": "git",
            "reference": "development"
        }
    }
  }],
  "require": {
      "AdamKyle/Aisis-Core": "development"
  }
}


问:
Find the minimum value in golang?
In the language there is a minimum function https://golang.org/pkg/math/#Min But what if I have more than 2 numbers? I must to write a manual comparison in a for loop, or is there another way? The numbers are in the slice.</p>

答:
No, there isn't any better way than looping. Not only is it cleaner than any other approach, it's also the fastest.

```<code>values := []int{4, 20, 0, -11, -10}

min := values[0]
for _, v := range values {
        if (v < min) {
            min = v
        }
}

fmt.Println(min)
</code>```

EDIT

Since there has been some discussion in the comments about error handling and how to handle empty slices, here is a basic function that determines the minimum value. Remember to import errors.

```<code>func Min(values []int) (min int, e error) {
    if len(values) == 0 {
        return 0, errors.New("Cannot detect a minimum value in an empty slice")
    }

    min = values[0]
    for _, v := range values {
            if (v < min) {
                min = v
            }
    }

    return min, nil
}
</code>```

Title: Find the minimum value in golang?

Body:
No, there isn't any better way than looping. Not only is it cleaner than any other approach, it's also the fastest.

values := []int{4, 20, 0, -11, -10}

min := values[0]
for _, v := range values {
        if (v < min) {
            min = v
        }
}

fmt.Println(min)

EDIT

Since there has been some discussion in the comments about error handling and how to handle empty slices, here is a basic function that determines the minimum value. Remember to import errors.

func Min(values []int) (min int, e error) {
    if len(values) == 0 {
        return 0, errors.New("Cannot detect a minimum value in an empty slice")
    }

    min = values[0]
    for _, v := range values {
            if (v < min) {
                min = v
            }
    }

    return min, nil
}


问:
Spring Boot ModelAndView - cannot update value to Model
I am trying to create a form with 3 fields within the class LoginForm: usuario, senha, msgLogin.
I receive the fields usuário and senha from the input boxes and then I try to redirect to the same page with the same fields plus the field MsgLogin. But I've not been able to update the msgLogin field and I don't understand why.
These are the code:

HTML:

```<code><form id="frmLogin" class="form col-md-12" action="#" th:action="@{/login}" th:object="${loginForm}" method="post">
        <div class="form-group">
            <label for="usuario" class="col-md-1">Usuário: </label>
            <input type="text" id="usuario" placeholder="Email" th:field="*{usuario}"/>
        </div>

        <div class="form-group">
            <label for="senha" class="col-md-1">Senha: </label>
            <input type="password" id="senha" placeholder="senha" th:field="*{senha}"/>
        </div>

        <div class="row">
            <button id="entrar">Entrar</button>
        </div>

    <div class="row">
        <div id="msgLogin"></div>
        <p th:text="${loginForm.msgLogin}" />
    </div>
</form>
</code>```

The Controller:

```<code>@RequestMapping("/")
public String init(@ModelAttribute LoginForm loginForm) {
    Logger.getAnonymousLogger().info("Tela Inicial.");
    return "home";
}

@PostMapping("/login")
public ModelAndView entrar(LoginForm loginForm) throws IOException {
    Logger.getAnonymousLogger().info("Entrando no Internet Banking.");

    service.login(usuario, senha);

    ModelMap model = new ModelMap();
    loginForm.setMsgLogin("I want to update that value!");
    model.addAttribute("loginForm", loginForm);
    return new ModelAndView("redirect:/", model);
}
</code>```

Class using Lombok:

```<code>@Getter
@Setter
public class LoginForm {

    private String usuario;

    private String senha;

    private String msgLogin;

}
</code>```

答: In your Controller, change the last line in your entrar method to: return new ModelAndView("/login", model);

Body:
I am trying to create a form with 3 fields within the class LoginForm: usuario, senha, msgLogin.
I receive the fields usuário and senha from the input boxes and then I try to redirect to the same page with the same fields plus the field MsgLogin. But I've not been able to update the msgLogin field and I don't understand why.
These are the code:

HTML:

<form id="frmLogin" class="form col-md-12" action="#" th:action="@{/login}" th:object="${loginForm}" method="post">

            Usuário:
            <input type="text" id="usuario" placeholder="Email" th:field="*{usuario}"/>

            Senha:
            <input type="password" id="senha" placeholder="senha" th:field="*{senha}"/>

            <button id="entrar">Entrar</button>

</form>

The Controller:

@RequestMapping("/")
public String init(@ModelAttribute LoginForm loginForm) {
    Logger.getAnonymousLogger().info("Tela Inicial.");
    return "home";
}

@PostMapping("/login")
public ModelAndView entrar(LoginForm loginForm) throws IOException {
    Logger.getAnonymousLogger().info("Entrando no Internet Banking.");

    service.login(usuario, senha);

    ModelMap model = new ModelMap();
    loginForm.setMsgLogin("I want to update that value!");
    model.addAttribute("loginForm", loginForm);
    return new ModelAndView("redirect:/", model);
}

Class using Lombok:

@Getter
@Setter
public class LoginForm {

    private String usuario;

    private String senha;

    private String msgLogin;

}


问:
Scatter plot with hues in matplotlib
i have a dataset in the form of

I want to create a scatter plot between x and y, colored by country in matplotlib.
Please help.

答:
Solving this in Altair.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

cat = ["US"] *5 + ["UK"]*4
x = np.append(np.arange(1,6), np.arange(2.5,4.1,0.5))
y = np.random.randint(12,24, size=len(cat))
df = pd.DataFrame({"cat":cat, "x":x, "y":y})

from altair import *
Chart(df).mark_point().encode(x='x', y='y', color='cat').configure_cell(width=200, height=150)
</code>```

Title: Scatter plot with hues in matplotlib

Body:
Solving this in Altair.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

cat = ["US"] *5 + ["UK"]*4
x = np.append(np.arange(1,6), np.arange(2.5,4.1,0.5))
y = np.random.randint(12,24, size=len(cat))
df = pd.DataFrame({"cat":cat, "x":x, "y":y})

from altair import *
Chart(df).mark_point().encode(x='x', y='y', color='cat').configure_cell(width=200, height=150)


问:
Take input in an infinte loop in c
I am writing a C program to blink LED for Raspberry Pi. Its like (i) Blink LED (2) Stop blinking it.

Now while the LED is blinking, if I press 2 it should stop blinking. How to do it ?

If I include scanf inside the code will stop blinking.

```<code>while(1)
{
 printf("Enter a command \n 1.Blink Led\n 2. Stop blinking\n");
 scanf("%d",&choice);
if(choice==1)
    for (;;)
    {
        digitalWrite (LED, HIGH) ;  // On
        delay (500) ;               // mS
        digitalWrite (LED, LOW) ;   // Off
        delay (500) ;
        // If i press 2 the led should stop blinking
  }

else if(choice==2){
 digitalWrite (LED, LOW) ;
}
</code>```

答:
if you don't want to interrupt the Blinking you should try to run the blinking in a parallel process using pthread_t.
i really want to give you the code but i'm not on my PC at the moment.

Title: Take input in an infinte loop in c

Body:
I am writing a C program to blink LED for Raspberry Pi. Its like (i) Blink LED (2) Stop blinking it.

Now while the LED is blinking, if I press 2 it should stop blinking. How to do it ?

If I include scanf inside the code will stop blinking.

while(1)
{
 printf("Enter a command \n 1.Blink Led\n 2. Stop blinking\n");
 scanf("%d",&choice);
if(choice==1)
    for (;;)
    {
        digitalWrite (LED, HIGH) ;  // On
        delay (500) ;               // mS
        digitalWrite (LED, LOW) ;   // Off
        delay (500) ;
        // If i press 2 the led should stop blinking
  }

else if(choice==2){
 digitalWrite (LED, LOW) ;
}


问:
How to sync sqlite database with mysql database other than creating a web service
Any help regarding sync sqlite database with mysql database other than using web service.</p>

答:
Your question is not clear to me.
If you are trying to sync between client and server then you can use android "Sync Adapter"

https://developer.android.com/training/sync-adapters/index.html

Please tell more about what you want exactly for clear answer.


问:
back to back or gates with object comparisons. Confusion
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)</p>

```<code>function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

答:
Because you are returning .before the second statement execute

function deepEqual(a, b) {
  if (a === b) {
    //return true;
  }

  if (a == null || typeof a != "object" ||
    b == null || typeof b != "object") {
    return false;
  }
}
var c = null;
console.log(deepEqual(c, c));```

Body:
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true


问:
File_get_content and CURL is not working, showing error of HTTP/1.1 400 BAD_REQUEST
File get content and CRUL is not working on this link: http://xxx?text=I love my country.

If I put same URL on browser then It works.

Here is my code for File get content and CRUL

File get content

```<code>$result =   file_get_contents("http://xxxx?text=I love my country");
print_r($result);
</code>```

CURL

```<code>$url = "http://xxx?text=I love my country";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
print_r(data);
</code>```

I also check file get contents on other URLs like

```<code>$result =   file_get_contents("http://www.google.com/");
</code>```

and It is working fine on other URLs.

Is there is any other way from file get content and CURL to solve this issue?

答:
Try this.

```<code><?php
    $result = file_get_contents(str_replace(' ','+',"http://apidemo.theysay.io/api/v1/sentiment?text=I love my country"));
    print_r($result);
?>
</code>```

You have to use + or %20 to replace with blank space from url.

Or just use the following to encode url

```<code><?php
    $result = file_get_contents("http://apidemo.theysay.io/api/v1/sentiment?text=".urlencode("I love my country"));
    print_r($result);
?>
</code>```

Body:
File get content and CRUL is not working on this link: http://xxx?text=I love my country.

If I put same URL on browser then It works.

Here is my code for File get content and CRUL

File get content

$result =   file_get_contents("http://xxxx?text=I love my country");
print_r($result);

CURL

$url = "http://xxx?text=I love my country";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
print_r(data);

I also check file get contents on other URLs like

$result =   file_get_contents("http://www.google.com/");

and It is working fine on other URLs.

Is there is any other way from file get content and CURL to solve this issue?

Body:
Try this.

<?php
    $result = file_get_contents(str_replace(' ','+',"http://apidemo.theysay.io/api/v1/sentiment?text=I love my country"));
    print_r($result);
?>

You have to use + or %20 to replace with blank space from url.

Or just use the following to encode url

<?php
    $result = file_get_contents("http://apidemo.theysay.io/api/v1/sentiment?text=".urlencode("I love my country"));
    print_r($result);
?>


问:
How to access id from JavaScript code and pass it to other function
Here is my JavaScript code, i want to access id from this code and pass to the function

```<code>function register_popup(id,name,msg)
{
    for(var iii = 0; iii < popups.length; iii++)
    {
        //already registered. Bring it to front.
        if(id == popups[iii])
        {
            Array.remove(popups, iii);
            popups.unshift(id);
            calculate_popups();
            return;
        }
    }
    var element = '<div class="msg_box" style="right:290px" id="'+ id +'">';
        element = element + '<div class="msg_head">'+ id +'';
        element = element + '<div class="close"><a href="javascript:close_popup(\''+ id +'\');">✕</a></div></div>';
        element = element + '<div class="id"><a href="javascript:getchat(\''+ id +'\');"></a></div>';
        element = element +'<div class="msg_wrap"><div class="msg_body" class="msg-wgt-body" ><ul id="chatlog"></ul>'+ msg+'<div class="msg_push" id="textmesage">dg</div></div><div class="msg_footer" ><textarea id="myTextArea" class="msg_input"  rows="4" onkeypress="PushMessage(event , this);"+"\n">  </textarea></div></div>';

    document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
    popups.unshift(id);
    calculate_popups();
}
</code>```

I want to get id from this function add pass it to this function I am new in JavaScript kindly help me to solve this problem.
Here is my function

```<code>function getchat(id)
{
    alert("function reached to the getchat");
}
</code>```

答:
To execute function from the html you can use onclick rather than href

```<code>function register_popup(id,name,msg)
{
  for(var iii = 0; iii < popups.length; iii++)
   {
     //already registered. Bring it to front.
     if(id == popups[iii])
       {
         Array.remove(popups, iii);
         popups.unshift(id);
         calculate_popups();
         return;
        }
   }
    var element = '<div class="msg_box" style="right:290px" id="'+ id +'">';
        element = element + '<div class="msg_head">'+ id +'';
        element = element + '<div class="close"><a onclick="close_popup(\''+ id +'\');">✕</a></div></div>';
         element = element + '<div class="id"><a onclick="getchat(\''+ id +'\');"></a></div>';
        element = element +'<div class="msg_wrap"><div class="msg_body" class="msg-wgt-body" ><ul id="chatlog"></ul>'+ msg+'<div class="msg_push" id="textmesage">dg</div></div><div class="msg_footer" ><textarea id="myTextArea" class="msg_input"  rows="4" onkeypress="PushMessage(event , this);"+"\n">  </textarea></div></div>';

    document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
    popups.unshift(id);
    calculate_popups();
}
</code>```

Body:
Here is my JavaScript code, i want to access id from this code and pass to the function

function register_popup(id,name,msg)
{
    for(var iii = 0; iii < popups.length; iii++)
    {
        //already registered. Bring it to front.
        if(id == popups[iii])
        {
            Array.remove(popups, iii);
            popups.unshift(id);
            calculate_popups();
            return;
        }
    }
    var element = '
';
        element = element + '
'+ id +'';
        element = element + '
✕

';
        element = element + '

';
        element = element +'

'+ msg+'
dg

<textarea id="myTextArea" class="msg_input"  rows="4" onkeypress="PushMessage(event , this);"+"\n">  </textarea>

';

    document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
    popups.unshift(id);
    calculate_popups();
}

I want to get id from this function add pass it to this function I am new in JavaScript kindly help me to solve this problem.
Here is my function

function getchat(id)
{
    alert("function reached to the getchat");
}

Body:
To execute function from the html you can use onclick rather than href

function register_popup(id,name,msg)
{
  for(var iii = 0; iii < popups.length; iii++)
   {
     //already registered. Bring it to front.
     if(id == popups[iii])
       {
         Array.remove(popups, iii);
         popups.unshift(id);
         calculate_popups();
         return;
        }
   }
    var element = '<div class="msg_box" style="right:290px" id="'+ id +'">';
        element = element + '<div class="msg_head">'+ id +'';
        element = element + '<div class="close"><a onclick="close_popup(\''+ id +'\');">&#10005;</a></div></div>';
         element = element + '<div class="id"><a onclick="getchat(\''+ id +'\');"></a></div>';
        element = element +'<div class="msg_wrap"><div class="msg_body" class="msg-wgt-body" ><ul id="chatlog"></ul>'+ msg+'<div class="msg_push" id="textmesage">dg</div></div><div class="msg_footer" ><textarea id="myTextArea" class="msg_input"  rows="4" onkeypress="PushMessage(event , this);"+"\n">  </textarea></div></div>';

    document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
    popups.unshift(id);
    calculate_popups();
}


问:
Will there be efficiency issue if access to keyChain frequently?
I have a tableView that row height needs to adjust dynamically according to the value stored in keyChain, so comes the problem.

Just wondering how to verify it quantitatly.

答: Its better to load all values ONCE, ie., store in memory.


问:
Troubleshooting ssh key for gitlab clone/push/pull
I've tried following solutions, so I did generated new ssh key for my gitlab account, when I do ssh -v git@gitlab.com I've got Permissions denied (publickey)..

Second solution is Working with non-default SSH key pair paths, so I've generated new key for that and my ~/.ssh/config is looking like this

```<code>  # GitLab.com server
  Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/id_rsa_gitlab.pub
</code>```

Both key's are added to my gitlab account, and when I try to troubleshoot ssh with:
ssh -i ~/.ssh/id_rsa_gitlab.pub -p 122 git@gitlab.com I've got nothing, literally when I type that to the terminal nothing is happening, and when I type shh -vvv git@gitlab.com the result is this:

```<code>  OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/petar/.ssh/config
debug1: /home/petar/.ssh/config line 2: Applying options for gitlab.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to gitlab.com:22 as 'git'
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:4
debug3: load_hostkeys: loaded 1 keys from 52.167.219.168
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/petar/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/petar/.ssh/id_rsa_gitlab.pub (0x562dd6bb8c80), explicit, agent
debug2: key: ppilipovic84@gmail.com (0x562dd6bbde10), agent
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/petar/.ssh/id_rsa_gitlab.pub
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: ppilipovic84@gmail.com
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

Can someone please explain me how to fix this?

答:
As @Jakuje suggested I was making a mistake in IdentityFile, but also I didn't know that this gitlab is staged on a private server so, if you want to clone a repository from private gitlab you need to do this

git clone git@ip_address_of_the_server:SomeName/ProjectName.git and you will be able to successfully clone the repository, but you first need to add ssh key to your gitlab profile.

You can also git clone it using http, then you need to do this

http://server_ip_address/SomeName/ProjectName.git, and you will be prompt for your username and password.

ContentLicense: CC BY-SA 4.0

Body:
I've tried following solutions, so I did generated new ssh key for my gitlab account, when I do ssh -v git@gitlab.com I've got Permissions denied (publickey)..

Second solution is Working with non-default SSH key pair paths, so I've generated new key for that and my ~/.ssh/config is looking like this

  # GitLab.com server
  Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/id_rsa_gitlab.pub

Both key's are added to my gitlab account, and when I try to troubleshoot ssh with:
ssh -i ~/.ssh/id_rsa_gitlab.pub -p 122 git@gitlab.com I've got nothing, literally when I type that to the terminal nothing is happening, and when I type shh -vvv git@gitlab.com the result is this:

  OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/petar/.ssh/config
debug1: /home/petar/.ssh/config line 2: Applying options for gitlab.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to gitlab.com:22 as 'git'
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:4
debug3: load_hostkeys: loaded 1 keys from 52.167.219.168
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/petar/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/petar/.ssh/id_rsa_gitlab.pub (0x562dd6bb8c80), explicit, agent
debug2: key: ppilipovic84@gmail.com (0x562dd6bbde10), agent
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/petar/.ssh/id_rsa_gitlab.pub
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: ppilipovic84@gmail.com
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

Can someone please explain me how to fix this?


问:
Transform XML file using Tokenizer in VSO
In my cloud app service , I want to pass values to a XML file using release variables during deployment in VSO. The idea is to pass different values to the xml based on the environment its being deployed to.

I have couple questions about that,

Is the tokenize task in VSO only applicable for web.config transformation ?

If tokenizing a non web.config file is a possibility then ,how do I unpack CsPkg file to replace the transformed xml file?

In my release I am using Azure cloud service deployment step to publish csfg to azure.

答:
No, there are many tokenize tasks, such as Replace Tokens, Tokenizer, you can use them to do it with other files.

Staring from Windows Azure SDK 1.5, the CsPkg file is the unencrypted package file, which you can unzip and visualize it contents. However it will throw FileFormatException during deploy if you change the file(s) and package (zip) the folders again.

So, I recommend that you can create the package after tokenize task (per to environment) during the release process. For this way, you need to publish source files to artifact during the build process.


问:
Matplotlib scatter color by categorical factors
I have a basic scatter where the x and y are float. But I want to change the color of the marker based on a third categorical variable. The categorical variable is in a string form. This seems to cause an issue.

To use the iris dataset- here is the code I think I would use:

```<code>#Scatter of Petal
x=df['Petal Length']
y=df['Petal Width']
z=df['Species']
plt.scatter(x, y, c=z, s=15, cmap='hot')
plt.xlabel('Petal Width')
plt.ylabel('Petal Length')
plt.title('Petal Width vs Length')
</code>```

But I get an error that: could not convert string to float: iris-setosa

Do I have to change the categorical variable to a numeric one before I run, or is there something I can do with the data in its current format?

Thanks

update: the entire traceback is:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-47-d67ee3bffc3b> in <module>()
      3 y=df['Petal Width']
      4 z=df['Species']
----> 5 plt.scatter(x, y, c=z, s=15, cmap='hot')
      6 plt.xlabel('Petal Width')
      7 plt.ylabel('Petal Length')

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, hold, **kwargs)
   3198         ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   3199                          vmin=vmin, vmax=vmax, alpha=alpha,
-> 3200                          linewidths=linewidths, verts=verts, **kwargs)
   3201         draw_if_interactive()
   3202     finally:

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, **kwargs)
   3605
   3606         if c_is_stringy:
-> 3607             colors = mcolors.colorConverter.to_rgba_array(c, alpha)
   3608         else:
   3609             # The inherent ambiguity is resolved in favor of color

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba_array(self, c, alpha)
    420             result = np.zeros((nc, 4), dtype=np.float)
    421             for i, cc in enumerate(c):
--> 422                 result[i] = self.to_rgba(cc, alpha)
    423             return result
    424

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba(self, arg, alpha)
    374         except (TypeError, ValueError) as exc:
    375             raise ValueError(
--> 376                 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
    377
    378     def to_rgba_array(self, c, alpha=None):

ValueError: to_rgba: Invalid rgba arg "Iris-setosa"
to_rgb: Invalid rgb arg "Iris-setosa"
could not convert string to float: iris-setosa
</code>```

答:
Altair should be a breeze here.

```<code>from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')
</code>```

Body:
I have a basic scatter where the x and y are float. But I want to change the color of the marker based on a third categorical variable. The categorical variable is in a string form. This seems to cause an issue.

To use the iris dataset- here is the code I think I would use:

#Scatter of Petal
x=df['Petal Length']
y=df['Petal Width']
z=df['Species']
plt.scatter(x, y, c=z, s=15, cmap='hot')
plt.xlabel('Petal Width')
plt.ylabel('Petal Length')
plt.title('Petal Width vs Length')

But I get an error that: could not convert string to float: iris-setosa

Do I have to change the categorical variable to a numeric one before I run, or is there something I can do with the data in its current format?

Thanks

update: the entire traceback is:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-47-d67ee3bffc3b> in <module>()
      3 y=df['Petal Width']
      4 z=df['Species']
----> 5 plt.scatter(x, y, c=z, s=15, cmap='hot')
      6 plt.xlabel('Petal Width')
      7 plt.ylabel('Petal Length')

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, hold, **kwargs)
   3198         ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   3199                          vmin=vmin, vmax=vmax, alpha=alpha,
-> 3200                          linewidths=linewidths, verts=verts, **kwargs)
   3201         draw_if_interactive()
   3202     finally:

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, **kwargs)
   3605
   3606         if c_is_stringy:
-> 3607             colors = mcolors.colorConverter.to_rgba_array(c, alpha)
   3608         else:
   3609             # The inherent ambiguity is resolved in favor of color

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba_array(self, c, alpha)
    420             result = np.zeros((nc, 4), dtype=np.float)
    421             for i, cc in enumerate(c):
--> 422                 result[i] = self.to_rgba(cc, alpha)
    423             return result
    424

/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba(self, arg, alpha)
    374         except (TypeError, ValueError) as exc:
    375             raise ValueError(
--> 376                 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
    377
    378     def to_rgba_array(self, c, alpha=None):

ValueError: to_rgba: Invalid rgba arg "Iris-setosa"
to_rgb: Invalid rgb arg "Iris-setosa"
could not convert string to float: iris-setosa

Body:
Altair should be a breeze here.

from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')


问:
Yii2 calling javascript function at another file
I have a js file and a index file which are located in the same folder. This is my form. I have already register the script already too.

```<code>$this->registerJs($this->render('script.js'), \yii\web\VIEW::POS_READY);

<?php $form = ActiveForm::begin(); ?>
<div class="booth">
    <video id="video" width="400" height="300"></video>
    <a href="#" id="capture" class="button">Take Photo</a>
    <canvas id="canvas" width="400" height="300"></canvas>
</div>

<div class="form-group">
       <?= Html::button('Save',['class'=>'btn btn-primary','onclick'=>'saveimage();']) ?>
</div>

 <?php ActiveForm::end(); ?>
</code>```

This is the function inside the js file.

```<code>function saveimage()
{
    var csrfToken = $('meta[name="csrf-token"]').attr("content");

    console.log(123);

    })*/
}
</code>```

When I clicked my button is show error Uncaught Reference Error: saveimage is not defined? Its there anyway to call the function?

I tried 'onclick'=> 'js:saveimage()' too, but still not working.

答:
Try:

```<code>$this->registerJs(
    "function saveimage()
     {
        var csrfToken = $('meta[name="csrf-token"]').attr("content");

        console.log(123);

     }",
    \yii\web\VIEW::POS_READY,
    'my-button-handler'
);
</code>```

Or alternatively, If you want to use a separate js file you can use below syntax:

```<code>$this->registerJsFile(
    '@web/js/script.js',
    ['depends' => [\yii\web\JqueryAsset::className()]]
);
</code>```

When working with the yii\web\View object you can dynamically register
  frontend scripts. There are two dedicated methods for this:

1) registerJs() for inline scripts

2) registerJsFile() for external scripts

For more details refer to the link.

Body:
I have a js file and a index file which are located in the same folder. This is my form. I have already register the script already too.

$this->registerJs($this->render('script.js'), \yii\web\VIEW::POS_READY);

<?php $form = ActiveForm::begin(); ?>

    <video id="video" width="400" height="300"></video>
    Take Photo
    <canvas id="canvas" width="400" height="300"></canvas>

       <?= Html::button('Save',['class'=>'btn btn-primary','onclick'=>'saveimage();']) ?>

 <?php ActiveForm::end(); ?>

This is the function inside the js file.

function saveimage()
{
    var csrfToken = $('meta[name="csrf-token"]').attr("content");

    console.log(123);

    })*/
}

When I clicked my button is show error Uncaught Reference Error: saveimage is not defined? Its there anyway to call the function?

I tried 'onclick'=> 'js:saveimage()' too, but still not working.

Body:
Try:

$this->registerJs(
    "function saveimage()
     {
        var csrfToken = $('meta[name="csrf-token"]').attr("content");

        console.log(123);

     }",
    \yii\web\VIEW::POS_READY,
    'my-button-handler'
);

Or alternatively, If you want to use a separate js file you can use below syntax:

$this->registerJsFile(
    '@web/js/script.js',
    ['depends' => [\yii\web\JqueryAsset::className()]]
);

When working with the yii\web\View object you can dynamically register
  frontend scripts. There are two dedicated methods for this:

1) registerJs() for inline scripts

2) registerJsFile() for external scripts

For more details refer to the link.


问:
Is Xcode9 backwards compatible to Swift 3 (or 3.1)?
I've just started using Xcode9 (beta2). My understanding was that it wouldn't force me to immediately change my code. However, I'm getting a build errors coming up with a library I'm using (Gloss):

1) For the following code:

```<code>public func valueForKeyPath(keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter, logger: Logger = GlossLogger()) -> Any? {
</code>```

I get:

Initializer 'init()' is internal and cannot be referenced from a
  default argument value

2) For this code:

```<code>internal func flatMap<KeyPrime : Hashable, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
    return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ (key, value) in
        return try transform(key, value)
    }))
}
</code>```

I'm getting:

Closure tuple parameter '(key: _, value: _)' does not support
  destructuring

Both of these caused no problem with Xcode 8.3/Swift 3.1.

I am using Xcode9 without having chosen the option to update to Swift 4. There seems several possibilities:

There are some flags that need to be set to retain Swift 3.1 backwards compatibility

Xcode9 is in beta and just isn't ready fully

Xcode9 will not be completely backwards compatible to Swift 3.1

Thoughts?

答: Xcode 9 is cross compatible with Swift 3 and 4. However, you need to be on Swift 3.2 which is the minimum for Xcode 9.</p>

Body:
I've just started using Xcode9 (beta2). My understanding was that it wouldn't force me to immediately change my code. However, I'm getting a build errors coming up with a library I'm using (Gloss):

1) For the following code:

public func valueForKeyPath(keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter, logger: Logger = GlossLogger()) -> Any? {

I get:

Initializer 'init()' is internal and cannot be referenced from a
  default argument value

2) For this code:

internal func flatMap<KeyPrime : Hashable, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
    return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ (key, value) in
        return try transform(key, value)
    }))
}

I'm getting:

Closure tuple parameter '(key: _, value: _)' does not support
  destructuring

Both of these caused no problem with Xcode 8.3/Swift 3.1.

I am using Xcode9 without having chosen the option to update to Swift 4. There seems several possibilities:

There are some flags that need to be set to retain Swift 3.1 backwards compatibility

Xcode9 is in beta and just isn't ready fully

Xcode9 will not be completely backwards compatible to Swift 3.1

Thoughts?


问:
What is UUID and CoreBluetooth?
I don't understand about UUID SERVICE! can I find where that?
e.g.

答:
The service and characteristic UUIDs are defined by your peripheral.

There are some well-known services and characteristics defined by the Bluetooth SIG.  These are typically abbreviated to 4 hex digits since they come from a common UUID range.

Peripherals can use any UUID they want for other services and characteristics.

The UUIDs in your question appear to be private values; You need to refer to the peripheral or manufacturer documentation for information on those.

Title: What is UUID and CoreBluetooth?


问:
Country selection in android using API
I need spinner item should be flag image which is from service but it is showing country name in spinner item or i can use custom list view instead of spinner which one is easy.

MainActivity.java

```<code>public class MainActivity extends Activity {
    JSONObject jsonobject;
    JSONArray jsonarray;
    ProgressDialog mProgressDialog;
    ArrayList<String> worldlist;
    ArrayList<WorldPopulation> world;

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

    // Download JSON file AsyncTask
    new DownloadJSON().execute();

}

// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        // Locate the WorldPopulation Class
        world = new ArrayList<WorldPopulation>();
        // Create an array to populate the spinner
        worldlist = new ArrayList<String>();
        // JSON file URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                // Populate spinner with country names
                worldlist.add(jsonobject.optString("country"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
}
</code>```

JSONfunctions.java

```<code>public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
}
</code>```

activity_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
    android:id="@+id/my_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/rank"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/my_spinner" />

<TextView
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rank" />

<TextView
    android:id="@+id/population"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/country" />

</RelativeLayout>
</code>```

答:
You can use dialog to open that list for replacing spinner:

```<code>void setStateListData() {
        try {
            final String[] stateList = new String[getStateArrGlobal().size()];
            for (int i = 0; i <getStateArrGlobal().size(); i++) {
                stateList[i] =getStateArrGlobal().get(i).getName();
            }
            showAlertDialog(getActivity(), "Select state", stateList, onClickedStateListner);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    DialogInterface.OnClickListener onClickedStateListner = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            districtArrGlobal = new ArrayList<DataModel>();
            editDistrict.setText("");
            editState.setText("" + getStateArrGlobal().get(item).getName());
            setDistrictListData(getStateArrGlobal().get(item).getId());
        }
    };
</code>```

and use the dialog as:

```<code> public void showAlertDialog(Context context, String message, String[] arrayList, DialogInterface.OnClickListener onClickedListener) {
        android.support.v7.app.AlertDialog.Builder dialogBuilder = new android.support.v7.app.AlertDialog.Builder(context);
        dialogBuilder.setTitle(message);
        dialogBuilder.setItems(arrayList, onClickedListener);
        //Create alert dialog object via builder
        android.support.v7.app.AlertDialog alertDialogObject = dialogBuilder.create();
        //Show the dialog
        alertDialogObject.show();
    }
</code>```

Title: Country selection in android using API

Body:
I need spinner item should be flag image which is from service but it is showing country name in spinner item or i can use custom list view instead of spinner which one is easy.

MainActivity.java

public class MainActivity extends Activity {
    JSONObject jsonobject;
    JSONArray jsonarray;
    ProgressDialog mProgressDialog;
    ArrayList<String> worldlist;
    ArrayList<WorldPopulation> world;

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

    // Download JSON file AsyncTask
    new DownloadJSON().execute();

}

// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        // Locate the WorldPopulation Class
        world = new ArrayList<WorldPopulation>();
        // Create an array to populate the spinner
        worldlist = new ArrayList<String>();
        // JSON file URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                // Populate spinner with country names
                worldlist.add(jsonobject.optString("country"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
}

JSONfunctions.java

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
    android:id="@+id/my_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/rank"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/my_spinner" />

<TextView
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rank" />

<TextView
    android:id="@+id/population"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/country" />

</RelativeLayout>

Body:
You can use dialog to open that list for replacing spinner:

void setStateListData() {
        try {
            final String[] stateList = new String[getStateArrGlobal().size()];
            for (int i = 0; i <getStateArrGlobal().size(); i++) {
                stateList[i] =getStateArrGlobal().get(i).getName();
            }
            showAlertDialog(getActivity(), "Select state", stateList, onClickedStateListner);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    DialogInterface.OnClickListener onClickedStateListner = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            districtArrGlobal = new ArrayList<DataModel>();
            editDistrict.setText("");
            editState.setText("" + getStateArrGlobal().get(item).getName());
            setDistrictListData(getStateArrGlobal().get(item).getId());
        }
    };

and use the dialog as:

 public void showAlertDialog(Context context, String message, String[] arrayList, DialogInterface.OnClickListener onClickedListener) {
        android.support.v7.app.AlertDialog.Builder dialogBuilder = new android.support.v7.app.AlertDialog.Builder(context);
        dialogBuilder.setTitle(message);
        dialogBuilder.setItems(arrayList, onClickedListener);
        //Create alert dialog object via builder
        android.support.v7.app.AlertDialog alertDialogObject = dialogBuilder.create();
        //Show the dialog
        alertDialogObject.show();
    }


问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答:
While on the topic, according to Jeff Atwood, the switch statement is a programming atrocity. Use them sparingly.

You can often accomplish the same task using a table. For example:

```<code>var table = new Dictionary<Type, string>()
{
   { typeof(int), "it's an int!" }
   { typeof(string), "it's a string!" }
};

Type someType = typeof(int);
Console.WriteLine(table[someType]);
</code>```

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

Body:
While on the topic, according to Jeff Atwood, the switch statement is a programming atrocity. Use them sparingly.

You can often accomplish the same task using a table. For example:

var table = new Dictionary<Type, string>()
{
   { typeof(int), "it's an int!" }
   { typeof(string), "it's a string!" }
};

Type someType = typeof(int);
Console.WriteLine(table[someType]);

OwnerDisplayName: Judah Himango

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Judah Himango


问:
Sequence data base with Django?
I am learning Django and creating  a Biological Sequence database, contains hundreds of sequences using a model as given bellow, model has two fields,  "Seq_ID" and "sequence". I am trying to write a view so that it can render IDs of all the sequences on home page and clicking on a particular IDs it will shows the associated sequence.

Updated Views and Urls:

Model:

```<code>from __future__ import unicode_literals

from django.db import models

    # Create your models here.
class FastaSeq(models.Model):

    Seq_ID =  models.CharField(max_length=20)
    Sequense = models.TextField()

    def __unicode__(self):

        return self.Seq_ID
</code>```

View:

```<code>from django.shortcuts import render
from django.conf import settings
from .models import FastaSeq

def home(request):
    data = FastaSeq.objects.all()
    context = {'data':data}
    template = 'home.html'
    return render(request, template, context)

def single(request,Seq_ID):
    data = FastaSeq.objects.get(Seq_ID=Seq_ID)
    return render(request,template,{'data':data})
</code>```

urls:

```<code>from django.conf.urls import url
from django.contrib import admin
from new_app import views as new_app_view

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^home/', new_app_view.home, name='home'),
    url(r'^User/(?P<Seq_ID>\d+)/$', new_app_view.single, name='single'),

]
</code>```

Example_Data:

```<code>Seq_ID:
>01_sequence

Sequence:
LARALLLCAAVVCGAANPCCSHPCQNRGVCMSVGFDQYKCDCTRTGFYGENCTTPEFLTRIKLLLKPTP
DTVHYILTHFKGVWNIVNKISFLRNMIMRYVLTSRSHLIESPPTYNVHYSYKSWEAFSNLSYYTRALPPV
PDDCPTPMGVKGRKELPDSKEVVKKVLLRRKFIPDPQGTNLMFAFFAQHFTHQFFKTDIERGPAFTKGKN
HGVDLSHVYGESLERQHNRRLFKDGKMKYQMINGEMYPPTVKDTQVEMIYPPHIPEHLKFAVGQEVFGLV
</code>```

Using this model I have added around 50 Demo sequences into the database but not able to writedown a view which can show the sequence ID on home page and clicking on ID will land you on sequence data.

Updated:

Showing some Error:

```<code>No    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/home/jai/.virtualenvs/env1/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 389, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
NoReverseMatch: Reverse for 'single' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['User/(?P<Seq_ID>\\d+)/$']
[06/Jul/2017 06:46:13] "GET /home/ HTTP/1.1" 500 133824
</code>```

答:
```<code>from .models import FastaSeq
def home(request):
    data = FastaSeq.objects.all()
    context = {'data':data}
    template = 'home.html'
    return render(request, template, context)
</code>```

in template

```<code>{% for d in data %}
<a href="{% url 'single' d.Seq_ID %}">{{ d.Seq_ID  }}</a>
{% endfor %}
</code>```

in urls.py

```<code>url(r'^User/(?P<Seq_ID>[\w{}.-]{1,40})/$', 'views.single', name='single'),
</code>```

create another view

```<code>def single(request,Seq_ID):
    data = FastaSeq.objects.get(Seq_ID=Seq_ID)
    return render(request,template,{'data':data})
</code>```

in single function template`

```<code>{{ data.Seq_ID }}
{{ data.Sequense }}
</code>```

Title: Sequence data base with Django?

Body:
I am learning Django and creating  a Biological Sequence database, contains hundreds of sequences using a model as given bellow, model has two fields,  "Seq_ID" and "sequence". I am trying to write a view so that it can render IDs of all the sequences on home page and clicking on a particular IDs it will shows the associated sequence.

Updated Views and Urls:

Model:

from __future__ import unicode_literals

from django.db import models

    # Create your models here.
class FastaSeq(models.Model):

    Seq_ID =  models.CharField(max_length=20)
    Sequense = models.TextField()

    def __unicode__(self):

        return self.Seq_ID

View:

from django.shortcuts import render
from django.conf import settings
from .models import FastaSeq

def home(request):
    data = FastaSeq.objects.all()
    context = {'data':data}
    template = 'home.html'
    return render(request, template, context)

def single(request,Seq_ID):
    data = FastaSeq.objects.get(Seq_ID=Seq_ID)
    return render(request,template,{'data':data})

urls:

from django.conf.urls import url
from django.contrib import admin
from new_app import views as new_app_view

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^home/', new_app_view.home, name='home'),
    url(r'^User/(?P<Seq_ID>\d+)/$', new_app_view.single, name='single'),

]

Example_Data:

Seq_ID:
>01_sequence

Sequence:
LARALLLCAAVVCGAANPCCSHPCQNRGVCMSVGFDQYKCDCTRTGFYGENCTTPEFLTRIKLLLKPTP
DTVHYILTHFKGVWNIVNKISFLRNMIMRYVLTSRSHLIESPPTYNVHYSYKSWEAFSNLSYYTRALPPV
PDDCPTPMGVKGRKELPDSKEVVKKVLLRRKFIPDPQGTNLMFAFFAQHFTHQFFKTDIERGPAFTKGKN
HGVDLSHVYGESLERQHNRRLFKDGKMKYQMINGEMYPPTVKDTQVEMIYPPHIPEHLKFAVGQEVFGLV

Using this model I have added around 50 Demo sequences into the database but not able to writedown a view which can show the sequence ID on home page and clicking on ID will land you on sequence data.

Updated:

Showing some Error:

No    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/home/jai/.virtualenvs/env1/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 389, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
NoReverseMatch: Reverse for 'single' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['User/(?P<Seq_ID>\\d+)/$']
[06/Jul/2017 06:46:13] "GET /home/ HTTP/1.1" 500 133824

Body:
from .models import FastaSeq
def home(request):
    data = FastaSeq.objects.all()
    context = {'data':data}
    template = 'home.html'
    return render(request, template, context)

in template

{% for d in data %}
<a href="{% url 'single' d.Seq_ID %}">{{ d.Seq_ID  }}</a>
{% endfor %}

in urls.py

url(r'^User/(?P<Seq_ID>[\w{}.-]{1,40})/$', 'views.single', name='single'),

create another view

def single(request,Seq_ID):
    data = FastaSeq.objects.get(Seq_ID=Seq_ID)
    return render(request,template,{'data':data})

in single function template`

{{ data.Seq_ID }}
{{ data.Sequense }}


问:
How does one React component call a method in another React component?
My page contains two completely separate React components (different files, different classes, no parent-child relationship).

How can one component call an instance method in another component? The problem seems to be obtaining the instance of the target component.

EDIT: Both components share the same parent (i.e. they are rendered in the same render() method) but I still don't know how to pass the reference of the target component to the calling component.

答:
you can send an event as props and call it from other component.

Say you have a class

```<code>    Class A{

    handleChange(evt)
    {

   this.setState({
name:evt.target.value

})
    }

    render{
    return(
    <div>
    <ComponentB name={this.state.name}{ onChange={this.handleChange}/>

    </div>

    );
    }
    }
</code>```

Child Component

```<code> Class B{

    handleChange()
    {

    //logic
    }

    render{
    return(
    <div>
    <input type="text" onChange={this.props.onChange}/>
    {this.props.name}
    </div>

    );

    }
</code>```

Here in Component B when you change the input it will call the method
of class A and update state of A.

Now getting the updated state as props in component B will give you
the changed text that you just entered

Body:
you can send an event as props and call it from other component.

Say you have a class

    Class A{

    handleChange(evt)
    {

   this.setState({
name:evt.target.value

})
    }

    render{
    return(
    <div>
    <ComponentB name={this.state.name}{ onChange={this.handleChange}/>

    </div>

    );
    }
    }

Child Component

 Class B{

    handleChange()
    {

    //logic
    }

    render{
    return(
    <div>
    <input type="text" onChange={this.props.onChange}/>
    {this.props.name}
    </div>

    );

    }

Here in Component B when you change the input it will call the method
of class A and update state of A.

Now getting the updated state as props in component B will give you
the changed text that you just entered


问:
Mysql very slow query, but fast working after reboot (CPU usage 99%)
I have a SQL query generated ORM (Hibernate). Query is big, but after restart MySQL service it works fast (0.2 sec.). A few days later, the query is becoming slower and slower (> 1 min.). I run DESCRIBE. And I see that the query plan is different. But I do not know what the problem is and how I can remedy the situation.

Fast:

Slow:

Generated query

答:
Please check the number of connection used in your MySQL, I have to doubt there are so many connections are opened or used that's why query execution plan was slow, but after reboot it comparatively fast..

Hop its work!


问:
how to get selected id inside interval using jquery
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

答:
Try like this

```<code> if ( $("div[id^='popup_']").length && !found) {
    found = true;
    console.log($('div').attr('id'));
  };
</code>```

Example:-

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id^='popup_']").length && !found) {
    found = true;
    console.log($('div').attr('id'));
  };

}, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

Body:
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);

<input type="button" value="click" id="btn">

Body:
Try like this

 if ( $("div[id^='popup_']").length && !found) {
    found = true;
    console.log($('div').attr('id'));
  };

Example:-

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('<div id="popup_w">A new popup div added</div>');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id^='popup_']").length && !found) {
    found = true;
    console.log($('div').attr('id'));
  };

}, 5000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn">