问:
Accessing xaml elements in viewmodel and applying dynamic styles at runtime using wpf mvvm
I need to apply dynamic style to my button in ViewModel on the basis of if else condition. I have created 2 styles for the button in separata user controls using ResourceDictionary with the same Key. This button is in one usercontrol i.e. xaml. How to dynamically apply the styles using style tag and DynamicResource. How to do this with properties?

Kindly Suggest?

Thanks

答:
By the sounds of things you need to use either MultiTriggers or MultiDataTriggers. You can find out more about MultiTriggers here and MultiDataTriggers here. The triggers allow you to take different actions based on a single or multiple condition(s).

Hope this helps.


来源: stackexchange

问:
Query to find accounts with specified months
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH
</code>```

I am still getting account ids which where in JULY

答:
Using SQL Server's Month function gives you an understandable example of how to solve this.</p>

```<code>SELECT ACCOUNT_ID
FROM DATA1
WHERE MONTH(DATA_MONTH) in (5,6) AND YEAR(DATA_MONTH) = 2018 AND MONTH(DATA_MONTH) NOT IN (7)
GROUP BY ACCOUNT_ID
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH

I am still getting account ids which where in JULY

Body:
Using SQL Server's Month function gives you an understandable example of how to solve this.

SELECT ACCOUNT_ID
FROM DATA1
WHERE MONTH(DATA_MONTH) in (5,6) AND YEAR(DATA_MONTH) = 2018 AND MONTH(DATA_MONTH) NOT IN (7)
GROUP BY ACCOUNT_ID


问:
501 Not Implemented error in small web app
I am trying to upload images to an S3 bucket with react and expressjs. When I attempt to upload the image I get a 501 Not Implemented Error. I am using axios to contact the end point I created in the server code.

My react code:

```<code>class FileUpload extends Component {
  state = {
    file: null
  };

  submitFile = (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append('file', this.state.file[0]);
    axios.post(`test-upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      // handle your response;
    }).catch(error => {
      // handle your error
    });
  }

  handleFileUpload = (event) => {
    this.setState({file: event.target.files});
  }

  render () {
    return (
      <form onSubmit={this.submitFile}>
        <input label='upload file' type='file' onChange=
    {this.handleFileUpload} />
        <button type='submit'>Send</button>
      </form>
    );
  }
}

export default FileUpload;
</code>```

My server code:

```<code>const uploadFile = (buffer, name, type) => {
  const params = {
    ACL: 'public-read',
    Body: buffer,
    Bucket: process.env.S3_BUCKET,
    ContentType: type.mime,
    Key: `${name}.${type.ext}`
  };
  return s3.upload(params).promise();
};

app.use('/', (req,res) =>{
  res.send(JSON.stringify({ greeting: `Hello!` }));
});

// Define POST route
app.post('/test-upload', (request, response) => {
  const form = new multiparty.Form();
    form.parse(request, async (error, fields, files) => {
      if (error) throw new Error(error);
      try {
        const path = files.file[0].path;
        const buffer = fs.readFileSync(path);
        const type = fileType(buffer);
        const timestamp = Date.now().toString();
        const fileName = `bucketFolder/${timestamp}-lg`;
        const data = await uploadFile(buffer, fileName, type);
        return response.status(200).send(data);
      } catch (error) {
        return response.status(400).send(error);
      }
    });
});
</code>```

This was done by following a guide on the internet but there seems to be something missing that I just can't figure out.

答:
Figured it out in the end,

```<code>axios.post(/test-upload,
</code>```

should have been

```<code>axios.post(http://localhost:3000/test-upload,
</code>```

Body:
I am trying to upload images to an S3 bucket with react and expressjs. When I attempt to upload the image I get a 501 Not Implemented Error. I am using axios to contact the end point I created in the server code.

My react code:

class FileUpload extends Component {
  state = {
    file: null
  };

  submitFile = (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append('file', this.state.file[0]);
    axios.post(`test-upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      // handle your response;
    }).catch(error => {
      // handle your error
    });
  }

  handleFileUpload = (event) => {
    this.setState({file: event.target.files});
  }

  render () {
    return (
      <form onSubmit={this.submitFile}>
        <input label='upload file' type='file' onChange=
    {this.handleFileUpload} />
        <button type='submit'>Send</button>
      </form>
    );
  }
}

export default FileUpload;

My server code:

const uploadFile = (buffer, name, type) => {
  const params = {
    ACL: 'public-read',
    Body: buffer,
    Bucket: process.env.S3_BUCKET,
    ContentType: type.mime,
    Key: `${name}.${type.ext}`
  };
  return s3.upload(params).promise();
};

app.use('/', (req,res) =>{
  res.send(JSON.stringify({ greeting: `Hello!` }));
});

// Define POST route
app.post('/test-upload', (request, response) => {
  const form = new multiparty.Form();
    form.parse(request, async (error, fields, files) => {
      if (error) throw new Error(error);
      try {
        const path = files.file[0].path;
        const buffer = fs.readFileSync(path);
        const type = fileType(buffer);
        const timestamp = Date.now().toString();
        const fileName = `bucketFolder/${timestamp}-lg`;
        const data = await uploadFile(buffer, fileName, type);
        return response.status(200).send(data);
      } catch (error) {
        return response.status(400).send(error);
      }
    });
});

This was done by following a guide on the internet but there seems to be something missing that I just can't figure out.

Body:
Figured it out in the end,

axios.post(/test-upload,

should have been

axios.post(http://localhost:3000/test-upload,


问:
C# - Problem Executing Application Outside Visual Studio
I'm with a problem executing an implementation in application. I have some webservices that I can work, run, and access its informations normally in Visual Studio.

The connection with the webservices addresses can be access via IE, for example, and the services are alright.

I execute the executable file in application, and when it is tried to access the webservices, I get the 403 (Forbidden) error.

The credentials are fine because the line that triggers the error is when an method of the webservice is used after the authentication is done.

Even running in administrator privileges in application it shows the same error. And the WCF service is running by a local administrator user.

I've already tried to request in the same scope that the method is being used, but unsuccessful.

```<code>private SI_Out_SyncClient WebserviceConnection ()
{

    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);

    binding.MaxBufferSize = 2147483647;
    binding.MaxReceivedMessageSize = 2147483647;

    binding.CloseTimeout = new TimeSpan(1, 5, 0);
    binding.OpenTimeout = new TimeSpan(1, 5, 0);
    binding.SendTimeout = new TimeSpan(1, 5, 0);

    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
    binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;

    EndpointAddress address = new EndpointAddress(Library.Environment.GetGlobalString("ENDPOINT"));

    var client = new SI_Out_SyncClient(binding, address);

    client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    client.ClientCredentials.UserName.UserName = Library.Environment.GetGlobalString("USER");
    client.ClientCredentials.UserName.Password = Library.Environment.GetGlobalString("PASSWORD");

    return client;
}
</code>```

I expect to run in application as I can run in debug, but in the correct way, without setting debug compilation mode to true.

Thanks in advance!

答:
I figured out what was going on.

In my case, the administrator user that is running the WCF service hadn't access to internet.

A silly mistake, but it is worth to register since I didn't find an orientation like this in my researches.

Body:
I'm with a problem executing an implementation in application. I have some webservices that I can work, run, and access its informations normally in Visual Studio.

The connection with the webservices addresses can be access via IE, for example, and the services are alright.

I execute the executable file in application, and when it is tried to access the webservices, I get the 403 (Forbidden) error.

The credentials are fine because the line that triggers the error is when an method of the webservice is used after the authentication is done.

Even running in administrator privileges in application it shows the same error. And the WCF service is running by a local administrator user.

I've already tried to request in the same scope that the method is being used, but unsuccessful.

private SI_Out_SyncClient WebserviceConnection ()
{

    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);

    binding.MaxBufferSize = 2147483647;
    binding.MaxReceivedMessageSize = 2147483647;

    binding.CloseTimeout = new TimeSpan(1, 5, 0);
    binding.OpenTimeout = new TimeSpan(1, 5, 0);
    binding.SendTimeout = new TimeSpan(1, 5, 0);

    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
    binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;

    EndpointAddress address = new EndpointAddress(Library.Environment.GetGlobalString("ENDPOINT"));

    var client = new SI_Out_SyncClient(binding, address);

    client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    client.ClientCredentials.UserName.UserName = Library.Environment.GetGlobalString("USER");
    client.ClientCredentials.UserName.Password = Library.Environment.GetGlobalString("PASSWORD");

    return client;
}

I expect to run in application as I can run in debug, but in the correct way, without setting debug compilation mode to true.

Thanks in advance!


问:
Typescript parameters - a generic array of objects and array of object's keys (partial)
I want to have a method that accepts an array of objects and an array of some of the objects keys. The method will return an array of arrays of object values but only of the selected keys.

data:

```<code>[
  {"firstName": "Jane", "lastName": "Doe"},
  {"firstName": "John", "lastName": "Doe"}
]
</code>```

fields:

```<code>["firstName"]
</code>```

result:

```<code>[["Jane"], ["John"]]
</code>```

By now I have a function that provides desired outcome but I am not sure how to handle the types better.

mapToCsvData: (data: { [key: string]: any }[], fields: string[]) => {
  return data.map((item: any) => {
    return fields.map(field => item[field]);
  });
}
```

<p>I have tried some variations of the next snippet but I get an error.</p>

```mapToCsvData: <T extends object>(data: T[], fields: keyof T[]) => {
```

```Property 'map' does not exist on type 'number'.
```

答:
You will need an extra type parameter to capture the actual tuple of keys being passed in. You can them map this tuple to the corresponding property types in T. It all works out very nicely:

```<code>type MapKeyTupleToProps<T, P extends [keyof T] | Array<keyof T>> = {
    [K in keyof P]: P[K] extends keyof T ? T[P[K]] : never
}
const m = {
    mapToCsvData: <T, P extends [keyof T] | Array<keyof T>>(data: T[], fields: P): MapKeyTupleToProps<T, P> => {
        return data.map((item: any) => {
            return fields.map(field => item[field]);
        }) as any;
    }
}

const data = [
    {"firstName": "Jane", "lastName": "Doe", age: 0},
    {"firstName": "John", "lastName": "Doe", age: 0}
]

let r = m.mapToCsvData(data, ["firstName", "lastName"]) // [string, string]
let r2 = m.mapToCsvData(data, ["firstName", "age"]) //[string, number]
</code>```

Body:
I want to have a method that accepts an array of objects and an array of some of the objects keys. The method will return an array of arrays of object values but only of the selected keys.

data:

[
  {"firstName": "Jane", "lastName": "Doe"},
  {"firstName": "John", "lastName": "Doe"}
]

fields:

["firstName"]

result:

[["Jane"], ["John"]]

By now I have a function that provides desired outcome but I am not sure how to handle the types better.

mapToCsvData: (data: { [key: string]: any }[], fields: string[]) => {
  return data.map((item: any) => {
    return fields.map(field => item[field]);
  });
}

I have tried some variations of the next snippet but I get an error.

mapToCsvData: <T extends object>(data: T[], fields: keyof T[]) => {

Property 'map' does not exist on type 'number'.

Body:
You will need an extra type parameter to capture the actual tuple of keys being passed in. You can them map this tuple to the corresponding property types in T. It all works out very nicely:

type MapKeyTupleToProps<T, P extends [keyof T] | Array<keyof T>> = {
    [K in keyof P]: P[K] extends keyof T ? T[P[K]] : never
}
const m = {
    mapToCsvData: <T, P extends [keyof T] | Array<keyof T>>(data: T[], fields: P): MapKeyTupleToProps<T, P> => {
        return data.map((item: any) => {
            return fields.map(field => item[field]);
        }) as any;
    }
}

const data = [
    {"firstName": "Jane", "lastName": "Doe", age: 0},
    {"firstName": "John", "lastName": "Doe", age: 0}
]

let r = m.mapToCsvData(data, ["firstName", "lastName"]) // [string, string]
let r2 = m.mapToCsvData(data, ["firstName", "age"]) //[string, number]


问:
Unrelated template parse error in Angular 6
I am developing a simple Angular 6 application. At a certain point a 'Template parse error' appeared, literally out of nowhere: "let-" is only supported on ng-template elements. I don't use any template or ng-template in my code. Anybody with an idea?</p>

```<code>Uncaught Error: Template parse errors:
"let-" is only supported on ng-template elements. ("
  </thead>
  <tbody>
    <template ngFor [ngForOf]="rows" [ERROR ->]let-rowz="$implicit" let-index="index">
      <tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].sec"): ng:///DatepickerModule/DayPickerComponent.html@38:37
"let-" is only supported on ng-template elements. ("
  </thead>
  <tbody>
    <template ngFor [ngForOf]="rows" let-rowz="$implicit" [ERROR ->]let-index="index">
      <tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].secondary && rowz[6].sec"): ng:///DatepickerModule/DayPickerComponent.html@38:58
    at syntaxError (compiler.js:2547)
    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (compiler.js:19495)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:25041)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:25028)
    at compiler.js:24971
    at Set.forEach (<anonymous>)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:24971)
    at compiler.js:24881
    at Object.then (compiler.js:2538)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:24880)
</code>```

答:
If I'm not wrong you are using an *ngFor and you are trying to get the index and if that's the case try following the below example.

```<code><div *ngFor="let element of array; let $index = index">{{$index}}</div>
</code>```

And I think what you are doing is let-index = index;, which I concluded from the error trace you have uploaded. You are using an - between let and index.

Body:
I am developing a simple Angular 6 application. At a certain point a 'Template parse error' appeared, literally out of nowhere: "let-" is only supported on ng-template elements. I don't use any template or ng-template in my code. Anybody with an idea?

Uncaught Error: Template parse errors:
"let-" is only supported on ng-template elements. ("

    <template ngFor [ngForOf]="rows" [ERROR ->]let-rowz="$implicit" let-index="index">
      <tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].sec"): ng:///DatepickerModule/DayPickerComponent.html@38:37
"let-" is only supported on ng-template elements. ("

    <template ngFor [ngForOf]="rows" let-rowz="$implicit" [ERROR ->]let-index="index">
      <tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].secondary && rowz[6].sec"): ng:///DatepickerModule/DayPickerComponent.html@38:58
    at syntaxError (compiler.js:2547)
    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (compiler.js:19495)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:25041)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:25028)
    at compiler.js:24971
    at Set.forEach (<anonymous>)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:24971)
    at compiler.js:24881
    at Object.then (compiler.js:2538)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:24880)

Body:
If I'm not wrong you are using an *ngFor and you are trying to get the index and if that's the case try following the below example.

<div *ngFor="let element of array; let $index = index">{{$index}}</div>

And I think what you are doing is let-index = index;, which I concluded from the error trace you have uploaded. You are using an - between let and index.


问:
Get specific value from a Array of JSON object and push it to another array?
I am using Vue.js, I have an Array of JSON Object, How can I push the 'c' and 'd' to selected1 and push the '88' and '66' to selected2?

```<code>export default {
 arr:[{
    "name": "a",
    "options": [{
        label: "b",
        value: 9,
        foodoption: [{ label: "c", value: 8 }, { label: "d", value: 6 }],
        selected1: [],
        show: false
      },

    ]},
    {
      "name": "aa",
      "options": [{
          label: "bb",
          value: 9,
          foodoption: [{ label: "cc", value: 88 }, { label: "dd", value: 66 }],
          selected2: [],
          show: false
        },
      ]}
  ]
</code>```

expect get:

```<code>selected1:[c,d]

selected2:[88,66]
</code>```

I try to use vue.js to get the value in the view:

```<code><div v-for="(obj, index) in arr" :key="index" >
     <div v-for="(opt, index) in obj.foodoption" :key="index">
         {{ opt.label }} {{ opt.value}}
     </div>
</div>

</code>```

How can I get each expects item by JavaScript?

答:
This is purely a JS question, you don't need VueJS to do that. Simply use a combination of dot and bracket notation to access the foodoption value in your arr, and then use Array.prototype.map to return the desired values based on the key (label or value):

const arr = [{
  "name": "a",
  "options": [{
      label: "b",
      value: 9,
      foodoption: [{ label: "c", value: 8 }, { label: "d", value: 6 }],
      selected1: [],
      show: false
    },

  ]},
  {
    "name": "aa",
    "options": [{
        label: "bb",
        value: 9,
        foodoption: [{ label: "cc", value: 88 }, { label: "dd", value: 66 }],
        selected2: [],
        show: false
      },
    ]}
];

const selected1 = arr[0].options[0].foodoption.map(opt => opt.label);
const selected2 = arr[1].options[0].foodoption.map(opt => opt.value);

console.log(selected1);
console.log(selected2);```

Body:
I am using Vue.js, I have an Array of JSON Object, How can I push the 'c' and 'd' to selected1 and push the '88' and '66' to selected2?

export default {
 arr:[{
    "name": "a",
    "options": [{
        label: "b",
        value: 9,
        foodoption: [{ label: "c", value: 8 }, { label: "d", value: 6 }],
        selected1: [],
        show: false
      },

    ]},
    {
      "name": "aa",
      "options": [{
          label: "bb",
          value: 9,
          foodoption: [{ label: "cc", value: 88 }, { label: "dd", value: 66 }],
          selected2: [],
          show: false
        },
      ]}
  ]

expect get:

selected1:[c,d]

selected2:[88,66]

I try to use vue.js to get the value in the view:

         {{ opt.label }} {{ opt.value}}

How can I get each expects item by JavaScript?


问:
find base address of current procrss in kernel space
hi i will dump the other process in kernel driver

and use KeStackAttachProcess  to  change driver current context

after user-mode address changed how can find base address of current process
i need base address for cast it to PIMAGE_DOS_HEADER( and parse it to find sections)
can use PEB?

any other solution?

答:
There is a special API function for that:

```<code>NTKERNELAPI
PVOID
PsGetProcessSectionBaseAddress(
    __in PEPROCESS Process
    );
</code>```

And you can use SectionBaseAddress field in the EPROCESS structure:

```<code>+0x128 SectionBaseAddress : 0x00400000 Void
</code>```

It may vary in different OS versions.

ContentLicense: CC BY-SA 3.0

Body:
There is a special API function for that:

NTKERNELAPI
PVOID
PsGetProcessSectionBaseAddress(
    __in PEPROCESS Process
    );

And you can use SectionBaseAddress field in the EPROCESS structure:

+0x128 SectionBaseAddress : 0x00400000 Void

It may vary in different OS versions.


问:
Can not connect to my ms-sql server through nodejs
I recently transferred a project to my desktop over from my laptop, and am trying to get the sql server set up.  I'm testing out the server to make sure it works, and have set up a test table in my sql database.  Whenever I try to input data into the table I get the following error:

UnhandledPromiseRejectionWarning: ConnectionError: Connection is closed.

I'm able to log into the server using the credentials outlined in the code below through SSMS.  Here is the code I am using:

```<code>const express = require('express');
var sql = require('mssql');
const app = express();

var config = {
    user: 'djaenike',
    password: 'password',
    server: 'JAENIKE_DESKTOP',
    database: 'master'
};

app.post('/testing', (req, res) => {
  console.log('request made')
  res.set('Access-Control-Allow-Origin', '*');
    let connection = new sql.ConnectionPool(config, function(err) {
      let request = new sql.Request(connection);
      request.query("insert into testTable (test) values ('a test')");
    })
    res.send(req.query);
    sql.close();
});

const port = process.env.PORT || 5000; //get the process port
app.listen(port, () => console.log(`Server running on port ${port}`));
</code>```

I'm using postman to make a request to http://localhost:5000/testing and am getting the "request made" in my console window, just can't seem to establish a connection.  Any advice on how to troubleshoot?

Thanks!

答: Resolved - had to enable TCP/IP protocol in the network configurator.  All set</p>

Body:
I recently transferred a project to my desktop over from my laptop, and am trying to get the sql server set up.  I'm testing out the server to make sure it works, and have set up a test table in my sql database.  Whenever I try to input data into the table I get the following error:

UnhandledPromiseRejectionWarning: ConnectionError: Connection is closed.

I'm able to log into the server using the credentials outlined in the code below through SSMS.  Here is the code I am using:

const express = require('express');
var sql = require('mssql');
const app = express();

var config = {
    user: 'djaenike',
    password: 'password',
    server: 'JAENIKE_DESKTOP',
    database: 'master'
};

app.post('/testing', (req, res) => {
  console.log('request made')
  res.set('Access-Control-Allow-Origin', '*');
    let connection = new sql.ConnectionPool(config, function(err) {
      let request = new sql.Request(connection);
      request.query("insert into testTable (test) values ('a test')");
    })
    res.send(req.query);
    sql.close();
});

const port = process.env.PORT || 5000; //get the process port
app.listen(port, () => console.log(`Server running on port ${port}`));

I'm using postman to make a request to http://localhost:5000/testing and am getting the "request made" in my console window, just can't seem to establish a connection.  Any advice on how to troubleshoot?

Thanks!


问:
Reduce Trying to understand the parameters in the callback function of .reduce()
I'm trying to learn JS and I have some questions about reduce()
I want to know how can I know what parameters this function needs and how I should call them.

are this parameters connected with any data or the array outside the function.

or this parameters propose is only to be available in this local context of the callback to work as const and be able to store some date for the correct execution of the .reduce() .

Thank You For Your Time

Just trying to understand .reduce()

```<code>const companies= [
  {name: "Company One", category: "Finance", start: 1981, end: 2004},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008},
  {name: "Company Three", category: "Auto", start: 1999, end: 2007},
  {name: "Company Four", category: "Retail", start: 1989, end: 2010},
  {name: "Company Five", category: "Technology", start: 2009, end: 2014},
  {name: "Company Six", category: "Finance", start: 1987, end: 2010},
  {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
  {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
  {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
];

const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0);

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

答:
They're only available inside the callback, but obviously they aren't constants, as total gets mutated with every tick. This reduce goes like this:

The accumulator is initialized to 0.

First tick, the callback gets the current value of the accumulator (it's named total, but this name is completely arbitrary), 0, and an element: an object (company), with, among other things, start = 1981 and end = 2004. The function returns the value of total + company.end - company.start (0 + 2004 - 1981).
2a. Value returned by the callback becomes the new value of the accumulator. It's now 23.

Second tick, the callback receives 23 as accumulator and { start: 1992, end: 2008 } as the current element. Everything else proceeds as above.

...

Last tick: the value returned by the last execution of the callback is the return value of the companies.reduce(/*...*/) expression.

Body:
I'm trying to learn JS and I have some questions about reduce()
I want to know how can I know what parameters this function needs and how I should call them.

are this parameters connected with any data or the array outside the function.

or this parameters propose is only to be available in this local context of the callback to work as const and be able to store some date for the correct execution of the .reduce() .

Thank You For Your Time

Just trying to understand .reduce()

const companies= [
  {name: "Company One", category: "Finance", start: 1981, end: 2004},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008},
  {name: "Company Three", category: "Auto", start: 1999, end: 2007},
  {name: "Company Four", category: "Retail", start: 1989, end: 2010},
  {name: "Company Five", category: "Technology", start: 2009, end: 2014},
  {name: "Company Six", category: "Finance", start: 1987, end: 2010},
  {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
  {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
  {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
];

const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0);

console.log(totalYears);


问:
Azure append policy does not append
I have a tag append policy which looks like this:

```<code>{
  "if": {
    "AllOf": [
      {
        "field": "type",
        "equals": "Microsoft.Compute/virtualMachines"
      },
      {
        "AnyOf": [
          {
            "field": "tags[SandBox]",
            "exists": "false"
          },
          {
            "field": "tags[CostCenter]",
            "exists": "false"
          }
        ]
      }
    ]
  },
  "then": {
    "effect": "append",
    "details": [
      {
        "field": "tags[CostCenter]",
        "value": "APP1234567"
      }
    ]
  }
}
</code>```

My intention is to apply a cost center tag to all VMs which do not already have sandbox tag. For test I have few VMs where one of the VMs have sandbox tag, one has just bunch of random tags and rest do not have tags at all. Policy finds non-compliant resources just fine but it does not apply the tags. Am I missing something in here?

答:
The policy works just fine. I just did not know this:
"Append is used to add additional fields to the requested resource during creation or update."</p>

Title: Azure append policy does not append

Body:
I have a tag append policy which looks like this:

{
  "if": {
    "AllOf": [
      {
        "field": "type",
        "equals": "Microsoft.Compute/virtualMachines"
      },
      {
        "AnyOf": [
          {
            "field": "tags[SandBox]",
            "exists": "false"
          },
          {
            "field": "tags[CostCenter]",
            "exists": "false"
          }
        ]
      }
    ]
  },
  "then": {
    "effect": "append",
    "details": [
      {
        "field": "tags[CostCenter]",
        "value": "APP1234567"
      }
    ]
  }
}

My intention is to apply a cost center tag to all VMs which do not already have sandbox tag. For test I have few VMs where one of the VMs have sandbox tag, one has just bunch of random tags and rest do not have tags at all. Policy finds non-compliant resources just fine but it does not apply the tags. Am I missing something in here?


问:
Help: HOWTO Test Android App from within Emulator with Different Mobile Web Broswer Engines?
I have developed a mobile application using jQuery Mobile.   I have it working in the emulator using the default web browser engine.  Now, I want to test the app using the different browsers engines available on mobile devices.  I have seen this accomplished from other developers, such as Opera, Chrome, or Safari.  What is happening is these different browsers are being pointed to the Android emulator that is running the application.

Can anyone provide a link on how this is accomplished so I may follow the steps? I have searched the net and I can seem to find any solid information that explains this well enough for me to follow.

Thank you for reading my post.

答:
You can use the emulator to browse the web and go to websites with browser packages for you to install other apps in your virtual phone.

Alternatively you can use DDMS to transfer the .apk files to your virtual mobile phone, and then install them without using internet on emulator.

Then, when you have some application associated with a specific file type or operation, typically Android asks you which one you want to use, with a popup, and allows you to also set a default one for that file type/action.


问:
Using cordova-fetch for cordova-android@^8.0.0
I am trying to upgrade the Cordova version to Cordova 9 (Cordova-android 8). I am getting error below while adding platform.

Please suggest any solution for this.

```<code>Using cordova-fetch for cordova-android@^8.0.0
Adding ng-modules-scripts project...
Unable to load PlatformApi from platform. Error: Uncaught, unspecified "error" event. (Does not appear to implement platform Api.)
Uncaught, unspecified "error" event. (The platform "ng-modules-scripts" does not appear to be a valid cordova platform. It is missing API.js. ng-modules-scripts not supported.)
Build step 'Execute shell' marked build as failure
Archiving artifacts
Finished: FAILURE
</code>```

Regards,

Tripaty Sahu

答: Your Cordova project somehow thinks it should add a ng-modules-scripts platform, which doesn't exist and as such can not be installed. You should check cordova platform list and clean your config.xml and package.json of this platform, possibly using cordova platform rm ng-modules-scripts.

Body:
I am trying to upgrade the Cordova version to Cordova 9 (Cordova-android 8). I am getting error below while adding platform.

Please suggest any solution for this.

Using cordova-fetch for cordova-android@^8.0.0
Adding ng-modules-scripts project...
Unable to load PlatformApi from platform. Error: Uncaught, unspecified "error" event. (Does not appear to implement platform Api.)
Uncaught, unspecified "error" event. (The platform "ng-modules-scripts" does not appear to be a valid cordova platform. It is missing API.js. ng-modules-scripts not supported.)
Build step 'Execute shell' marked build as failure
Archiving artifacts
Finished: FAILURE

Regards,

Tripaty Sahu


问:
How to re render component on goBack icon press in header
I am trying to re render the component after goBack press . By using goBack I am able to go back page ,but that page is not getting refresh. How I can solve it ?
After goBack I have to call some api ,and now after back non of the function is getting call . I can only call if page will refresh or rerender .

Example , from page 1 header am clicking back arrow icon (i.e goBack fucntion) to go on Page 1 and after going page 1 it should refresh .

```<code><View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>
            <Body
              style={{ textAlign: 'center', width: '100%', flexGrow: 2, alignItems: 'center', justifyContent: 'center' }}>
            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}
            </Body>
            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
          </View>
</code>```

Thanks

答:
You can re render the component by using react life cycle hook function shouldcomponentupdate.
Specify the condition to update the state and re render the component.</p>

Body:
I am trying to re render the component after goBack press . By using goBack I am able to go back page ,but that page is not getting refresh. How I can solve it ?
After goBack I have to call some api ,and now after back non of the function is getting call . I can only call if page will refresh or rerender .

Example , from page 1 header am clicking back arrow icon (i.e goBack fucntion) to go on Page 1 and after going page 1 it should refresh .

<View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>

            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}

            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
          </View>

Thanks


问:
In my LinkedIn Oauth2.0.php access token's fetch function not responding any user content?
HI We are using LinkedIn API call at our website to get our website visitor details to logged in their profile through Linkedin.

The functionality was working fine but suddenly its stop working I checked in it.

We are getting Access Token Response in call but later on its fetching function is not working means not getting any values.I added some debug to check response and field value code and debug screenshot is attached

I tried to test made scope fields similar showing in app

```<code>define('SCOPE',        'r_basicprofile r_emailaddress'  --->
define('SCOPE',        'r_liteprofile r_emailaddress'
</code>```

and update call code to latest method

```<code>https://www.linkedin.com/uas/oauth2/authorization ->> https://www.linkedin.com/oauth/v2/authorization

https://www.linkedin.com/uas/oauth2/accessToken?  ->>
https://www.linkedin.com/oauth/v2/accessToken
</code>```

But still nothing change than I redo changs in code and this is the code

```<code><?php
$config = include(dirname(__FILE__).'/config.php');
// Change these
define('API_KEY',      'XXXXXXXXX');
define('API_SECRET',   'XXXXXXXXX');
//define('REDIRECT_URI', ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")?'https':'http').'://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('REDIRECT_URI', ('https://example.com/linkedin/OAuth2.php'));
define('SCOPE',        'r_basicprofile r_emailaddress'                        );

// You'll probably use a database
    session_name('linkedin');
    session_start();

// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application

        getAccessToken();

} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
    $_SESSION['access_token'] = '';

    }
    if (empty($_SESSION['access_token']) || $_SESSION['access_token'] == '') {
        // Start authorization process
        getAuthorizationCode();
    }
}

echo "Fetching" . "<br>";
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(id,first-name,last-name,headline,email-address,picture-urls::(original),public-profile-url,picture-url,location,industry,site-standard-profile-request,interests,positions,summary,main-address,phone-numbers,skills:(skill))');

$userData = array('linkedin_id'=>'','first-name'=>'','last-name'=>'','picture-url'=>'','email-address'=>'','public_url'=>'','summary'=>'','twitter-account'=>'','headline'=>'','companyname'=>'','designation'=>'');

          foreach($user as $key=>$value)
          {

            if($key=='id')
                $userData['linkedin_id'] = $value;
            if($key=='firstName')
                $userData['first-name'] = $value;
            if($key=='lastName')
                $userData['last-name'] = $value;
            if($key=='pictureUrls')
            {
                $userData['picture-url'] = $value->values[0];
            }
            if($key=='pictureUrl' && $userData['picture-url']=='')
            {
                $userData['picture-url'] = $value;
            }

            if($key=='emailAddress')
                $userData['email-address'] = $value;
            if($key=='publicProfileUrl'){
                $userData['public_url'] = $value;

                          }
            if($key=='summary')
                $userData['summary'] = $value;

            if($key=='twitter-accounts')
            {
                foreach($value as $key=>$val)
                 {
                    if($key=='twitter-account')
                    {
                        $valueTwit = json_encode($val);
                        $valueTwit = json_decode($valueTwit,true);
                        $userData['twitter-account'] = $userData['twitter-account'].",".$valueTwit['provider-account-name'];
                    }
                 }
                 $userData['twitter-account'] = substr($userData['twitter-account'],1,strlen($userData['twitter-account']));
            }

            if($key=='headline')
                $userData['headline'] = $value;

                        if($key=='positions')
                               {

                                foreach($value as $key1=>$val)
                {

                     if($key1=='values')
                                {

                $company_array = $val[0];
                                 foreach($company_array as $key2=>$val1)
                 {
                                   if($key2=='company')
                                    {
                    foreach($val1 as $key3=>$val3)
                    {
                            if($key3=='name')
                                         {
                            $userData['companyname'] = $val3;
                            }
                    }
                                    }

                                 }
                                }
                                }
                               }

                        if($key=='positions')
                               {

                                foreach($value as $keys1=>$vals)
                {

                     if($keys1=='values')
                                {

                $company_array1 = $vals[0];
                                 foreach($company_array1 as $keys2=>$vals1)
                 {

                                   if($keys2=='title')
                                    {
                                        $userData['designation'] = $vals1;
                                    }

                                 }
                                }
                                }
                               }

          }

          $userRequiredDetails = "";
                   $random = rand();
          $userRequiredDetails.="?oid=".$userData['linkedin_id']."&email=".$userData['email-address']."&random=".$random;

          $linkedinMenter_array =array('oid'=> $userData['linkedin_id']."<br/>",'first_name'=>$userData['first-name']."<br/>",'last_name'=>$userData['last-name']."<br/>",'image'=>$userData['picture-url']."<br/>",'email'=>$userData['email-address']."<br/>",'public_url'=>$userData['public_url']."<br/>",'summary'=>$userData['summary']."<br/>",'twitter-account'=>$userData['twitter-account']."<br/>",'headline'=>$userData['headline']."<br/>", 'companyname'=>$userData['companyname']."<br/>", 'designation'=>$userData['designation']."<br/>",'questionId'=>$questionId, 'questionURL'=>$questionURL, 'projectId'=>$projectId, 'directoryConsultationId'=>$directoryConsultationId, 'feedbackId' => $feedbackId, 'mentorshipId' => $mentorshipId, 'plan_id' => $plan_id, 'planUserId' => $planUserId, 'sresult' => $sresult, 'projectUserId' => $projectUserId);
           echo "Request token retrieval failed:<br /><br />RESPONSE:<br /><br />```" . print_r($linkedinMenter_array, TRUE) . "```<br /><br />LINKEDIN OBJ:<br /><br />```" . print_r($OBJ_linkedin, TRUE) . "```";
           exit;
          /* for data write in file */
          $file = "../".$userData['linkedin_id'].".txt";
          file_put_contents($file, $linkedinMenter_array);
                 echo $file;
                 exit;
          //header("location:https://example.com/users/signuplinkedin".$userRequiredDetails);

function getAuthorizationCode() {
    $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
              );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

echo print_r($_SESSION, TRUE) . "\n<br>";
echo print_r($params, TRUE) . "\n<br>";

echo "Pankaj getAuthorizationCode";

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}

function getAccessToken() {
    $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
              );

    // Access Token request
    $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

    // Tell streams to make a POST request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => 'POST',
                        )
                    )
                );

    // Retrieve access token information
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    $token = json_decode($response);
 echo print_r($token, TRUE) . "\n<br>";
    // Store access token and expiration time
    $_SESSION['access_token'] = $token->access_token; // guard this!
    $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
    $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time

echo "Pankaj getAccessToken"  . "\n<br>";
    return true;
}

function fetch($method, $resource, $body = '') {
    $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
              );

    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => $method,
                        )
                    )
                );

    // Hocus Pocus
    $response = file_get_contents($url, false, $context);
   //echo($response);
    // Native PHP object, please
    return json_decode($response);
}
</code>```

Getting this as a response in debug mode

```<code>stdClass Object ( [access_token] => AQX7maxbOfOpday8AEmpHyagkSKQcS26YYwMsocDx0FeIGPVwopJstJ27bqlSYrP754vT_DY6n1HoSr0kniJYY-RvhqvnX9ab4sczmzOYiqKo5p1ISVydiZJ_SiN-on9Hw12zD3tiktfvIPex6iHIi0dVhZ5-8CWWvdTX2Sj_d7YAusr9dJAmWQiNE3Aowe-i5cLlZSE-sOpzudCm3dns-ou2A4hg_NMLe5RAJcCQ2TlrGOiA29-1rZsN1_SJw5r4ZjLsx0HY8yUKmxmB1CnfOfg31y1RwlsDAaG679ILyGFvEqhdVJhcRrNzsHaI3JrDc1MJZTGAkBDCJt6WK9FexvqYHOLpw [expires_in] => 5184000 )
Pankaj getAccessToken
Fetching
Request token retrieval failed:

RESPONSE:

Array
(
    [oid] =>

    [first_name] =>

    [last_name] =>

    [image] =>

    [email] =>

    [public_url] =>

    [summary] =>

    [twitter-account] =>

    [headline] =>

    [companyname] =>

    [designation] =>

    [questionId] =>
    [questionURL] =>
    [projectId] =>
    [directoryConsultationId] =>
    [feedbackId] =>
    [mentorshipId] =>
    [plan_id] =>
    [planUserId] =>
    [sresult] =>
    [projectUserId] =>
)

LINKEDIN OBJ:
</code>```

答:
Use below code to receive access token</p>

```<code> $params = array('grant_type' => 'authorization_code',
            'client_id' => $this->api_key,
            'client_secret' => $this->api_secret,
            'code' => $_GET['code'],
            'redirect_uri' => base_url().$this->redirect,
        );
        // Access Token request
        $url = 'https://www.linkedin.com/oauth/v2/accessToken?' . http_build_query($params);
        $data_len = strlen(http_build_query($params));
        // Tell streams to make a POST request
        $context = stream_context_create(
                array('http' =>
                    array('method' => 'POST','header'=> 'Content-Length: 0'
                    )
                )
        );

        // Retrieve access token information
        $response = file_get_contents($url, false, $context);
        $token = json_decode($response);
        return $token->access_token;
</code>```

Body:
HI We are using LinkedIn API call at our website to get our website visitor details to logged in their profile through Linkedin.

The functionality was working fine but suddenly its stop working I checked in it.

We are getting Access Token Response in call but later on its fetching function is not working means not getting any values.I added some debug to check response and field value code and debug screenshot is attached

I tried to test made scope fields similar showing in app

define('SCOPE',        'r_basicprofile r_emailaddress'  --->
define('SCOPE',        'r_liteprofile r_emailaddress'

and update call code to latest method

https://www.linkedin.com/uas/oauth2/authorization ->> https://www.linkedin.com/oauth/v2/authorization

https://www.linkedin.com/uas/oauth2/accessToken?  ->>
https://www.linkedin.com/oauth/v2/accessToken

But still nothing change than I redo changs in code and this is the code

<?php
$config = include(dirname(__FILE__).'/config.php');
// Change these
define('API_KEY',      'XXXXXXXXX');
define('API_SECRET',   'XXXXXXXXX');
//define('REDIRECT_URI', ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")?'https':'http').'://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('REDIRECT_URI', ('https://example.com/linkedin/OAuth2.php'));
define('SCOPE',        'r_basicprofile r_emailaddress'                        );

// You'll probably use a database
    session_name('linkedin');
    session_start();

// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application

        getAccessToken();

} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
    $_SESSION['access_token'] = '';

    }
    if (empty($_SESSION['access_token']) || $_SESSION['access_token'] == '') {
        // Start authorization process
        getAuthorizationCode();
    }
}

echo "Fetching" . "
";
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(id,first-name,last-name,headline,email-address,picture-urls::(original),public-profile-url,picture-url,location,industry,site-standard-profile-request,interests,positions,summary,main-address,phone-numbers,skills:(skill))');

$userData = array('linkedin_id'=>'','first-name'=>'','last-name'=>'','picture-url'=>'','email-address'=>'','public_url'=>'','summary'=>'','twitter-account'=>'','headline'=>'','companyname'=>'','designation'=>'');

          foreach($user as $key=>$value)
          {

            if($key=='id')
                $userData['linkedin_id'] = $value;
            if($key=='firstName')
                $userData['first-name'] = $value;
            if($key=='lastName')
                $userData['last-name'] = $value;
            if($key=='pictureUrls')
            {
                $userData['picture-url'] = $value->values[0];
            }
            if($key=='pictureUrl' && $userData['picture-url']=='')
            {
                $userData['picture-url'] = $value;
            }

            if($key=='emailAddress')
                $userData['email-address'] = $value;
            if($key=='publicProfileUrl'){
                $userData['public_url'] = $value;

                          }
            if($key=='summary')
                $userData['summary'] = $value;

            if($key=='twitter-accounts')
            {
                foreach($value as $key=>$val)
                 {
                    if($key=='twitter-account')
                    {
                        $valueTwit = json_encode($val);
                        $valueTwit = json_decode($valueTwit,true);
                        $userData['twitter-account'] = $userData['twitter-account'].",".$valueTwit['provider-account-name'];
                    }
                 }
                 $userData['twitter-account'] = substr($userData['twitter-account'],1,strlen($userData['twitter-account']));
            }

            if($key=='headline')
                $userData['headline'] = $value;

                        if($key=='positions')
                               {

                                foreach($value as $key1=>$val)
                {

                     if($key1=='values')
                                {

                $company_array = $val[0];
                                 foreach($company_array as $key2=>$val1)
                 {
                                   if($key2=='company')
                                    {
                    foreach($val1 as $key3=>$val3)
                    {
                            if($key3=='name')
                                         {
                            $userData['companyname'] = $val3;
                            }
                    }
                                    }

                                 }
                                }
                                }
                               }

                        if($key=='positions')
                               {

                                foreach($value as $keys1=>$vals)
                {

                     if($keys1=='values')
                                {

                $company_array1 = $vals[0];
                                 foreach($company_array1 as $keys2=>$vals1)
                 {

                                   if($keys2=='title')
                                    {
                                        $userData['designation'] = $vals1;
                                    }

                                 }
                                }
                                }
                               }

          }

          $userRequiredDetails = "";
                   $random = rand();
          $userRequiredDetails.="?oid=".$userData['linkedin_id']."&email=".$userData['email-address']."&random=".$random;

          $linkedinMenter_array =array('oid'=> $userData['linkedin_id']."
",'first_name'=>$userData['first-name']."
",'last_name'=>$userData['last-name']."
",'image'=>$userData['picture-url']."
",'email'=>$userData['email-address']."
",'public_url'=>$userData['public_url']."
",'summary'=>$userData['summary']."
",'twitter-account'=>$userData['twitter-account']."
",'headline'=>$userData['headline']."
", 'companyname'=>$userData['companyname']."
", 'designation'=>$userData['designation']."
",'questionId'=>$questionId, 'questionURL'=>$questionURL, 'projectId'=>$projectId, 'directoryConsultationId'=>$directoryConsultationId, 'feedbackId' => $feedbackId, 'mentorshipId' => $mentorshipId, 'plan_id' => $plan_id, 'planUserId' => $planUserId, 'sresult' => $sresult, 'projectUserId' => $projectUserId);
           echo "Request token retrieval failed:

RESPONSE:

" . print_r($linkedinMenter_array, TRUE) . "

LINKEDIN OBJ:

" . print_r($OBJ_linkedin, TRUE) . "
";
           exit;
          /* for data write in file */
          $file = "../".$userData['linkedin_id'].".txt";
          file_put_contents($file, $linkedinMenter_array);
                 echo $file;
                 exit;
          //header("location:https://example.com/users/signuplinkedin".$userRequiredDetails);

function getAuthorizationCode() {
    $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
              );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

echo print_r($_SESSION, TRUE) . "\n
";
echo print_r($params, TRUE) . "\n
";

echo "Pankaj getAuthorizationCode";

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}

function getAccessToken() {
    $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
              );

    // Access Token request
    $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

    // Tell streams to make a POST request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => 'POST',
                        )
                    )
                );

    // Retrieve access token information
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    $token = json_decode($response);
 echo print_r($token, TRUE) . "\n
";
    // Store access token and expiration time
    $_SESSION['access_token'] = $token->access_token; // guard this!
    $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
    $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time

echo "Pankaj getAccessToken"  . "\n
";
    return true;
}

function fetch($method, $resource, $body = '') {
    $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
              );

    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => $method,
                        )
                    )
                );

    // Hocus Pocus
    $response = file_get_contents($url, false, $context);
   //echo($response);
    // Native PHP object, please
    return json_decode($response);
}

Getting this as a response in debug mode

stdClass Object ( [access_token] => AQX7maxbOfOpday8AEmpHyagkSKQcS26YYwMsocDx0FeIGPVwopJstJ27bqlSYrP754vT_DY6n1HoSr0kniJYY-RvhqvnX9ab4sczmzOYiqKo5p1ISVydiZJ_SiN-on9Hw12zD3tiktfvIPex6iHIi0dVhZ5-8CWWvdTX2Sj_d7YAusr9dJAmWQiNE3Aowe-i5cLlZSE-sOpzudCm3dns-ou2A4hg_NMLe5RAJcCQ2TlrGOiA29-1rZsN1_SJw5r4ZjLsx0HY8yUKmxmB1CnfOfg31y1RwlsDAaG679ILyGFvEqhdVJhcRrNzsHaI3JrDc1MJZTGAkBDCJt6WK9FexvqYHOLpw [expires_in] => 5184000 )
Pankaj getAccessToken
Fetching
Request token retrieval failed:

RESPONSE:

Array
(
    [oid] =>

    [first_name] =>

    [last_name] =>

    [image] =>

    [email] =>

    [public_url] =>

    [summary] =>

    [twitter-account] =>

    [headline] =>

    [companyname] =>

    [designation] =>

    [questionId] =>
    [questionURL] =>
    [projectId] =>
    [directoryConsultationId] =>
    [feedbackId] =>
    [mentorshipId] =>
    [plan_id] =>
    [planUserId] =>
    [sresult] =>
    [projectUserId] =>
)

LINKEDIN OBJ:

Body:
Use below code to receive access token

 $params = array('grant_type' => 'authorization_code',
            'client_id' => $this->api_key,
            'client_secret' => $this->api_secret,
            'code' => $_GET['code'],
            'redirect_uri' => base_url().$this->redirect,
        );
        // Access Token request
        $url = 'https://www.linkedin.com/oauth/v2/accessToken?' . http_build_query($params);
        $data_len = strlen(http_build_query($params));
        // Tell streams to make a POST request
        $context = stream_context_create(
                array('http' =>
                    array('method' => 'POST','header'=> 'Content-Length: 0'
                    )
                )
        );

        // Retrieve access token information
        $response = file_get_contents($url, false, $context);
        $token = json_decode($response);
        return $token->access_token;


问:
Calculate conditional probability using groupby and shift operations in Pandas dataframe
I have a dataframe with patients and their visits and the presence of a disease in their left and/or right eye is labeled with {0,1} values (0 = not present and 1 = present). The dataset looks like this:

```<code>Patient   R L

P_1       0 1

P_1       1 1

P_1       0 1

P_1       0 1

P_1       0 1

P_2       1 1

P_2       0 1

P_2       0 1

P_2       1 1

P_3       0 0

P_3       1 1

P_3       0 0

P_3       0 1

P_3       1 1

P_3       0 1

and so on.....
</code>```

How can I calculate, for example, the conditional probability of P(R=1 | L=1) using grouby and shift operations in an elegant way?

答:
IIUC:

```<code>df.groupby('L').R.mean()
</code>```

gives

```<code>L
0    0.000000
1    0.384615
Name: R, dtype: float64
</code>```

So the answer: P(R=1|L=1) = 0.384, and P(R=1|L=0) = 0.

Or if we want to get probability on patients as well:

```<code>df.groupby(['Patient','L']).R.mean()
</code>```

gives:

```<code>Patient  L
P_1      1    0.2
P_2      1    0.5
P_3      0    0.0
         1    0.5
Name: R, dtype: float64
</code>```

so, for example, P(R=1|Patent=P_3, L=1) = 0.5.

Body:
I have a dataframe with patients and their visits and the presence of a disease in their left and/or right eye is labeled with {0,1} values (0 = not present and 1 = present). The dataset looks like this:

Patient   R L

P_1       0 1

P_1       1 1

P_1       0 1

P_1       0 1

P_1       0 1

P_2       1 1

P_2       0 1

P_2       0 1

P_2       1 1

P_3       0 0

P_3       1 1

P_3       0 0

P_3       0 1

P_3       1 1

P_3       0 1

and so on.....

How can I calculate, for example, the conditional probability of P(R=1 | L=1) using grouby and shift operations in an elegant way?

Body:
IIUC:

df.groupby('L').R.mean()

gives

L
0    0.000000
1    0.384615
Name: R, dtype: float64

So the answer: P(R=1|L=1) = 0.384, and P(R=1|L=0) = 0.

Or if we want to get probability on patients as well:

df.groupby(['Patient','L']).R.mean()

gives:

Patient  L
P_1      1    0.2
P_2      1    0.5
P_3      0    0.0
         1    0.5
Name: R, dtype: float64

so, for example, P(R=1|Patent=P_3, L=1) = 0.5.


问:
How to use toLowerCase method in amp- mustache template variable
I am binding the amp-list with a JSON. The problem is I am providing the array element for amp-img and the src for amp-img must be in lower case as the asset on my server is in lowercase.</p>

```<code><amp-list layout="fixed-height" height= "10" [height]="getData().length * 50"
   [src]="getData()" id="datalist" items=".">
    <template type="amp-mustache">
        <amp-img alt="image"
            width="100"
            height="100"
            src="static/{{name}}.png">
            // I want to use {{name.toLowerCase()}} here which is causing the problem
           // Current src= "static/XYZ.png"
          // Expected src= "static/xyz.png"
        </amp-img>
    </template>
</amp-list>
</code>```

答:
After trying multiple approaches, I achieved what I wanted to like this: [src]="'static/{{ name }}.png'.toLowerCase()"

Code Sample:

```<code><amp-list layout="fixed-height" height= "10" [height]="getData().length * 50"
[src]="getData()" id="datalist" items=".">
    <template type="amp-mustache">
        <amp-img alt="image"
            width="100"
            height="100"
            [src]="'static/{{ name }}.png'.toLowerCase()">
        </amp-img>
    </template>
</amp-list>
</code>```

Body:
I am binding the amp-list with a JSON. The problem is I am providing the array element for amp-img and the src for amp-img must be in lower case as the asset on my server is in lowercase.

<amp-list layout="fixed-height" height= "10" [height]="getData().length * 50"
   [src]="getData()" id="datalist" items=".">
    <template type="amp-mustache">
        <amp-img alt="image"
            width="100"
            height="100"
            src="static/{{name}}.png">
            // I want to use {{name.toLowerCase()}} here which is causing the problem
           // Current src= "static/XYZ.png"
          // Expected src= "static/xyz.png"
        </amp-img>
    </template>
</amp-list>

Body:
After trying multiple approaches, I achieved what I wanted to like this: [src]="'static/{{ name }}.png'.toLowerCase()"

Code Sample:

<amp-list layout="fixed-height" height= "10" [height]="getData().length * 50"
[src]="getData()" id="datalist" items=".">
    <template type="amp-mustache">
        <amp-img alt="image"
            width="100"
            height="100"
            [src]="'static/{{ name }}.png'.toLowerCase()">
        </amp-img>
    </template>
</amp-list>


问:
What is a good algorithm for mapping random (barcode values) numbers to an String in a collection?
Say that my application has a finite number of "stuff", in my case they will be items in my game but for the purposes of this question I'll use Strings.

Say I have 5 Strings :

James

Dave

John

Steve

Jack

There will be a set list of them, however I will increase that list in the future.

Question : What is a good algorithm I can use, to go from a random number (generated from a barcode) into one of those values from above?

For example, if I have the value 4523542354254, then what algorithm could I use to map that onto Dave? If I have that same number again, I need to make sure it maps to Dave and not to something else each time.

One option I did consider was taking the last digit of the barcode and using the 0-9 that would map onto 10 items, but its not very future proof if I added an 11th item.

Any suggestions?

答:
Hmm... If it is OK that multiple values can be mapped to the one, you can use</p>

```<code>string name = names[value % number_of_names];
</code>```

Body:
Hmm... If it is OK that multiple values can be mapped to the one, you can use

string name = names[value % number_of_names];


问:
asp.et core 2.1 change password length attributes in scaffolded login/register pages
Does anyone know how I can change (i.e., increase) the max allowed password length? The scaffolded login/register pages contain the attribute:

```<code>data-val-length="The Password must be at least 6 and at max 100 characters long." data-val-length-max="100" data-val-length-min="6"
</code>```

They prevent longer passwords. I've tried setting options.Stores.MaxLengthForKeys = 1024 but that did result in any noticeable changes in these attributes at run-time.

答:
The validation is specified as an attribute on the Password property on the page model. You'll have to scaffold in the Register.cshtml Razor Page and then modify it there.

If you haven't scaffolded in stuff from the Identity default UI before, just right-click on your project in the Solution Explorer and choose Add > New Scaffolded Item. Select the Identity item on the left, and then the only available scaffold presented, and choose OK. This will pop a dialog with a list of all the available Razor Pages in the default UI. Select the one(s) you want, and then OK again.

Once you have the page in your project, open the Register.cshtml.cs codebehind and find the Password property. Modify the attribute as you like.

Body:
Does anyone know how I can change (i.e., increase) the max allowed password length? The scaffolded login/register pages contain the attribute:

data-val-length="The Password must be at least 6 and at max 100 characters long." data-val-length-max="100" data-val-length-min="6"

They prevent longer passwords. I've tried setting options.Stores.MaxLengthForKeys = 1024 but that did result in any noticeable changes in these attributes at run-time.


问:
Random number generator in VHDL
I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user.
I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

```<code>RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;
</code>```

Is there any alternatives for this problem?

答:
I don't know anything of VHDL, but in general I try to avoid randomness in tests. Flaky unit tests, for example, are bad. What's the value of a test that fails only sometimes?

Anyway, supposed you really want to do it, do you have access to a timer? You can initialize the PRNG with the current time as seed. Not cryptographically safe, but probably for this use case good enough.

Title: Random number generator in VHDL

Body:
I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user.
I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;

Is there any alternatives for this problem?


问:
Unable to hide the column header based on the boolean value in the component
I am trying to show and hide a header and row based on a boolean value in component. I am able to hide the specific td but not able to hide the specific column. In the example below , I am trying to hide Last Edited row which includes th and td element. If I set the boolean variable to false, the td for that column is not shown but how do i hide the header. It doesn't seem to work if I put the following condition

```<code>  <th *ngIf="c == ColumnNames[1] && showCol""
</code>```

Html

```<code> <div *ngIf="LegalFundClasses && LegalFundClasses.LegalFundClassDetailsViewModel && ColumnNames">
     <table class="fundClassesTable table-striped">
      <tr *ngFor="let c of ColumnNames">
        <th [ngClass]="c != ColumnNames[2] ? 'tableItem bold' : 'cellbgcolor'" >{{ c }}</th>
        <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
          <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[1] && showCol">{{f.AuditSummary}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td
        </ng-container>
      </tr>
    </table>
  </div>
</code>```

Component

```<code> public showCol: boolean = false;
 public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];
</code>```

Here is the fiddle

https://jsfiddle.net/zyk9xhd1/9/

答:
You are better off putting the condition on the whole tr

With the code below, it'll only display the rows based on a boolean array declared in the component

```<code>  <tr *ngFor="let c of ColumnNames; let rowIndex = index">
  <ng-container *ngIf="rowVisibility[rowIndex]">
    <th [ngClass]="c != ColumnNames[2] ? 'tableItem bold' : 'cellbgcolor'" >{{ c }}</th>
    <ng-container *ngFor="let f of data">
      <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
      <td class="tableItem" *ngIf="c == ColumnNames[1]">{{f.AuditSummary}}</td>
      <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td>
    </ng-container>
 </ng-container>
</tr>
</code>```

component.ts

```<code>constructor(){

    //decide which row ro show
    public rowVisibility = [true, //1strow
     false, //2nd row
     true//3rd row
];
</code>```

Example on jsfiddle

Body:
I am trying to show and hide a header and row based on a boolean value in component. I am able to hide the specific td but not able to hide the specific column. In the example below , I am trying to hide Last Edited row which includes th and td element. If I set the boolean variable to false, the td for that column is not shown but how do i hide the header. It doesn't seem to work if I put the following condition

  <th *ngIf="c == ColumnNames[1] && showCol""

Html

        {{ c }}
        <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
          {{f.Description}}
          {{f.AuditSummary}}
          {{f.Id}}</td
        </ng-container>

Component

 public showCol: boolean = false;
 public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];

Here is the fiddle

https://jsfiddle.net/zyk9xhd1/9/

Body:
You are better off putting the condition on the whole tr

With the code below, it'll only display the rows based on a boolean array declared in the component

  <tr *ngFor="let c of ColumnNames; let rowIndex = index">
  <ng-container *ngIf="rowVisibility[rowIndex]">
    <th [ngClass]="c != ColumnNames[2] ? 'tableItem bold' : 'cellbgcolor'" >{{ c }}</th>
    <ng-container *ngFor="let f of data">
      <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
      <td class="tableItem" *ngIf="c == ColumnNames[1]">{{f.AuditSummary}}</td>
      <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td>
    </ng-container>
 </ng-container>
</tr>

component.ts

constructor(){

    //decide which row ro show
    public rowVisibility = [true, //1strow
     false, //2nd row
     true//3rd row
];

Example on jsfiddle


问:
unable to parse specific value from a particular column of a csv file
I am making a predictive model to predict revenue and trying to parse this 'cast' value from the data frame as it is not a list or a dict

```<code>x['cast']
</code>```

And the output is

```<code>0    [{'cast_id': 4, 'character': 'Lou', 'credit_id...
1    [{'cast_id': 1, 'character': 'Mia Thermopolis'...
2    [{'cast_id': 5, 'character': 'Andrew Neimann',...
3    [{'cast_id': 1, 'character': 'Vidya Bagchi', '...
4    [{'cast_id': 3, 'character': 'Chun-soo', 'cred...
5    [{'cast_id': 6, 'character': 'Pinocchio (voice...
6    [{'cast_id': 23, 'character': 'Clyde', 'credit...
7    [{'cast_id': 2, 'character': 'Himself', 'credi...
8    [{'cast_id': 1, 'character': 'Long John Silver...
9    [{'cast_id': 24, 'character': 'Jonathan Steinb...
Name: cast, dtype: object
</code>```

I need all the 'character' values in a list.
but when I try

```<code>x['cast'][0]['character']
</code>```

It throws this error

```<code>TypeError: string indices must be integers
</code>```

Help me out with this please.

答:
First convert json to list of dictionaries and then get values from first list by key of dict:

```<code>import ast

mask = x['cast'].notna()

x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(ast.literal_eval)
#alternative
#x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(pd.io.json.loads)
x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(lambda x: x[0].get('character', 'not match data'))
</code>```

EDIT:

If still problem use Series.str.extract:

```<code>x = pd.DataFrame({'cast':[[{'cast_id': 4, 'character': 'Lou'}], np.nan]})

x['cat'] = x['cast'].astype(str).str.extract("'character': '([^'']+)'")
print (x)
                                   cast  cat
0  [{'cast_id': 4, 'character': 'Lou'}]  Lou
1                                   NaN  NaN
</code>```

Body:
I am making a predictive model to predict revenue and trying to parse this 'cast' value from the data frame as it is not a list or a dict

x['cast']

And the output is

0    [{'cast_id': 4, 'character': 'Lou', 'credit_id...
1    [{'cast_id': 1, 'character': 'Mia Thermopolis'...
2    [{'cast_id': 5, 'character': 'Andrew Neimann',...
3    [{'cast_id': 1, 'character': 'Vidya Bagchi', '...
4    [{'cast_id': 3, 'character': 'Chun-soo', 'cred...
5    [{'cast_id': 6, 'character': 'Pinocchio (voice...
6    [{'cast_id': 23, 'character': 'Clyde', 'credit...
7    [{'cast_id': 2, 'character': 'Himself', 'credi...
8    [{'cast_id': 1, 'character': 'Long John Silver...
9    [{'cast_id': 24, 'character': 'Jonathan Steinb...
Name: cast, dtype: object

I need all the 'character' values in a list.
but when I try

x['cast'][0]['character']

It throws this error

TypeError: string indices must be integers

Help me out with this please.

Body:
First convert json to list of dictionaries and then get values from first list by key of dict:

import ast

mask = x['cast'].notna()

x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(ast.literal_eval)
#alternative
#x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(pd.io.json.loads)
x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(lambda x: x[0].get('character', 'not match data'))

EDIT:

If still problem use Series.str.extract:

x = pd.DataFrame({'cast':[[{'cast_id': 4, 'character': 'Lou'}], np.nan]})

x['cat'] = x['cast'].astype(str).str.extract("'character': '([^'']+)'")
print (x)
                                   cast  cat
0  [{'cast_id': 4, 'character': 'Lou'}]  Lou
1                                   NaN  NaN


问:
done is not a function in passport.js
```<code>const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');

var User = mongoose.model('User');

passport.use(
    new localStrategy({ usernameField: 'email' },
        (req, username, password, done) => {
            User.findOne({ email: username },
                (err, user) => {

                    if (err)
                        return done(err);
                    // unknown user
                    else if (!user)
                        return done(null, false, { message: 'Email is not registered' });
                    // wrong password
                    else if (!user.verifyPassword(password))
                        return done(null, false, { message: 'Wrong password.' });
                    // wrong type
                    else if (!user.verifyType(req.body.type))
                        return done(null, false, { message: 'Wrong type.' });
                    // authentication succeeded
                    else
                        return done(null, user);
                });
        })
);
</code>```

done is not a function is the error
Using PassportJS, how pass one additional form fields to the local authentication strategy?

答:
just remove the "req" parameter in the anonymous function inside new localStrategy and you should be fine.

You don't have the req parameter anywhere on this code, so you can't use it in there

like this:

```<code> (username, password, done) => {
</code>```

Title: done is not a function in passport.js

Body:
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');

var User = mongoose.model('User');

passport.use(
    new localStrategy({ usernameField: 'email' },
        (req, username, password, done) => {
            User.findOne({ email: username },
                (err, user) => {

                    if (err)
                        return done(err);
                    // unknown user
                    else if (!user)
                        return done(null, false, { message: 'Email is not registered' });
                    // wrong password
                    else if (!user.verifyPassword(password))
                        return done(null, false, { message: 'Wrong password.' });
                    // wrong type
                    else if (!user.verifyType(req.body.type))
                        return done(null, false, { message: 'Wrong type.' });
                    // authentication succeeded
                    else
                        return done(null, user);
                });
        })
);

done is not a function is the error
Using PassportJS, how pass one additional form fields to the local authentication strategy?

Body:
just remove the "req" parameter in the anonymous function inside new localStrategy and you should be fine.

You don't have the req parameter anywhere on this code, so you can't use it in there

like this:

 (username, password, done) => {


问:
useEffect function open/close modal based in props works only at first time (click)
Im learning React and using the new implemented "Hooks" from Documentation. I got a problem with a Modal (Dialog from Material UI) and the open/close function using useEffect() function.

I have already read these both articles: React.useState does not reload state from props and How to sync props to state using React hook : setState()

It's already helped me, I have forgot to use the useEffect() function instead I was just setting the useState from what comes from props. Learned that useState will be executed only one time for setting the initial state. But I have however more one problem.

```<code>function AddItemModal(props) {
  const [open, setOpen] = useState(props.isOpen);

  useEffect(() => {
    setOpen(props.isOpen);
  }, [props.isOpen]);

  function handleClose() {
    setOpen(false);
  }
</code>```

That works for the first time when I click at the add button (in another Component) and handle the click (it changes the state to true) and I pass it as props to the Modal. But when I click (in modal) at close and try to click at add to open it again, nothing happens. In case needed, here's the code from the component where I handle the click and call the modal.

```<code>function ItemsTable() {
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  const handleAddClick = () => {
    setAddModalOpen(true);
  };

  <Box mt={4} position="fixed" bottom={10} right={10}>
    <Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
      <AddIcon />
    </Fab>
  </Box>
  <AddItemModal isOpen={addModalOpen} />
</code>```

答:
You have split your modal state across two components which is confusing and going to lead to bugs like this. You should put the state in one place and update it where necessary. In this case, you could keep the modal state in the ItemsTable and pass in a handler for the modal to access.

Something like:

```<code>function ItemsTable() {
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  const handleAddClick = () => {
    setAddModalOpen(true);
  };
  const handleClose = ()=>{
    setAddModalOpen(false)
  }
  <Box mt={4} position="fixed" bottom={10} right={10}>
    <Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
      <AddIcon />
    </Fab>
  </Box>
  <AddItemModal isOpen={addModalOpen} handleClose={handleClose}/>
</code>```

Body:
Im learning React and using the new implemented "Hooks" from Documentation. I got a problem with a Modal (Dialog from Material UI) and the open/close function using useEffect() function.

I have already read these both articles: React.useState does not reload state from props and How to sync props to state using React hook : setState()

It's already helped me, I have forgot to use the useEffect() function instead I was just setting the useState from what comes from props. Learned that useState will be executed only one time for setting the initial state. But I have however more one problem.

function AddItemModal(props) {
  const [open, setOpen] = useState(props.isOpen);

  useEffect(() => {
    setOpen(props.isOpen);
  }, [props.isOpen]);

  function handleClose() {
    setOpen(false);
  }

That works for the first time when I click at the add button (in another Component) and handle the click (it changes the state to true) and I pass it as props to the Modal. But when I click (in modal) at close and try to click at add to open it again, nothing happens. In case needed, here's the code from the component where I handle the click and call the modal.

function ItemsTable() {
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  const handleAddClick = () => {
    setAddModalOpen(true);
  };

  <Box mt={4} position="fixed" bottom={10} right={10}>
    <Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
      <AddIcon />
    </Fab>
  </Box>
  <AddItemModal isOpen={addModalOpen} />

Body:
You have split your modal state across two components which is confusing and going to lead to bugs like this. You should put the state in one place and update it where necessary. In this case, you could keep the modal state in the ItemsTable and pass in a handler for the modal to access.

Something like:

function ItemsTable() {
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  const handleAddClick = () => {
    setAddModalOpen(true);
  };
  const handleClose = ()=>{
    setAddModalOpen(false)
  }
  <Box mt={4} position="fixed" bottom={10} right={10}>
    <Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
      <AddIcon />
    </Fab>
  </Box>
  <AddItemModal isOpen={addModalOpen} handleClose={handleClose}/>


问:
502 Bad Gateway with nginx | Google App Engine | Node JS
I am hosting the web app on Google Cloud Platform with App Engine and I am using ExpressJS and MongoDB, which is hosted on mLab.

Everything worked well until 1/1/2017. I had vm:true before and now was forced to change the env to flex. Now I am getting 502 bad gateway error with nginx. App engine doesn't allow us to change the nginx config file.

I had tried the suggestion from this post: Google App Engine 502 (Bad Gateway) with NodeJS but still doesn't work.

For some reason, I have another app with exactly the same setting on app engine and it works perfectly.

Any suggestion will be greatly appreciated. Thank you.

答:
Create a server and then check with a ternary condition if current environment is production or not, assign port '80' if current environment is development else assign process.env.NODE.ENV. </p>

```<code>const app = require('express')();
        const server = require('http').Server(app);
        const port = process.env.NODE_ENV === 'production' ? process.env.PORT :'80';
        server.listen(port, ()=> {
          console.log('listening on port number  *:' + server.address().port);
         });
</code>```

Body:
Create a server and then check with a ternary condition if current environment is production or not, assign port '80' if current environment is development else assign process.env.NODE.ENV.

const app = require('express')();
        const server = require('http').Server(app);
        const port = process.env.NODE_ENV === 'production' ? process.env.PORT :'80';
        server.listen(port, ()=> {
          console.log('listening on port number  *:' + server.address().port);
         });


问:
How to get Number of bands from a Bitmap in Android Device?
I am doing an Image Processing algorithm using BoofCV in Android Client. For this, I did a demo on the server side using BufferedImage.

For that, my code was:

```<code>int numBands = bufferedImage.getRaster().getNumBands()
</code>```

Now, I need to get the number of bands from a Bitmap Image.

Can anyone tell me how I can do this?

Thanks in advance!!

答:
As far as I understand, there is no concept directly equal to "bands" in Android Bitmaps.

You can look at the Bitmap.Config to get some idea of the pixel layout and how colors are stored. I believe ARGB_8888 is the most common one.

Body:
I am doing an Image Processing algorithm using BoofCV in Android Client. For this, I did a demo on the server side using BufferedImage.

For that, my code was:

int numBands = bufferedImage.getRaster().getNumBands()

Now, I need to get the number of bands from a Bitmap Image.

Can anyone tell me how I can do this?

Thanks in advance!!


答:
React Navigation have events listener Component called "NavigationEvents" that can be used to know when the screen is active or inactive.

you can implement it to your code like this:

```<code>import { NavigationEvents } from 'react-navigation';

<View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>

<NavigationEvents
      // try only this. and your component will auto refresh when this is the active component
      onWillFocus={payload => this.setState({})}
      // other props
      onDidFocus={payload => console.log('did focus',payload)}
      onWillBlur={payload => console.log('will blur',payload)}
      onDidBlur={payload => console.log('did blur',payload)}
    />
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>
            <Body
              style={{ textAlign: 'center', width: '100%', flexGrow: 2, alignItems: 'center', justifyContent: 'center' }}>
            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}
            </Body>
            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
</View>
</code>```

reference for NavigationEvents: react-navigation navigation events

Title: How to re render component on goBack icon press in header

Body:
I am trying to re render the component after goBack press . By using goBack I am able to go back page ,but that page is not getting refresh. How I can solve it ?
After goBack I have to call some api ,and now after back non of the function is getting call . I can only call if page will refresh or rerender .

Example , from page 1 header am clicking back arrow icon (i.e goBack fucntion) to go on Page 1 and after going page 1 it should refresh .

<View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>

            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}

            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
          </View>

Thanks

Body:
React Navigation have events listener Component called "NavigationEvents" that can be used to know when the screen is active or inactive.

you can implement it to your code like this:

import { NavigationEvents } from 'react-navigation';

<View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>

<NavigationEvents
      // try only this. and your component will auto refresh when this is the active component
      onWillFocus={payload => this.setState({})}
      // other props
      onDidFocus={payload => console.log('did focus',payload)}
      onWillBlur={payload => console.log('will blur',payload)}
      onDidBlur={payload => console.log('did blur',payload)}
    />
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>
            <Body
              style={{ textAlign: 'center', width: '100%', flexGrow: 2, alignItems: 'center', justifyContent: 'center' }}>
            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}
            </Body>
            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
</View>

reference for NavigationEvents: react-navigation navigation events


问:
Why does my decorator execute the code in this order?
I have the following code and I have a hard time understanding why it prints the statements in the order it does.

```<code>def main():
    print('1')
    registry=[]

def register(func):
    print('2')
    registry.append(func)
    return func

@register
def f1():
    print('3')
print('4')
f1()
main()
</code>```

This code prints:

```<code>1
2
4
3
</code>```

But I'm wondering why it doesn't print:

```<code>1
2
3
4
</code>```

when the @register is called I understand it that register(f1) is called, it prints 2 and then f1 is returned. To me it seems like 3 should be printed next since f1 is returned. But instead f1 is not called until the very end f1() statement. Doesn't return func run the function it returns?

答:
Consider the equivalent code that doesn't use decorator syntax. Also, we make registry a pre-defined global so that the code actually runs.

```<code>registry = []

def main():
    print('1')
    #registry=[]

def register(func):
    print('2')
    registry.append(func)
    return func

def f1():
    print('3')

f1 = register(f1)
print('4')
f1()
main()
</code>```

The first function that gets called is register, so the first value output is 2. Next, print('4') outputs 4. Third, f1 is called and outputs 3. Finally, main is called and outputs 1.

register never calls f1; it simply adds it to the list registry and returns it.

Body:
I have the following code and I have a hard time understanding why it prints the statements in the order it does.

def main():
    print('1')
    registry=[]

def register(func):
    print('2')
    registry.append(func)
    return func

@register
def f1():
    print('3')
print('4')
f1()
main()

This code prints:

1
2
4
3

But I'm wondering why it doesn't print:

1
2
3
4

when the @register is called I understand it that register(f1) is called, it prints 2 and then f1 is returned. To me it seems like 3 should be printed next since f1 is returned. But instead f1 is not called until the very end f1() statement. Doesn't return func run the function it returns?

Body:
Consider the equivalent code that doesn't use decorator syntax. Also, we make registry a pre-defined global so that the code actually runs.

registry = []

def main():
    print('1')
    #registry=[]

def register(func):
    print('2')
    registry.append(func)
    return func

def f1():
    print('3')

f1 = register(f1)
print('4')
f1()
main()

The first function that gets called is register, so the first value output is 2. Next, print('4') outputs 4. Third, f1 is called and outputs 3. Finally, main is called and outputs 1.

register never calls f1; it simply adds it to the list registry and returns it.