问:
Extract rows with duplicates entries in one column satisfying a given condition in another column
I have a sample dataframe with duplicate entries in the first column given below:

```<code>df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0
</code>```

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

```<code>aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2
</code>```

but I have not been able to solve the problem.

Desired Output: The output should look like this:

```<code>df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0
</code>```

Thanks!

答:
You can use slice, i.e.

```<code>library(dplyr)

df %>%
 group_by(ID) %>%
 slice(which(Type == 1)[1]:n())
</code>```

which gives,

```<code># A tibble: 7 x 3
# Groups:   ID [4]
     ID  Type   sex
  <dbl> <dbl> <dbl>
1   101     1     0
2   101     1     0
3   102     1     1
4   102     2     1
5   103     1     1
6   104     1     0
7   104     2     0
</code>```

Body:
I have a sample dataframe with duplicate entries in the first column given below:

df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2

but I have not been able to solve the problem.

Desired Output: The output should look like this:

df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0

Thanks!

Body:
You can use slice, i.e.

library(dplyr)

df %>%
 group_by(ID) %>%
 slice(which(Type == 1)[1]:n())

which gives,

# A tibble: 7 x 3
# Groups:   ID [4]
     ID  Type   sex
  <dbl> <dbl> <dbl>
1   101     1     0
2   101     1     0
3   102     1     1
4   102     2     1
5   103     1     1
6   104     1     0
7   104     2     0


来源: stackexchange

问:
Bind a function to all text input - jQuery
I want to bind a function to all the textarea and want to run it whenever a key gets pressed.

```<code>function fx(docid)
{
  $('#'+docid).val=encodeURIComponent($('#'+docid).val());
  //document.getElementByID('docid').value = encodeURIComponent(document.getElementByID('docid').value);
}
</code>```

Note: the page will have different textarea, I want a single function to do the same job for all the textarea. I don't want to hard code the event with the textarea <textarea onkeydown="..." />

Edit

I want to trigger the function on multiple events, thats on keypress, keydown,click

答:
Similar to @mVChr's answer,

```<code>$('textarea').bind('keypress keydown click', function (e) {
    var $this = $(this);
    $this.val(encodeURIComponent($this.val()));
});
</code>```

but you almost certainly don't want to run the exact same function on keypress and on keydown.

ContentLicense: CC BY-SA 3.0

Body:
I want to bind a function to all the textarea and want to run it whenever a key gets pressed.

function fx(docid)
{
  $('#'+docid).val=encodeURIComponent($('#'+docid).val());
  //document.getElementByID('docid').value = encodeURIComponent(document.getElementByID('docid').value);
}

Note: the page will have different textarea, I want a single function to do the same job for all the textarea. I don't want to hard code the event with the textarea <textarea onkeydown="..." />

Edit

I want to trigger the function on multiple events, thats on keypress, keydown,click

Body:
Similar to @mVChr's answer,

$('textarea').bind('keypress keydown click', function (e) {
    var $this = $(this);
    $this.val(encodeURIComponent($this.val()));
});

but you almost certainly don't want to run the exact same function on keypress and on keydown.


问:
How to use global URLSearchParams in node
I am writing a (client-side) JavaScript library (a node/angular module).
In this library, I make use of the URLSearchParams class.

```<code>const form = new URLSearchParams();
form.set('username', data.username);
form.set('password', data.pass);
</code>```

As this is a shared library, it is packed as an npm module.
However, when running a mocha unit test, I get the error that URLSearchParams is not defined. The reason seems to be that node does not have URLSearchParams at the global scope, but has to be imported using require('url'):

```<code>$ node
> new URLSearchParams()
ReferenceError: URLSearchParams is not defined
    at repl:1:5
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
</code>```

How can I make URLSearchParams available to the client-side code within node, so that I can test the library using mocha?

This is not working:

```<code>> global.URLSearchParams = require('url').URLSearchParams
undefined
> new URLSearchParams()
TypeError: URLSearchParams is not a constructor
    at repl:1:1
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
</code>```

答:
You may use polifill @ungap/url-search-params https://www.npmjs.com/package/@ungap/url-search-params and for webpack may use @ungap/url-search-params/cjs

Old NodeJS 8 (which isused in AWS and GCloud) does not support URLSearchParams so this polifill helps.

In Node 10 when using TypeScript you may enable library dom which includes URLSearchParams implementation. Change tsconfig.json:

```<code>{
  "compilerOptions": {
    "lib": [
      ...
      "dom"
      ...
    ]
  }
}
</code>```

Body:
I am writing a (client-side) JavaScript library (a node/angular module).
In this library, I make use of the URLSearchParams class.

const form = new URLSearchParams();
form.set('username', data.username);
form.set('password', data.pass);

As this is a shared library, it is packed as an npm module.
However, when running a mocha unit test, I get the error that URLSearchParams is not defined. The reason seems to be that node does not have URLSearchParams at the global scope, but has to be imported using require('url'):

$ node
> new URLSearchParams()
ReferenceError: URLSearchParams is not defined
    at repl:1:5
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)

How can I make URLSearchParams available to the client-side code within node, so that I can test the library using mocha?

This is not working:

> global.URLSearchParams = require('url').URLSearchParams
undefined
> new URLSearchParams()
TypeError: URLSearchParams is not a constructor
    at repl:1:1
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)

Body:
You may use polifill @ungap/url-search-params https://www.npmjs.com/package/@ungap/url-search-params and for webpack may use @ungap/url-search-params/cjs

Old NodeJS 8 (which isused in AWS and GCloud) does not support URLSearchParams so this polifill helps.

In Node 10 when using TypeScript you may enable library dom which includes URLSearchParams implementation. Change tsconfig.json:

{
  "compilerOptions": {
    "lib": [
      ...
      "dom"
      ...
    ]
  }
}

ContentLicense: CC BY-SA 4.0


问:
ImportError: No module named requests_oauthlib
Trying to tweet on my Raspberry Pi. Installed both Twython and oauthlib without problem. But can't get past this error:

Traceback (most recent call last):
  File "tweet_test.py", line 3, in
    from twython import Twython

File "/usr/lib/python2.7/dist-packages/twython/init.py", line 23, in
    from .api import Twython

File "/usr/lib/python2.7/dist-packages/twython/api.py", line 14, in
    from requests_oauthlib import OAuth1, OAuth2

ImportError: No module named requests_oauthlib

Original:

```<code>#!/usr/bin/env python
import sys
from twython import Twython

tweetStr = "Tweet text!"

apiKey = 'apiKey'
apiSecret = 'apiSecret'
accessToken = 'A_token'
accessTokenSecret = 'A_token_secret'

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)

api.update_status(status=tweetStr)

print "Tweeted: " + tweetStr
</code>```

答:
Try this it will work

sudo apt-get install -y python3-oauth python3-oauth2client python3-oauthlib python3-requests-oauthlib

Body:
Trying to tweet on my Raspberry Pi. Installed both Twython and oauthlib without problem. But can't get past this error:

Traceback (most recent call last):
  File "tweet_test.py", line 3, in
    from twython import Twython

File "/usr/lib/python2.7/dist-packages/twython/init.py", line 23, in
    from .api import Twython

File "/usr/lib/python2.7/dist-packages/twython/api.py", line 14, in
    from requests_oauthlib import OAuth1, OAuth2

ImportError: No module named requests_oauthlib

Original:

#!/usr/bin/env python
import sys
from twython import Twython

tweetStr = "Tweet text!"

apiKey = 'apiKey'
apiSecret = 'apiSecret'
accessToken = 'A_token'
accessTokenSecret = 'A_token_secret'

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)

api.update_status(status=tweetStr)

print "Tweeted: " + tweetStr


问:
ini_set(): Headers already sent. You cannot change the session module's ini settings at this time in codeigniter
I'm using CI 3.1.10.In the index.php file i use development enviroment.

MY controller

<?php
class Test extends CI_Controller {
public function index(){
    echo CI_VERSION;
 }
}

?>```

When i try to access the test class then it show me this error

This is the image that show me the warning.

Screenshot of the error is attached

答: Remove Close tag from the Controller ?> then check

Body:
I'm using CI 3.1.10.In the index.php file i use development enviroment.

MY controller

<?php
class Test extends CI_Controller {
public function index(){
    echo CI_VERSION;
 }
}

?>

When i try to access the test class then it show me this error

This is the image that show me the warning.

Screenshot of the error is attached


问:
bitwise join two if's into one
I have this,

```<code>public enum Condition : uint // bitwise
{
    None = 0,
    NewLine = 1,
    Space = 2
}

Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;
</code>```

I'd like to convert this,

```<code>if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;
</code>```

Into something like,

```<code>if((someCondition & condition) == someCondition) return true;
</code>```

But it isn't working.  What am I forgetting?

答:
Well, if you're just wanting to test for none, then check for > 0. But, if you're looking for a less specific solution, something like this would combine the two and remove the if altogether:

```<code>return (int)(someCondition & (Condition.Space | Condition.NewLine)) > 0
</code>```

Title: bitwise join two if's into one

Body:
I have this,

public enum Condition : uint // bitwise
{
    None = 0,
    NewLine = 1,
    Space = 2
}

Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;

I'd like to convert this,

if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;

Into something like,

if((someCondition & condition) == someCondition) return true;

But it isn't working.  What am I forgetting?

Body:
Well, if you're just wanting to test for none, then check for > 0. But, if you're looking for a less specific solution, something like this would combine the two and remove the if altogether:

return (int)(someCondition & (Condition.Space | Condition.NewLine)) > 0


问:
Sequelize error using association on n:m related objects
I am using nodeJS, express (4.17.1), sequelize (5.21.4) and mysql (mysql2 v2.1.0) for a current project.

In my database I have three tables Filter, Element and FilterElement. If I query data from database from Filter or Element table separatly I get the result of objects with data. If I want to use "connecting" table FilterElement I get this error {"name":"SequelizeEagerLoadingError"}

EagerLoadingError [SequelizeEagerLoadingError]: filter_element is not
  associated to filters_new!

What is wrong with my code?
These are my sequelize objects codes.

Filter.js

const Sequelize = require('sequelize');
const db = require('../config/database');

const Filter = db.define('filters_new', {
    Model:{
        type: Sequelize.STRING,
        primaryKey: true,
        allowNull: false
    }
},
    {
        timestamps: false,
        freezeTableName: true
    }
);

Filter.associate = function(models) {
    Filter.belongsToMany(models.Element, {
      through: models.FilterElement,
      as: 'filter',
      foreignKey: 'FilterHousingModel'
    });
  };

module.exports = Filter;```
</div>
</div>
</p>

<p>Element.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Sequelize = require('sequelize');
const db = require('../config/database');

const Element = db.define('filter_element', {
    idfilter_element:{
        type: Sequelize.INTEGER,
        primaryKey: true,
        allowNull: false
    },
    ElementName:{
        type: Sequelize.STRING,
    }
},
    {
        timestamps: false,
        freezeTableName: true
    }
);

Element.associate = function(models) {
    Element.belongsToMany(models.Filter, {
      through: models.FilterElement,
      as: 'element',
      foreignKey: 'FilterElementId'
    });
  };

module.exports = Element;</code>```

FilterElemnt.js

const Sequelize = require('sequelize');
const db = require('../config/database');

const FilterElement = db.define('filters_new', {
    idfilter_filterelement:{
        type: Sequelize.STRING,
        primaryKey: true,
        allowNull: false,
        autoincrement: true
    },
    FilterHousingModel: {
        type: Sequelize.STRING
    },
    FilterElementId: {
        type: Sequelize.INTEGER
    }
},
    {
        timestamps: false,
        freezeTableName: true
    }
);

module.exports = FilterElement;```
</div>
</div>
</p>

<p>If I call this function, I do get the desired result of data from database.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>listFiltersOnly(req, res) {

        return filter.findAll()
        .then((filters) => {
            res.status(200).send(filters);
        })
        .catch(err => {
            console.log(err);
            res.status(400).send(err);
        });
    }</code>```

then if I call function list I get the error mentioned up EagerLoadingError

list(req, res) {
        return filter.findAll({
            include: [{
                model: element,
                as: 'element'
            }],
        })
        .then((filters) => {
            console.log(filters);
            res.status(200).send(filters);
        })
        .catch(err => {
            console.log(err);
            res.status(400).send(err);
        });
    }```

Looking for some suggjestions where might be the problem?

答:
@RatulSharker I removed the asociation from the model and added it where the models are implemented in the controller and now I do get some results.

Filter.belongsToMany(FilterElement, {
    through: FilterFilterElement,
    foreignKey: 'FilterHousingModel'
});

FilterElement.belongsToMany(Filter, {
    through: FilterFilterElement,
    foreignKey: 'FilterElementId'
});```

Thank you @Ratul Sharker

Body:
I am using nodeJS, express (4.17.1), sequelize (5.21.4) and mysql (mysql2 v2.1.0) for a current project.

In my database I have three tables Filter, Element and FilterElement. If I query data from database from Filter or Element table separatly I get the result of objects with data. If I want to use "connecting" table FilterElement I get this error {"name":"SequelizeEagerLoadingError"}

EagerLoadingError [SequelizeEagerLoadingError]: filter_element is not
  associated to filters_new!

What is wrong with my code?
These are my sequelize objects codes.

Filter.js

const Sequelize = require('sequelize');
const db = require('../config/database');

const Filter = db.define('filters_new', {
    Model:{
        type: Sequelize.STRING,
        primaryKey: true,
        allowNull: false
    }
},
    {
        timestamps: false,
        freezeTableName: true
    }
);

Filter.associate = function(models) {
    Filter.belongsToMany(models.Element, {
      through: models.FilterElement,
      as: 'filter',
      foreignKey: 'FilterHousingModel'
    });
  };

module.exports = Filter;

Element.js

const Sequelize = require('sequelize');
const db = require('../config/database');

const Element = db.define('filter_element', {
    idfilter_element:{
        type: Sequelize.INTEGER,
        primaryKey: true,
        allowNull: false
    },
    ElementName:{
        type: Sequelize.STRING,
    }
},
    {
        timestamps: false,
        freezeTableName: true
    }
);

Element.associate = function(models) {
    Element.belongsToMany(models.Filter, {
      through: models.FilterElement,
      as: 'element',
      foreignKey: 'FilterElementId'
    });
  };

module.exports = Element;

FilterElemnt.js

const Sequelize = require('sequelize');
const db = require('../config/database');

const FilterElement = db.define('filters_new', {
    idfilter_filterelement:{
        type: Sequelize.STRING,
        primaryKey: true,
        allowNull: false,
        autoincrement: true
    },
    FilterHousingModel: {
        type: Sequelize.STRING
    },
    FilterElementId: {
        type: Sequelize.INTEGER
    }
},
    {
        timestamps: false,
        freezeTableName: true
    }
);

module.exports = FilterElement;

If I call this function, I do get the desired result of data from database.

listFiltersOnly(req, res) {

        return filter.findAll()
        .then((filters) => {
            res.status(200).send(filters);
        })
        .catch(err => {
            console.log(err);
            res.status(400).send(err);
        });
    }

then if I call function list I get the error mentioned up EagerLoadingError

list(req, res) {
        return filter.findAll({
            include: [{
                model: element,
                as: 'element'
            }],
        })
        .then((filters) => {
            console.log(filters);
            res.status(200).send(filters);
        })
        .catch(err => {
            console.log(err);
            res.status(400).send(err);
        });
    }

Looking for some suggjestions where might be the problem?

Body:
@RatulSharker I removed the asociation from the model and added it where the models are implemented in the controller and now I do get some results.

Filter.belongsToMany(FilterElement, {
    through: FilterFilterElement,
    foreignKey: 'FilterHousingModel'
});

FilterElement.belongsToMany(Filter, {
    through: FilterFilterElement,
    foreignKey: 'FilterElementId'
});

Thank you @Ratul Sharker


问:
Return value from Ajax to Javascript
I'm trying to check if a Name already exists in the database. But my Ajax isn't returning the value, honestly not even sure if the Ajax is running at all.

Here's my code on my php page.

```<code><input class="form-control" id="name" name="name" onblur="checkNameStatus()" />

<script>
    function checkNameStatus(){
    //alert('Start of funtion');
    var name=$("#name").val();
    //alert("Name Input value is: "+name);
    $.ajax({
        type:'post',
            url:'<?php echo base_url() ?>assets/ajax/checkName.php?name='+name,
            success:function(msg){
            alert(msg);
            }
     });
     //alert("End of function");
    }
</script>
</code>```

Using alerts I can tell that the function is indeed running and recieving the name input's value.

And then my Ajax

```<code><?php

$hostname   = 'localhost';
$username   = 'root';
$password   = '123';
$dbname     = 'test_db';

function clean($string) {
   return preg_replace('/[^A-Za-z0-9\- .!@#$%&]/', '', $string);
}

$name= clean($_GET['name']);
$msg = "";

$conn=mysqli_connect($hostname,$username,$password,$dbname);

if (mysqli_connect_errno()){
    echo ("Failed to connect to MySQL: " . mysqli_connect_error());
}

$sql = "SELECT * FROM pattern where name = '$name';";

$check=mysqli_query($conn, $sql);
$count=mysqli_num_rows($check);

if($count!=0)
   {
     $msg = "A Schedule Pattern with the Name of $name already exists. If you continue to use this Name it will overwrite $name's current Data.";
     return $msg;
   } else {
    $msg = "Count check Failed";
    echo $msg;
   }

mysqli_close($con);

 ?>
</code>```

How do I receive the $msg variable from my ajax and return it to the script, and then subsequently show it in an alert?

答:
I think you have to change this

$check=mysql_query($sql);
$count=mysql_num_rows($check);
```

<p>To this</p>

<pre class="lang-php prettyprint-override"><code>$check=mysqli_query($conn, $sql);
$count=mysqli_num_rows($check);
</code>```

You are using both mysql_ and mysqli_ together which is wrong, and it is probably why it failed to check for a count, I also recommend you emplement error messages incase no name has been found for example.

Edit, full code should be: (PHP):

```<code><?php

$hostname   = 'localhost';
$username   = 'root';
$password   = '123';
$dbname     = 'test_db';

function clean($string) {
   return preg_replace('/[^A-Za-z0-9\- .!@#$%&]/', '', $string);
}

if(isset($_GET['name'])){
$name= clean($_GET['name']);
$msg = "";

$conn=mysqli_connect($hostname,$username,$password,$dbname);

if (mysqli_connect_errno()){
    echo ("Failed to connect to MySQL: " . mysqli_connect_error());
}

$sql = "SELECT * FROM pattern where `name` = '$name';";

$check=mysqli_query($conn, $sql);
$count=mysqli_num_rows($check);

if($count!=0)
   {
     $msg = "A Schedule Pattern with the Name of $name already exists. If you continue to use this Name it will overwrite $name's current Data.";
     echo $msg;
   } else {
    $msg = "Count check Failed";
    echo $msg;
   }
mysqli_close($conn);
}
?>
</code>```

Title: Return value from Ajax to Javascript

Body:
I'm trying to check if a Name already exists in the database. But my Ajax isn't returning the value, honestly not even sure if the Ajax is running at all.

Here's my code on my php page.

<input class="form-control" id="name" name="name" onblur="checkNameStatus()" />

Using alerts I can tell that the function is indeed running and recieving the name input's value.

And then my Ajax

<?php

$hostname   = 'localhost';
$username   = 'root';
$password   = '123';
$dbname     = 'test_db';

function clean($string) {
   return preg_replace('/[^A-Za-z0-9\- .!@#$%&]/', '', $string);
}

$name= clean($_GET['name']);
$msg = "";

$conn=mysqli_connect($hostname,$username,$password,$dbname);

if (mysqli_connect_errno()){
    echo ("Failed to connect to MySQL: " . mysqli_connect_error());
}

$sql = "SELECT * FROM pattern where name = '$name';";

$check=mysqli_query($conn, $sql);
$count=mysqli_num_rows($check);

if($count!=0)
   {
     $msg = "A Schedule Pattern with the Name of $name already exists. If you continue to use this Name it will overwrite $name's current Data.";
     return $msg;
   } else {
    $msg = "Count check Failed";
    echo $msg;
   }

mysqli_close($con);

 ?>

How do I receive the $msg variable from my ajax and return it to the script, and then subsequently show it in an alert?

Body:
I think you have to change this

$check=mysql_query($sql);
$count=mysql_num_rows($check);

To this

$check=mysqli_query($conn, $sql);
$count=mysqli_num_rows($check);

You are using both mysql_ and mysqli_ together which is wrong, and it is probably why it failed to check for a count, I also recommend you emplement error messages incase no name has been found for example.

Edit, full code should be: (PHP):

<?php

$hostname   = 'localhost';
$username   = 'root';
$password   = '123';
$dbname     = 'test_db';

function clean($string) {
   return preg_replace('/[^A-Za-z0-9\- .!@#$%&]/', '', $string);
}

if(isset($_GET['name'])){
$name= clean($_GET['name']);
$msg = "";

$conn=mysqli_connect($hostname,$username,$password,$dbname);

if (mysqli_connect_errno()){
    echo ("Failed to connect to MySQL: " . mysqli_connect_error());
}

$sql = "SELECT * FROM pattern where `name` = '$name';";

$check=mysqli_query($conn, $sql);
$count=mysqli_num_rows($check);

if($count!=0)
   {
     $msg = "A Schedule Pattern with the Name of $name already exists. If you continue to use this Name it will overwrite $name's current Data.";
     echo $msg;
   } else {
    $msg = "Count check Failed";
    echo $msg;
   }
mysqli_close($conn);
}
?>


问:
Kubectl exec to the specific container in deployment
Running a deployment with three pod.

```<code>NAME                        READY   STATUS    RESTARTS   AGE
my-api-XXX                  3/3     Running   0          4h

Containers:
  zipkin:
    Container ID:   docker://XXX
    Image:          openzipkin/zipkin:2.11
    Image ID:       docker-pullable://openzipkin/zipkin@sha256:XXX
    Port:           8611/TCP
    Host Port:      8611/TCP
    State:          Running
      Started:      Mon, 17 Feb 2020 12:13:03 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      XXX
  my-api:
    Container ID:   docker://XXX
    Image:          XXX
    Image ID:       XXX
    Ports:          5000/TCP, 6000/TCP
    Host Ports:     5000/TCP, 6000/TCP
    State:          Running
      Started:      Mon, 17 Feb 2020 12:13:04 +0800
    Ready:          True
    Restart Count:  0
    Mounts:
      XXX
  my-metrics:
    Container ID:   docker://XXX
    Image:          XXX
    Image ID:       XXX
    Ports:          5001/TCP, 6001/TCP
    Host Ports:     5001/TCP, 6001/TCP
    State:          Running
      Started:      Mon, 17 Feb 2020 12:13:04 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      XXX
    Mounts:
      XXX
</code>```

The only one pod container I can connect is zipkin with kubectl exec -it my-api-XXX -- /bin/bash.

If I want to access the my-api container using kubectl exec -it my-api-XXX -c <my-api container ID> -- /bin/bash.

It report a error show the container is not in that pod.

Error from server (BadRequest): container my-api_containerID is not valid for pod my-api-XXX

答:
kubectl exec -it "pod-name" -c "container-name" -n "namespace"

Here only the container name is needed. In your case it will be:

kubectl exec -it my-api-XXX -c my-api  -- /bin/bash

You can exec to Zipkin because exec is taking zipkin as the default container.

Body:
Running a deployment with three pod.

NAME                        READY   STATUS    RESTARTS   AGE
my-api-XXX                  3/3     Running   0          4h

Containers:
  zipkin:
    Container ID:   docker://XXX
    Image:          openzipkin/zipkin:2.11
    Image ID:       docker-pullable://openzipkin/zipkin@sha256:XXX
    Port:           8611/TCP
    Host Port:      8611/TCP
    State:          Running
      Started:      Mon, 17 Feb 2020 12:13:03 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      XXX
  my-api:
    Container ID:   docker://XXX
    Image:          XXX
    Image ID:       XXX
    Ports:          5000/TCP, 6000/TCP
    Host Ports:     5000/TCP, 6000/TCP
    State:          Running
      Started:      Mon, 17 Feb 2020 12:13:04 +0800
    Ready:          True
    Restart Count:  0
    Mounts:
      XXX
  my-metrics:
    Container ID:   docker://XXX
    Image:          XXX
    Image ID:       XXX
    Ports:          5001/TCP, 6001/TCP
    Host Ports:     5001/TCP, 6001/TCP
    State:          Running
      Started:      Mon, 17 Feb 2020 12:13:04 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      XXX
    Mounts:
      XXX

The only one pod container I can connect is zipkin with kubectl exec -it my-api-XXX -- /bin/bash.

If I want to access the my-api container using kubectl exec -it my-api-XXX -c <my-api container ID> -- /bin/bash.

It report a error show the container is not in that pod.

Error from server (BadRequest): container my-api_containerID is not valid for pod my-api-XXX


问:
B2C Custom policy skip Signup for AAD by authenticationSource ends up with AADB2C90037
I have integrated Azure AD multitenant with B2C using custom policies and i dont want to have a signup page for the Azure AD user when he tries to sign in for the first time. Since that using Preconditions im trying to skip signup page for AD login users. But it gives me the following error AADB2C90037: An error occurred while processing the request. Please contact administrator of the site you are trying to access.
 But if the second precondition removed from the 4th step it won't give me the error and will bring the signup page which is not my requirement.My claim provider and preconditions in user journey have been mentioned below.

signin_signup policy file

```<code> <RelyingParty>
    <DefaultUserJourney ReferenceId="SignUpOrSignInAD" />

    <UserJourneyBehaviors>
      <JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="xxxxxxxxx" DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0" />
    </UserJourneyBehaviors>
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />
      <OutputClaims>
     <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
        <OutputClaim ClaimTypeReferenceId="otherMails" PartnerClaimType="emails" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />
        <!-- <OutputClaim ClaimTypeReferenceId="identityProvider" /> -->
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />
        <OutputClaim ClaimTypeReferenceId="TnCs" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" PartnerClaimType="SignInemails" />
        <OutputClaim ClaimTypeReferenceId="signInName" />
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
        <OutputClaim ClaimTypeReferenceId="upnUserName" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>
</code>```

Claims Provider for AD

```<code>  <ClaimsProvider>
  <Domain>commonaad</Domain>
  <DisplayName>Common AAD</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="Common-AAD">
      <DisplayName>Multi-Tenant AAD</DisplayName>
      <Description>Login with your Contoso account</Description>
      <Protocol Name="OAuth2"/>
      <Metadata>
    <Item Key="AccessTokenEndpoint">https://login.microsoftonline.com/organizations/oauth2/v2.0/token</Item>
    <Item Key="authorization_endpoint">https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize</Item>
    <Item Key="BearerTokenTransmissionMethod">AuthorizationHeader</Item>
    <Item Key="ClaimsEndpoint">https://graph.microsoft.com/v1.0/me</Item>
    <Item Key="client_id">xxxxxxxxxxxxxxxxxxxxxxxxxxx</Item>
    <Item Key="DiscoverMetadataByTokenIssuer">true</Item>
    <Item Key="HttpBinding">POST</Item>
    <Item Key="IdTokenAudience">xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</Item>
    <Item Key="response_types">code</Item>
    <Item Key="scope">https://graph.microsoft.com/user.read</Item>
    <Item Key="UsePolicyInRedirectUri">false</Item>
    <Item Key="ValidTokenIssuerPrefixes">https://login.microsoftonline.com/</Item>
      </Metadata>

      <CryptographicKeys>
        <Key Id="client_secret" StorageReferenceId="B2C_1A_AADAppSecret"/>
      </CryptographicKeys>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="objectId" />
        <OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid"/>
        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="ExternalAD" AlwaysUseDefaultValue="true" />
        <OutputClaim ClaimTypeReferenceId="identityProvider" PartnerClaimType="idp" />
        <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="displayName" />
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="mail" />
        <OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="surname" />
        <OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="id"/>
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="userPrincipalName" />
      </OutputClaims>
      <OutputClaimsTransformations>
        <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
        <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
        <OutputClaimsTransformation ReferenceId="CreateAzureADIdentityProvider" />
        <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
        <OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
      </OutputClaimsTransformations>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin"/>
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>
</code>```

Orchestrator step for skipping the signup

```<code><OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
           <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
             <Value>authenticationSource</Value>
              <Value>ExternalAD</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Social" TechnicalProfileReferenceId="SelfAsserted-Social" />
          </ClaimsExchanges>
        </OrchestrationStep>
</code>```

答:
Signing-in to an Azure AD tenant requires that the user performing the sign-in flow already has an attribute such as object ID that will identify them on the Azure AD tenant they are signing-in to. Object IDs of every user is different on every Azure AD tenant irrespective of their root Azure AD tenant, this attribute is not transferred from directory to directory and only a sign-up process will create this attribute for users on Azure AD.

As i have been able to configure custom policy file to bypass this step, i will not be able to get an access token as users are required to go through the signup process before they will get attributes such as object IDs that uniquely identifies every user on different Azure AD tenants.

Existing users on an Azure AD B2C tenant will not have to pass through the sign-up process, they could simply proceed to sign-in to your Azure AD B2C tenant as they would already have attributes identifying them on your Azure AD tenant.

Body:
I have integrated Azure AD multitenant with B2C using custom policies and i dont want to have a signup page for the Azure AD user when he tries to sign in for the first time. Since that using Preconditions im trying to skip signup page for AD login users. But it gives me the following error AADB2C90037: An error occurred while processing the request. Please contact administrator of the site you are trying to access.
 But if the second precondition removed from the 4th step it won't give me the error and will bring the signup page which is not my requirement.My claim provider and preconditions in user journey have been mentioned below.

signin_signup policy file

 <RelyingParty>
    <DefaultUserJourney ReferenceId="SignUpOrSignInAD" />

    <UserJourneyBehaviors>
      <JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="xxxxxxxxx" DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0" />
    </UserJourneyBehaviors>
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />
      <OutputClaims>
     <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
        <OutputClaim ClaimTypeReferenceId="otherMails" PartnerClaimType="emails" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />

        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />
        <OutputClaim ClaimTypeReferenceId="TnCs" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" PartnerClaimType="SignInemails" />
        <OutputClaim ClaimTypeReferenceId="signInName" />
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
        <OutputClaim ClaimTypeReferenceId="upnUserName" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>

Claims Provider for AD

  <ClaimsProvider>
  <Domain>commonaad</Domain>
  <DisplayName>Common AAD</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="Common-AAD">
      <DisplayName>Multi-Tenant AAD</DisplayName>
      <Description>Login with your Contoso account</Description>
      <Protocol Name="OAuth2"/>
      <Metadata>
    <Item Key="AccessTokenEndpoint">https://login.microsoftonline.com/organizations/oauth2/v2.0/token</Item>
    <Item Key="authorization_endpoint">https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize</Item>
    <Item Key="BearerTokenTransmissionMethod">AuthorizationHeader</Item>
    <Item Key="ClaimsEndpoint">https://graph.microsoft.com/v1.0/me</Item>
    <Item Key="client_id">xxxxxxxxxxxxxxxxxxxxxxxxxxx</Item>
    <Item Key="DiscoverMetadataByTokenIssuer">true</Item>
    <Item Key="HttpBinding">POST</Item>
    <Item Key="IdTokenAudience">xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</Item>
    <Item Key="response_types">code</Item>
    <Item Key="scope">https://graph.microsoft.com/user.read</Item>
    <Item Key="UsePolicyInRedirectUri">false</Item>
    <Item Key="ValidTokenIssuerPrefixes">https://login.microsoftonline.com/</Item>
      </Metadata>

      <CryptographicKeys>
        <Key Id="client_secret" StorageReferenceId="B2C_1A_AADAppSecret"/>
      </CryptographicKeys>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="objectId" />
        <OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid"/>
        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="ExternalAD" AlwaysUseDefaultValue="true" />
        <OutputClaim ClaimTypeReferenceId="identityProvider" PartnerClaimType="idp" />
        <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="displayName" />
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="mail" />
        <OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="surname" />
        <OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="id"/>
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="userPrincipalName" />
      </OutputClaims>
      <OutputClaimsTransformations>
        <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
        <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
        <OutputClaimsTransformation ReferenceId="CreateAzureADIdentityProvider" />
        <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
        <OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
      </OutputClaimsTransformations>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin"/>
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

Orchestrator step for skipping the signup

<OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
           <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
             <Value>authenticationSource</Value>
              <Value>ExternalAD</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Social" TechnicalProfileReferenceId="SelfAsserted-Social" />
          </ClaimsExchanges>
        </OrchestrationStep>


问:
Filter WPF DataGrid by multiple criterias
I would like to implement Excel like filter to datagrid by three columns.

Here is my code:

```<code>    using System.Data.Odbc;
    using System.Windows;
    using System.Data;

    namespace DB_inspector
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();

            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                OdbcConnection dbConnection = new OdbcConnection("Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;");
                string strSql = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
                dbConnection.Open();
                OdbcDataAdapter dadapter = new OdbcDataAdapter();
                dadapter.SelectCommand = new OdbcCommand(strSql, dbConnection);
                DataTable table = new DataTable("COMPANY");
                dadapter.Fill(table);
                DataGrid1.DataContext = table;
                DataGrid1.ItemsSource = table.DefaultView;
                dadapter.Update(table);
                dbConnection.Close();
            }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = NameSearch.Text;
                if (string.IsNullOrEmpty(filter))
                    dv.RowFilter = null;
                else
                    dv.RowFilter = string.Format("NAME Like '%{0}%'", filter);

        }

        private void TextBox_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = ActiveSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("ACTIVE Like '%{0}%'", filter);
        }

        private void CustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = CustomerNumberSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("NRO Like '%{0}%'", filter); //this should be "Begins with" not "Like"
        }
    }
}
</code>```

XAML

```<code><Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DB_inspector"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="11*"/>
            <RowDefinition Height="553*"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,51,0,0" Grid.Row="1"/>
        <Image Height="41" Margin="847,10,10,502" Width="141" Source="Logo_small.jpg" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="23" Margin="77,14,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="409" Grid.Row="1" TextChanged="TextBox_TextChanged"/>
        <Button Content="Refrsh" HorizontalAlignment="Left" Height="23" Margin="736,14,0,0" VerticalAlignment="Top" Width="72" Click="Button_Click" Grid.Row="1" Background="#FF51C951" BorderBrush="{x:Null}" Foreground="White"/>
        <TextBox x:Name="ActiveSearch" HorizontalAlignment="Left" Height="23" Margin="502,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="66" TextChanged="TextBox_TextChanged_1"/>
        <TextBox x:Name="CustomerNumberSearch" HorizontalAlignment="Left" Height="23" Margin="580,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="82" TextChanged="CustomerNumberSearch_TextChanged"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="10" Margin="0,1,0,0" VerticalAlignment="Top" Width="998" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="23" Margin="680,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="51" Click="Button_Click_1"/>

    </Grid>
</Window>
</code>```

I would like to implement filters for column NRO and ACTIVE so that during load of data in column NRO will be numbers starting with 3 only and in column ACTIVE values with 1 only. In ACTIVE there are values 1 and 0 (1 active, 0 not active).

My current setup is filtering only by one criteria. How to make all three criteria function correct?

答:
you need to combine multiple conditions in one Filter string:</p>

```<code>private Dictionary<string, string> _conditions = new Dictionary<string, string>();

private void UpdateFilter()
{
     var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
     DataView dv = DataGrid1.ItemsSource as DataView;
     dv.RowFilter = string.Join(" AND ", activeConditions);
}

private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = NameSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["name"] = null;
    else
        _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
    UpdateFilter();
}

private void TextBox_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = ActiveSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["active"] = null;
    else
        _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", filter);
    UpdateFilter();
}

private void CustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = CustomerNumberSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["nro"] = null;
    else
        _conditions["nro"] = string.Format("NRO Like '%{0}%'", filter); //this should be "Begins with" not "Like"
    UpdateFilter();
}
</code>```

Body:
I would like to implement Excel like filter to datagrid by three columns.

Here is my code:

    using System.Data.Odbc;
    using System.Windows;
    using System.Data;

    namespace DB_inspector
    {
        ///
        /// Interaction logic for MainWindow.xaml
        ///
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();

            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                OdbcConnection dbConnection = new OdbcConnection("Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;");
                string strSql = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
                dbConnection.Open();
                OdbcDataAdapter dadapter = new OdbcDataAdapter();
                dadapter.SelectCommand = new OdbcCommand(strSql, dbConnection);
                DataTable table = new DataTable("COMPANY");
                dadapter.Fill(table);
                DataGrid1.DataContext = table;
                DataGrid1.ItemsSource = table.DefaultView;
                dadapter.Update(table);
                dbConnection.Close();
            }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = NameSearch.Text;
                if (string.IsNullOrEmpty(filter))
                    dv.RowFilter = null;
                else
                    dv.RowFilter = string.Format("NAME Like '%{0}%'", filter);

        }

        private void TextBox_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = ActiveSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("ACTIVE Like '%{0}%'", filter);
        }

        private void CustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = CustomerNumberSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("NRO Like '%{0}%'", filter); //this should be "Begins with" not "Like"
        }
    }
}

XAML

<Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DB_inspector"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="11*"/>
            <RowDefinition Height="553*"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,51,0,0" Grid.Row="1"/>
        <Image Height="41" Margin="847,10,10,502" Width="141" Source="Logo_small.jpg" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="23" Margin="77,14,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="409" Grid.Row="1" TextChanged="TextBox_TextChanged"/>
        <Button Content="Refrsh" HorizontalAlignment="Left" Height="23" Margin="736,14,0,0" VerticalAlignment="Top" Width="72" Click="Button_Click" Grid.Row="1" Background="#FF51C951" BorderBrush="{x:Null}" Foreground="White"/>
        <TextBox x:Name="ActiveSearch" HorizontalAlignment="Left" Height="23" Margin="502,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="66" TextChanged="TextBox_TextChanged_1"/>
        <TextBox x:Name="CustomerNumberSearch" HorizontalAlignment="Left" Height="23" Margin="580,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="82" TextChanged="CustomerNumberSearch_TextChanged"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="10" Margin="0,1,0,0" VerticalAlignment="Top" Width="998" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="23" Margin="680,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="51" Click="Button_Click_1"/>

    </Grid>
</Window>

I would like to implement filters for column NRO and ACTIVE so that during load of data in column NRO will be numbers starting with 3 only and in column ACTIVE values with 1 only. In ACTIVE there are values 1 and 0 (1 active, 0 not active).

My current setup is filtering only by one criteria. How to make all three criteria function correct?

Body:
you need to combine multiple conditions in one Filter string:

private Dictionary<string, string> _conditions = new Dictionary<string, string>();

private void UpdateFilter()
{
     var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
     DataView dv = DataGrid1.ItemsSource as DataView;
     dv.RowFilter = string.Join(" AND ", activeConditions);
}

private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = NameSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["name"] = null;
    else
        _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
    UpdateFilter();
}

private void TextBox_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = ActiveSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["active"] = null;
    else
        _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", filter);
    UpdateFilter();
}

private void CustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = CustomerNumberSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["nro"] = null;
    else
        _conditions["nro"] = string.Format("NRO Like '%{0}%'", filter); //this should be "Begins with" not "Like"
    UpdateFilter();
}


问:
"Invalid platform app" error using Instagram Basic Display API
I am trying to use Instagram Basic display API but when I post the authorization code to get the access token I keep getting the following error

{"error_type": "OAuthException", "code": 400, "error_message":
"Invalid platform app"}

I am following all the steps mentioned here -> https://developers.facebook.com/docs/instagram-basic-display-api/getting-started and Yes I am using the Instagram app ID and It's client secret which is in Products -> Instagram -> Display and following is the URL I am sending the request

"https://api.instagram.com/oauth/access_token?client_id=".$app_id."&client_secret=".$app_secret."&grant_type=authorization_code&redirect_uri=".$redirecturi."&code=".$code,

答:
Working example code:</p>
```<code>$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.instagram.com/oauth/access_token",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => array('client_id' => '{client_id}','client_secret' => '{client_secret}','grant_type' => 'authorization_code','redirect_uri' => '{redirect_uri}','code' => '{code}'),
  CURLOPT_HTTPHEADER => array(
    "Content-Type: multipart/form-data; boundary=--------------------------780367731654051340650991"
  ),
));
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
</code>```

Body:
Working example code:

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.instagram.com/oauth/access_token",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => array('client_id' => '{client_id}','client_secret' => '{client_secret}','grant_type' => 'authorization_code','redirect_uri' => '{redirect_uri}','code' => '{code}'),
  CURLOPT_HTTPHEADER => array(
    "Content-Type: multipart/form-data; boundary=--------------------------780367731654051340650991"
  ),
));
$response = curl_exec($curl);
curl_close($curl);
print_r($response);


问:
Get names of the params passed to a C# method
```<code>void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }
</code>```

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

```<code>string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);
</code>```

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)

答: It is not possible, and I wonder why you would need that.</p>

Body:
void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)


问:
How to implement Spring boot + Hibernate
I am getting this error:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field sessionFactory in com.demo.dao.EmployeeDAO required a bean of type 'org.hibernate.SessionFactory' that could not be found.

Action: Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
</code>```

My HibernateUtil class is:

```<code>@Configuration
public class HibernateUtil {

    @Autowired
    private EntityManagerFactory factory;

    @Bean
    public SessionFactory getSessionFactory() {
        if(factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("Factory is not a hibernate factory.");
        }
        return factory.unwrap(SessionFactory.class);
    }
}
</code>```

my EmployeeDao class is:

```<code>@Repository
public class EmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    public void save(Employee emp) {

        Session session = null;

        try {
            session = sessionFactory.openSession();
            System.out.println("Session got.");
            Transaction tx = session.beginTransaction();
            session.save(emp);
            tx.commit();
        }catch(HibernateException he) {
            he.printStackTrace();
        }
    }
}
</code>```

application.properties file,

```<code>spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/manissh
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
</code>```

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

答:
try to create Autowired  sessionFactory in your Repository

```<code>   @Repository
   public class EmployeeDAO {
            private SessionFactory sessionFactory;

            @Autowired
            public EmployeeDAO(EntityManagerFactory entityManagerFactory) {
                    this.sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
            }
    }
</code>```

or try this solution - https://stackoverflow.com/a/43895827/6582610

Body:
I am getting this error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field sessionFactory in com.demo.dao.EmployeeDAO required a bean of type 'org.hibernate.SessionFactory' that could not be found.

Action: Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.

My HibernateUtil class is:

@Configuration
public class HibernateUtil {

    @Autowired
    private EntityManagerFactory factory;

    @Bean
    public SessionFactory getSessionFactory() {
        if(factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("Factory is not a hibernate factory.");
        }
        return factory.unwrap(SessionFactory.class);
    }
}

my EmployeeDao class is:

@Repository
public class EmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    public void save(Employee emp) {

        Session session = null;

        try {
            session = sessionFactory.openSession();
            System.out.println("Session got.");
            Transaction tx = session.beginTransaction();
            session.save(emp);
            tx.commit();
        }catch(HibernateException he) {
            he.printStackTrace();
        }
    }
}

application.properties file,

spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/manissh
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

Body:
try to create Autowired  sessionFactory in your Repository

   @Repository
   public class EmployeeDAO {
            private SessionFactory sessionFactory;

            @Autowired
            public EmployeeDAO(EntityManagerFactory entityManagerFactory) {
                    this.sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
            }
    }

or try this solution - https://stackoverflow.com/a/43895827/6582610


问:
Docker TLS - How to create key on local machine
Pre knowledge:

So I started using docker myself and installed it on my server and enabled TLS. I followed this tutorial: https://docs.docker.com/engine/security/https/

This tutorial will eventually give you 6 files:

-r-------- ca-key.pem

-r--r--r-- ca.pem

-r--r--r-- cert.pem

-r-------- key.pem

-r--r--r-- server-cert.pem

-r-------- server-key.pem

The owner of these files is root. I copied the ca.pem, cert.pem and key.pem, I used them to connect from my local portainer instance. (Actually I only use cert.pem and key.pem since I only have client verification on)

DOCKER HOST:

```<code>{
  "hosts": [
    "unix:///var/run/docker.sock",
    "tcp://0.0.0.0:2376"
  ],
  "storage-driver": "overlay2",
  "tls": true,
  "tlscacert": "/etc/docker/certs/ca.pem",
  "tlscert": "/etc/docker/certs/server-cert.pem",
  "tlskey": "/etc/docker/certs/server-key.pem",
  "tlsverify": true
}
</code>```

My problem:

The company where I work installed docker for me and enabled TLS, put all the pem files in a directory which I can access... Problem is, I cannot download the key.pem since the owner is root and I won't get access to it.

I can download the next files:

ca.pem

cert.pem

server-cert.pem

Is is possible for me; with access to those files ONLY, not changing anything on the server, to access docker over TLS? How can I create my own key.pem, or is there another way?

Sorry if this is common knowledge, I just could not find my answer anywhere, or I did not know what I was exactly searching for...

答:
Private keys create the certificates, you can't create a key from a cert. If your docker wants a 2 way authentication you will need access to the private key. It cannot be done without.

You'll need the following files (for client-server authentication):

ca.pem

cert.pem

key.pem

Body:
Pre knowledge:

So I started using docker myself and installed it on my server and enabled TLS. I followed this tutorial: https://docs.docker.com/engine/security/https/

This tutorial will eventually give you 6 files:

-r-------- ca-key.pem

-r--r--r-- ca.pem

-r--r--r-- cert.pem

-r-------- key.pem

-r--r--r-- server-cert.pem

-r-------- server-key.pem

The owner of these files is root. I copied the ca.pem, cert.pem and key.pem, I used them to connect from my local portainer instance. (Actually I only use cert.pem and key.pem since I only have client verification on)

DOCKER HOST:

{
  "hosts": [
    "unix:///var/run/docker.sock",
    "tcp://0.0.0.0:2376"
  ],
  "storage-driver": "overlay2",
  "tls": true,
  "tlscacert": "/etc/docker/certs/ca.pem",
  "tlscert": "/etc/docker/certs/server-cert.pem",
  "tlskey": "/etc/docker/certs/server-key.pem",
  "tlsverify": true
}

My problem:

The company where I work installed docker for me and enabled TLS, put all the pem files in a directory which I can access... Problem is, I cannot download the key.pem since the owner is root and I won't get access to it.

I can download the next files:

ca.pem

cert.pem

server-cert.pem

Is is possible for me; with access to those files ONLY, not changing anything on the server, to access docker over TLS? How can I create my own key.pem, or is there another way?

Sorry if this is common knowledge, I just could not find my answer anywhere, or I did not know what I was exactly searching for...


问:
Azure Devops Pipeline : Difference between system.debug and 'Enable system diagnostics'
If we use the UI of build pipeline, we see 'enable system diagnostics' check box as given below. There is also a default variable 'system.debug'.

What is the difference between these two?

One comment here states both could be the same. But if we set system.debug is set to 'true' 'enable system diagnostics' is still unchecked.

答:
They both are the same. It is given here. The main purpose is to set the variable for automated runs. But it can be used for single runs too, which makes the UI checkbox, the additional duplicate feature, pointless.

It is confusing because it appears in build pipeline and not in release pipeline. Also when we run , like you said, even when the variable is set to true, the UI is still not updated(unchecked). Which might require double work(checking diagnostics too) like I did for some time.

"To configure verbose logs for all runs, you can add a variable named system.debug and set its value to true." And ignore the UI check box


问:
Why am I having to set the dataType to text?
I have the following script which works, but I don't understand why it will not work when the type is set to json:

Serverside:

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Clear()
    Response.ContentType = "text/plain" '//#### <- should't this be text/json? ###
    Response.Write(getTabFrame())
    Response.End()
End Sub

Function getTabFrame() As String
    objStringBuilder = New StringBuilder()

    objStringBuilder.Append("[")

    objStringBuilder.Append("{""key"":1,""value"":""Default""},")
    objStringBuilder.Append("{""key"":2,""value"":""Reports""},")
    objStringBuilder.Append("{""key"":3,""value"":""Other""}")

    objStringBuilder.Append("]")

    Return objStringBuilder.ToString
End Function
</code>```

Clientside:

```<code>$.ajax({
    url: 'serverside',
    type: 'GET',
    dataType: 'text', //#### <------------------------ shouldn't this be json? ###
    error: function(xhr, status, error) {
        alert('Error: ' + status + '\nError Text: ' + error + '\nResponse Text: ' + xhr.responseText);
    },
    success: function(results) {
        var obj = jQuery.parseJSON(results);
        var len = obj.length;

        for(i=0; i<len; i++) {
            $("#tabs").tabs("add","tabs.aspx?tab=" + obj[i].key, obj[i].value)
        };
    }
});
</code>```

When I change those values to json, the whole thing stops working and returns "null"...

Why?

答:
I think it should be an appropriate to use
• Response.ContentType = "text/html";

The XML validates and checks the markup validity of Web documents in HTML, XHTML, SMIL, MathML, etc. to conform to w3 standards.

SAMPLE CODE: (With error)
protected void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    Response.ContentType = "text/json";  //#### <- should't this be ‘application/json’?

    Response.Write(getTabFrame());

    Response.End();
}

private string  getTabFrame()
{

    var objStringBuilder = new StringBuilder();
    objStringBuilder.Append("[");
    objStringBuilder.Append("{\"key\":1,\"value\":\"Default\"},");
    objStringBuilder.Append("{\"key\":2,\"value\":\"Reports\"},") ;
    objStringBuilder.Append("{\"key\":3,\"value\":\"Other\"}");
    objStringBuilder.Append("]");
    return objStringBuilder.ToString();
}

Page Error Output:

The XML page cannot be displayed
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.

Invalid at the top level of the document. Error processing resource 'http://localhost:1713/Default.aspx'. Line 1, Position...

[{"key":1,"value":"Default"},{"key":2,"value":"Reports"},{"key":3,"value":"Other"}]
^

SAMPLE CODE: (No error)
protected void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    Response.ContentType = "text/html";  //#### <- should't this be text/html? ###

    Response.Write(getTabFrame());

    Response.End();
}

private string  getTabFrame()
{

   var objStringBuilder = new StringBuilder();
   objStringBuilder.Append("[");
   objStringBuilder.Append("{\"key\":1,\"value\":\"Default\"},");
   objStringBuilder.Append("{\"key\":2,\"value\":\"Reports\"},") ;
   objStringBuilder.Append("{\"key\":3,\"value\":\"Other\"}");
   objStringBuilder.Append("]");
   return objStringBuilder.ToString();
}

Page Output(No error):

[{"key":1,"value":"Default"},{"key":2,"value":"Reports"},{"key":3,"value":"Other"}]

Body:
I have the following script which works, but I don't understand why it will not work when the type is set to json:

Serverside:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Clear()
    Response.ContentType = "text/plain" '//#### <- should't this be text/json? ###
    Response.Write(getTabFrame())
    Response.End()
End Sub

Function getTabFrame() As String
    objStringBuilder = New StringBuilder()

    objStringBuilder.Append("[")

    objStringBuilder.Append("{""key"":1,""value"":""Default""},")
    objStringBuilder.Append("{""key"":2,""value"":""Reports""},")
    objStringBuilder.Append("{""key"":3,""value"":""Other""}")

    objStringBuilder.Append("]")

    Return objStringBuilder.ToString
End Function

Clientside:

$.ajax({
    url: 'serverside',
    type: 'GET',
    dataType: 'text', //#### <------------------------ shouldn't this be json? ###
    error: function(xhr, status, error) {
        alert('Error: ' + status + '\nError Text: ' + error + '\nResponse Text: ' + xhr.responseText);
    },
    success: function(results) {
        var obj = jQuery.parseJSON(results);
        var len = obj.length;

        for(i=0; i<len; i++) {
            $("#tabs").tabs("add","tabs.aspx?tab=" + obj[i].key, obj[i].value)
        };
    }
});

When I change those values to json, the whole thing stops working and returns "null"...

Why?


问:
Return partial sums of the array items as an array
I am trying to solve this kata on Codewars using JavaScript.

(sorry that I haven't copied and pasted the exercise here, the explanation is quite long)

I have some code that works for smaller arrays, but it is returning a server timeout error when I try to submit the solution:

```<code>function partsSums(ls) {
  const results = [];
  ls.forEach((c, i) => {results.push((ls.slice([i])).reduce((a, b) => {return(a+b)}))});
  results.push(0);
  return results;
};
</code>```

I don't know how to make this code any more efficient so that I can submit the solution. Any help on this would be appreciated!

Body:
I am trying to solve this kata on Codewars using JavaScript.

(sorry that I haven't copied and pasted the exercise here, the explanation is quite long)

I have some code that works for smaller arrays, but it is returning a server timeout error when I try to submit the solution:

function partsSums(ls) {
  const results = [];
  ls.forEach((c, i) => {results.push((ls.slice([i])).reduce((a, b) => {return(a+b)}))});
  results.push(0);
  return results;
};

I don't know how to make this code any more efficient so that I can submit the solution. Any help on this would be appreciated!

Body:
You could get a copy from the data and iterate from the end for assigning the sum.

function partsSums(array) {
    var i = array.length,
        result = array.slice();

    result[i] = 0;
    while (i--) result[i] += result[i + 1];
    return result;
}

console.log(partsSums([1, 2, 3, 4, 5, 6]));
//[21, 20, 18, 15, 11, 6, 0]

console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));
// [10037855, 9293730, 9292795, 9292388, 9291934, 9291504, 9291414, 9291270, 2581057, 2580168, 2579358, 0]


问:
How to cleanly do a git pull-with-rebase after merging branches

Alternative title: How to squash merge commits?

I have the following state in my local repository:

```<code>      C     (origin/feature)
     /
A - B - m   (feature)
       /
  Y - Z     (master)
</code>```

I've just merged changes from one branch to another (e.g. from master into our feature branch, or even vice versa). When I did this, commit B and Z were the most latest commits in their respective branches.

However! Dastardly Dan just pushed his change to the branch I was merging into (C). When I now try and push, I can't. I first have to fetch the changes and merge them somehow. The question is: how?

If I do a pull with rebase, I end up having to resolve all the conflicts in the merge between B & Z. If I try to merge, I end up with two merge commits, which isn't that clean, and also shouldn't be that necessary.

```<code>      C --
     /     \
A - B - m - m2
       /
  Y - Z
</code>```

Is there any way of squashing m and m2 such that it looks like:

```<code>      C --
     /     \
A - B    -- m3
       /
  Y - Z
</code>```

An interactive rebase obviously doesn't show the merge commits, and a cherry-pick requires me to resolve all the merge conflicts again (between B & Z, which weren't affected by C at all).

答:
In order to go from :

```<code>      C --
     /     \
A - B - m - m2
       /
  Y - Z
</code>```

to:

```<code>      C --
     /     \
A - B    -- m3
       /
  Y - Z
</code>```

you can use git commit-tree as suggested in this answer :

```<code>git commit-tree -p C -p Z m2^{tree}
</code>```

Body:
Alternative title: How to squash merge commits?

I have the following state in my local repository:

      C     (origin/feature)
     /
A - B - m   (feature)
       /
  Y - Z     (master)

I've just merged changes from one branch to another (e.g. from master into our feature branch, or even vice versa). When I did this, commit B and Z were the most latest commits in their respective branches.

However! Dastardly Dan just pushed his change to the branch I was merging into (C). When I now try and push, I can't. I first have to fetch the changes and merge them somehow. The question is: how?

If I do a pull with rebase, I end up having to resolve all the conflicts in the merge between B & Z. If I try to merge, I end up with two merge commits, which isn't that clean, and also shouldn't be that necessary.

      C --
     /     \
A - B - m - m2
       /
  Y - Z

Is there any way of squashing m and m2 such that it looks like:

      C --
     /     \
A - B    -- m3
       /
  Y - Z

An interactive rebase obviously doesn't show the merge commits, and a cherry-pick requires me to resolve all the merge conflicts again (between B & Z, which weren't affected by C at all).

Body:
In order to go from :

      C --
     /     \
A - B - m - m2
       /
  Y - Z

to:

      C --
     /     \
A - B    -- m3
       /
  Y - Z

you can use git commit-tree as suggested in this answer :

git commit-tree -p C -p Z m2^{tree}


问:
How to automate a mongo db command?
Since the sudo mongod command did not work for my macOS version (/ data/db path was not found), I changed the path to /System/Volumes/Data/data/db.

To start mongo I always have to enter sudo mongod --dbpath /System/Volumes/Data/data/db so that the new path is recognized.

Is there a way to design this process so that I only have to enter sudo mongod again?

I'm using the following macOS version: Catalina 10.15.3 with zsh

答:
You should search for config file of MongoDB and check the content of:

```<code>storage:
   dbPath: <string>
</code>```

And dbPath must point to the /System/Volumes/Data/data/db

The usual location of config file is /usr/local/etc/mongod.conf

Title: How to automate a mongo db command?

Body:
You should search for config file of MongoDB and check the content of:

storage:
   dbPath: <string>

And dbPath must point to the /System/Volumes/Data/data/db

The usual location of config file is /usr/local/etc/mongod.conf


问:
What is JSONP, and why was it created?
I understand JSON, but not JSONP. Wikipedia's document on JSON is (was) the top search result for JSONP. It says this:

JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself.

Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call.

The 2nd search result is from some guy named Remy, who writes this about JSONP:

JSONP is script tag injection, passing the response from the server in to a user specified function.

I can sort of understand that, but it's still not making any sense.

So what is JSONP? Why was it created (what problem does it solve)? And why would I use it?

Addendum: I've just created a new page for JSONP on Wikipedia; it now has a clear and thorough description of JSONP, based on jvenema's answer.

答:
This is my ELI5 (explain me like I'm 5) attempt for those that need it.

TL;DR

JSONP is an old trick invented to bypass the security restriction in web browsers that forbids us to get data that is in a different website/server (called different origin1) than our own.

The trick works by using a
```
<p>So we'll receive it like this:</p>
```tourismJSONP({"city":"Barcelona"})
```
<p>which now makes it <em>JS code</em> that we could interact with.</p>
<p>As per <strong>2)</strong>, we need to write a function with the same name in our code, like this:</p>
```function tourismJSONP(data){
  alert(data.city); // "Barcelona"
}
```

The browser will download the JSONP and run it, which calls our function, where the argument data will be the JSON data from anotherweb.com. We can now do with our data whatever we want to.

Don't use JSONP, use CORS

JSONP is a cross-site hack with a few downsides:

We can only perform GET requests

Since it's a GET request triggered by a simple script tag, we don't get helpful errors or progress info

There are also some security concerns, like running in your client JS code that could be changed to a malicious payload

It only solves the problem with JSON data, but Same-Origin security policy applies to other data (WebFonts, images/video drawn with drawImage()...)

It's not very elegant nor readable.

The takeaway is that there's no need to use it nowadays.

You should read about CORS here, but the gist of it is:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin. A web application executes a cross-origin HTTP request when it
requests a resource that has a different origin (domain, protocol, or
port) from its own.

origin is defined by 3 things: protocol, port, and host. So, https://web.com is a different origin than http://web.com (different protocol), also https://web.com:8081 (different port) and obviously https://thatotherweb.net (different host)

Title: What is JSONP, and why was it created?

Body:
This is my ELI5 (explain me like I'm 5) attempt for those that need it.

TL;DR

JSONP is an old trick invented to bypass the security restriction in web browsers that forbids us to get data that is in a different website/server (called different origin1) than our own.

The trick works by using a <script> tag to load a JSON (e.g.: { "city":"Barcelona" }) from somewhere else, that will send us the data wrapped in a function, the actual JSONP ("JSON with Padding"):

tourismJSONP({"city":"Barcelona"})

Receiving it in this way enables us to use the data within our tourismJSONP function. JSONP is a bad practice and not needed anymore, don't use it (read at the end).

The problem

Say we want to use on ourweb.com some JSON data (or any raw data really) hosted at anotherweb.com. If we were to use GET request (think XMLHttpRequest, or fetch call, $.ajax, etc.), our browser would tell us it's not allowed with this ugly error:

This is a Content Security Policy restriction error, it's designed to protect users from certain attacks. You should just configure it properly (see at the end).

How would the JSONP trick help us here? Well, <script> tags are not subjected to this whole server (origin1) restriction! That's why we can load a library like jQuery or Google Maps from any server.

Here's the important point: if you think about it, those libraries are actual, runnable JS code (usually a massive function with all the logic inside). But raw data is not code. There's nothing to run; it's just plain text.

Hence, the browser will download the data pointed at by our <script> tag and when processing it'll rightfully complain:

wtf is this {"city":"Barcelona"} crap we loaded? It's not code. I can't compute!

The old JSONP hack

If only we could make plain text somehow runnable, we could grab it on runtime. We need anotherweb.com to send it as it if were code, so when it's downloaded the browser will run it. We just need two things: 1) to get the data in a way that it can be run, and 2) write some code in the client so that when the data runs, our function is called and we get to use the data.

For 1) if the foreign server is JSONP friendly we'll ask for the data like this:

<script src="https://anotherweb.com/api/tourism-data.json?myCallback=tourismJSONP"></script>

So we'll receive it like this:

tourismJSONP({"city":"Barcelona"})

which now makes it JS code that we could interact with.

As per 2), we need to write a function with the same name in our code, like this:

function tourismJSONP(data){
  alert(data.city); // "Barcelona"
}

The browser will download the JSONP and run it, which calls our function, where the argument data will be the JSON data from anotherweb.com. We can now do with our data whatever we want to.

Don't use JSONP, use CORS

JSONP is a cross-site hack with a few downsides:

We can only perform GET requests

Since it's a GET request triggered by a simple script tag, we don't get helpful errors or progress info

There are also some security concerns, like running in your client JS code that could be changed to a malicious payload

It only solves the problem with JSON data, but Same-Origin security policy applies to other data (WebFonts, images/video drawn with drawImage()...)

It's not very elegant nor readable.

The takeaway is that there's no need to use it nowadays.

You should read about CORS here, but the gist of it is:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin. A web application executes a cross-origin HTTP request when it
requests a resource that has a different origin (domain, protocol, or
port) from its own.

origin is defined by 3 things: protocol, port, and host. So, https://web.com is a different origin than http://web.com (different protocol), also https://web.com:8081 (different port) and obviously https://thatotherweb.net (different host)


问:
Why my search for faunaDB can't get any item?
I'm stacking in searching faunaDB document by index. Please tell me what is wrong with my steps.

I have a document that has a value of externalID as "GBXzbXya".

I've created a index named label_search_by_externalID which has term as externalID

Then I've searched GBXzbXya, but I've got a blank array as follows:

Now, I've no idea what was wrong. Any suggestions are welcome! Thank you for your help!

答: I've found the cause is the case mismatch. The document entry is externalID although Index term is ExternalID.


问:
Using non-hashable Python objects as keys in dictionaries
Python doesn't allow non-hashable objects to be used as keys in other dictionaries. As pointed out by Andrey Vlasovskikh, there is a nice workaround for the special case of using non-nested dictionaries as keys:

```<code>frozenset(a.items())#Can be put in the dictionary instead
</code>```

Is there a method of using arbitrary objects as keys in dictionaries?

Example:

How would this be used as a key?

```<code>{"a":1, "b":{"c":10}}
</code>```

It is extremely rare that you will actually have to use something like this in your code. If you think this is the case, consider changing your data model first.

Exact use case

The use case is caching calls to an arbitrary keyword only function. Each key in the dictionary is a string (the name of the argument) and the objects can be quite complicated, consisting of layered dictionaries, lists, tuples, ect.

Related problems

This sub-problem has been split off from the problem here. Solutions here deal with the case where the dictionaries is not layered.

答:
Based off solution by Chris Lutz again. </p>

```<code>import collections

def hashable(obj):
    if isinstance(obj, collections.Hashable):
        items = obj
    elif isinstance(obj, collections.Mapping):
        items = frozenset((k, hashable(v)) for k, v in obj.iteritems())
    elif isinstance(obj, collections.Iterable):
        items = tuple(hashable(item) for item in obj)
    else:
        raise TypeError(type(obj))

    return items
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Python doesn't allow non-hashable objects to be used as keys in other dictionaries. As pointed out by Andrey Vlasovskikh, there is a nice workaround for the special case of using non-nested dictionaries as keys:

frozenset(a.items())#Can be put in the dictionary instead

Is there a method of using arbitrary objects as keys in dictionaries?

Example:

How would this be used as a key?

{"a":1, "b":{"c":10}}

It is extremely rare that you will actually have to use something like this in your code. If you think this is the case, consider changing your data model first.

Exact use case

The use case is caching calls to an arbitrary keyword only function. Each key in the dictionary is a string (the name of the argument) and the objects can be quite complicated, consisting of layered dictionaries, lists, tuples, ect.

Related problems

This sub-problem has been split off from the problem here. Solutions here deal with the case where the dictionaries is not layered.

Body:
Based off solution by Chris Lutz again.

import collections

def hashable(obj):
    if isinstance(obj, collections.Hashable):
        items = obj
    elif isinstance(obj, collections.Mapping):
        items = frozenset((k, hashable(v)) for k, v in obj.iteritems())
    elif isinstance(obj, collections.Iterable):
        items = tuple(hashable(item) for item in obj)
    else:
        raise TypeError(type(obj))

    return items


问:
How to create a release signed apk file using Gradle?
I would like to have my Gradle build to create a release signed apk file using Gradle.

I'm not sure if the code is correct or if I'm missing a parameter when doing gradle build?

This is some of the code in my build.gradle/build.gradle.kts file:

```<code>android {
    ...
    signingConfigs {
        release {
            storeFile(file("release.keystore"))
            storePassword("******")
            keyAlias("******")
            keyPassword("******")
        }
    }
}
</code>```

The Gradle build finishes SUCCESSFUL, and in my build/apk folder I only see the ...-release-unsigned.apk and ...-debug-unaligned.apk files.

Any suggestions on how to solve this?

答:
Adding my way to do it in React-Native using react-native-config package.

Create a .env file:

```<code>RELEASE_STORE_PASSWORD=[YOUR_PASSWORD]
RELEASE_KEY_PASSWORD=[YOUR_PASSWORD]
</code>```

note this should not be part of the version control.

in your build.gradle:

```<code>signingConfigs {
        debug {
            ...
        }
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword project.env.get('RELEASE_STORE_PASSWORD')
            keyAlias RELEASE_KEY_ALIAS
            keyPassword project.env.get('RELEASE_KEY_PASSWORD')
        }
    }
</code>```

Body:
I would like to have my Gradle build to create a release signed apk file using Gradle.

I'm not sure if the code is correct or if I'm missing a parameter when doing gradle build?

This is some of the code in my build.gradle/build.gradle.kts file:

android {
    ...
    signingConfigs {
        release {
            storeFile(file("release.keystore"))
            storePassword("******")
            keyAlias("******")
            keyPassword("******")
        }
    }
}

The Gradle build finishes SUCCESSFUL, and in my build/apk folder I only see the ...-release-unsigned.apk and ...-debug-unaligned.apk files.

Any suggestions on how to solve this?

Body:
Adding my way to do it in React-Native using react-native-config package.

Create a .env file:

RELEASE_STORE_PASSWORD=[YOUR_PASSWORD]
RELEASE_KEY_PASSWORD=[YOUR_PASSWORD]

note this should not be part of the version control.

in your build.gradle:

signingConfigs {
        debug {
            ...
        }
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword project.env.get('RELEASE_STORE_PASSWORD')
            keyAlias RELEASE_KEY_ALIAS
            keyPassword project.env.get('RELEASE_KEY_PASSWORD')
        }
    }


问:
Can any one explain the meaning of orderby line of SQL in below code?
Could anyone please explain the meaning of orderby line in below code?</p>

```<code>SELECT winner, subject
FROM nobel
WHERE year=1984
ORDER BY subject IN ('Chemistry', 'Physics'),subject,winner
</code>```

答: You are ordering to keep Chemistry and Physics values as the priority of sort order, followed by other subjects and winner</p>

Body:
Could anyone please explain the meaning of orderby line in below code?

SELECT winner, subject
FROM nobel
WHERE year=1984
ORDER BY subject IN ('Chemistry', 'Physics'),subject,winner


问:
Checking null object in react js with graphql query
I am new to the react and graphql . here, I have a query and I want to check the null data.

```<code>return (
      <Query
        query={Report}
        variables={{
          id: match.params.pId
        }}
        {({ loading, error, data: gdata }) => {
          if (loading) return <Loader />
          if (error) return <Error />
          return <Report data={gdata && gdata.greport} />
        }}
      </Query>
</code>```

So, I checking null using this way or

```<code>data: gdata = { gdata: {} } })
</code>```

In which way should I check for the null or empty data as it gets crashed .And also if it is an array. Thanks for the help.

答:
Currently I am checking the result on my project using ternary

if its an array

```<code>gData ? gData.greport : []
</code>```

if its an object

```<code>gData ? gData.greport : {}
</code>```

Body:
I am new to the react and graphql . here, I have a query and I want to check the null data.

return (
      <Query
        query={Report}
        variables={{
          id: match.params.pId
        }}
        {({ loading, error, data: gdata }) => {
          if (loading) return <Loader />
          if (error) return <Error />
          return <Report data={gdata && gdata.greport} />
        }}
      </Query>

So, I checking null using this way or

data: gdata = { gdata: {} } })

In which way should I check for the null or empty data as it gets crashed .And also if it is an array. Thanks for the help.

Body:
Currently I am checking the result on my project using ternary

if its an array

gData ? gData.greport : []

if its an object

gData ? gData.greport : {}


问:
Implementing own localization engine in React.js - is it worth it?
I decided to write my own localisation engine using react hooks.
I don't need too much localisations, just want to display messages depending chosen locale.
I have some questions about performance and etc.

This is my translation component which simply returns message by given key:

```<code>import React from 'react';
import useLocale from 'store/LocaleContext';

export default ({ k }) => {
  const { messages } = useLocale();

  const msg = messages[k] ? messages[k] : k;

  return <>{msg}</>;
};
</code>```

As you can see it uses react hooks and i have messages asynchronously loaded in context provider.

My app is medium sized project and so I am planing to use 50-100 or more <Translate k="messagekey" /> component in it.

Does it affects my app performance if so many components are subscribed to one context which has provided about 5-6 KB data? (I mean messages will be about 5-10KB in size).

Is it good to use this engine instead of react-intl or react-i18n, if I ignore other localisation issues (date, time, currency, number ..., Just for messages)?

Edit:

https://codesandbox.io/s/test-localisations-8kynz This is sample codesandbox link.

You can see whole localisation files which I created.

Also I added translate function which doesn't returns component but only translated message. Is it good practice to do that?

答:
The problem you might face using a Context is that every time the Provider updates, it will render. And every time a component renders its children render too (unless they are memoized).

In the case you describe I can think of two scenarios.

Are all messages loaded at once?

If this is the case you will have an initial render and another one after the data is fetched. From this point the data will not change and the Provider will not trigger new renders.

Are messages updated/added several times?

In this case every time the Provider updates all of its children will render. This can be an issue if there are many children and are not memoized.

If your case is the first one I would test if there is any issue managing the data inside a Context.

In the second case you might want to consider other options, like using Redux instead of a Context or possibly one of the libraries you suggest.

In any of the two cases, if you are managing a large amount of information in a single object you might consider using different Context and providing smaller sets of data to different parts of the app.

Body:
I decided to write my own localisation engine using react hooks.
I don't need too much localisations, just want to display messages depending chosen locale.
I have some questions about performance and etc.

This is my translation component which simply returns message by given key:

import React from 'react';
import useLocale from 'store/LocaleContext';

export default ({ k }) => {
  const { messages } = useLocale();

  const msg = messages[k] ? messages[k] : k;

  return <>{msg}</>;
};

As you can see it uses react hooks and i have messages asynchronously loaded in context provider.

My app is medium sized project and so I am planing to use 50-100 or more <Translate k="messagekey" /> component in it.

Does it affects my app performance if so many components are subscribed to one context which has provided about 5-6 KB data? (I mean messages will be about 5-10KB in size).

Is it good to use this engine instead of react-intl or react-i18n, if I ignore other localisation issues (date, time, currency, number ..., Just for messages)?

Edit:

https://codesandbox.io/s/test-localisations-8kynz This is sample codesandbox link.

You can see whole localisation files which I created.

Also I added translate function which doesn't returns component but only translated message. Is it good practice to do that?