问:
ReactJs -TimeTravel - FB tutorial - how does setState in jumpTo work?
The following code is in time-travel section of reactjs tutorial from FB here:

```<code> jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }
</code>```

How does this.setState exactly work in this code? IMO, it creates immutable copy of current state of Game and merges stepNumber and xIsNext properties into it. How does this exactly achieve time travel?  Shouldn't jumpTo delete history after the step?

答:
This is a trickiest part of the tutorial. It is correct that jumpTo resets stepNumber of the latest status of Game component. However render method of Game component uses stepNumber as index to retrieve current squares from history. This is very clever indeed. Code excerpt below:

```<code>render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
</code>```

So the answer to question "Shouldn't jumpTo chop-off the history until that step?" is No. Also if jumpTo tries to modify history then time travel will not be possible, technically speaking.

It's also worth noting that as soon as a historical step is modified by clicking on board, all "future" history from that step becomes invalid. Therefore chopping history is done in handleClick method. Code excerpt from Game component's handleClick method:

```<code>handleClick(i) {
   const history = this.state.history.slice(0, this.state.stepNumber + 1);
   const current = history[history.length - 1];
   const squares = current.squares.slice();
</code>```

Body:
The following code is in time-travel section of reactjs tutorial from FB here:

 jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }

How does this.setState exactly work in this code? IMO, it creates immutable copy of current state of Game and merges stepNumber and xIsNext properties into it. How does this exactly achieve time travel?  Shouldn't jumpTo delete history after the step?

Body:
This is a trickiest part of the tutorial. It is correct that jumpTo resets stepNumber of the latest status of Game component. However render method of Game component uses stepNumber as index to retrieve current squares from history. This is very clever indeed. Code excerpt below:

render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

So the answer to question "Shouldn't jumpTo chop-off the history until that step?" is No. Also if jumpTo tries to modify history then time travel will not be possible, technically speaking.

It's also worth noting that as soon as a historical step is modified by clicking on board, all "future" history from that step becomes invalid. Therefore chopping history is done in handleClick method. Code excerpt from Game component's handleClick method:

handleClick(i) {
   const history = this.state.history.slice(0, this.state.stepNumber + 1);
   const current = history[history.length - 1];
   const squares = current.squares.slice();


来源: stackexchange

问:
Right syntax for a while loop in a GitLab CI file
I want to write a while loop in a GitLab CI file and here is the syntax that I've tried but seems to not be working.

Is the while loop authorized in GitLab or YAML files? Or are there other ways to write it?

Here is where I used it:

```<code>  - while ($(curl -X GET ${URL} | jq -r '.task.status') != "SUCCESS")
   ANALYSIS_ID=$(curl -X GET ${URL} | jq -r '.task.analysisId')
</code>```

答:
Why don't you write yourself a shell/python/whatever script and just run it from the CI?

YAML is not the suitable language to perform such a things (e.g. while loops, large conditions, for loops) and should not be used that way...

ContentLicense: CC BY-SA 4.0

Body:
I want to write a while loop in a GitLab CI file and here is the syntax that I've tried but seems to not be working.

Is the while loop authorized in GitLab or YAML files? Or are there other ways to write it?

Here is where I used it:

  - while ($(curl -X GET ${URL} | jq -r '.task.status') != "SUCCESS")
   ANALYSIS_ID=$(curl -X GET ${URL} | jq -r '.task.analysisId')


问:
Mongodb c# filter using and or operator
I have json documents in mongodb

Sample

```<code>{
 "SchemaName": "Intelligence",
 "SchemaDescription": "WindPower",
 "SchemaType": "WindPower",
 "SchemaTypeId": 1,
 "SchemaData": {
  "ProjectId": 1,
  "LastUpdated": "2016-07-02T19:27:28.000+0000",
  "ProjectName": "Zhonghuashan II",
  "Capacity": 49.0,
  "Technology": "Onshore",
   "Country":{
          "CountryId":1,
          "CountryName":"UnitedKingdom",
          "CountryCode":"UK"
    }
 }
}
</code>```

Now I am filtering data on basis on search criteria

```<code>var filter = Builders<Schema>.Filter.Or(
                Builders<Schema>.Filter.Where(p => p.SchemaData.ProjectName.ToLower().Contains(searchCriteria.ProjectName.ToLower())),
                Builders<Schema>.Filter.Where(p => p.SchemaData.Technology.ToLower().Contains(searchCriteria.Technology.ToLower())),
                Builders<Schema>.Filter.Where(p => p.SchemaData.Country.CountryName.ToLower().Contains(searchCriteria.Country.ToLower()))
            );
            var list = await collectionHandler.ReadOnly<Schema>().FindSync(filter).ToListAsync();
            return list;
</code>```

I need to add condition

searchCriteria.ProjectName ="" || searchCriteria.Technology="" || searchCriteria.Country = "" = return all records

searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" || searchCriteria.Country = "" = return matched records

searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

searchCriteria.ProjectName ="" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

searchCriteria.Technology="" ="abc" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

say any property of search criteria can have combination of and and or with other property of search criteria

答:
I did it this way:

Took as base this answer over here

```<code>        var idFilter = new BsonDocument { { "_id", new BsonDocument { { "$regex", codeRegex }, { "$options", "i" } } } };
        var nameFilter = new BsonDocument { { "Name", new BsonDocument { { "$regex", codeRegex }, { "$options", "i" } } } };

        var filter = new BsonDocument("$or", new BsonArray { idFilter, nameFilter });

        var query = _collection.Find(filter)
            .SortBy(c=>c.Id);
        return query.ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Mongodb c# filter using and or operator

Body:
I have json documents in mongodb

Sample

{
 "SchemaName": "Intelligence",
 "SchemaDescription": "WindPower",
 "SchemaType": "WindPower",
 "SchemaTypeId": 1,
 "SchemaData": {
  "ProjectId": 1,
  "LastUpdated": "2016-07-02T19:27:28.000+0000",
  "ProjectName": "Zhonghuashan II",
  "Capacity": 49.0,
  "Technology": "Onshore",
   "Country":{
          "CountryId":1,
          "CountryName":"UnitedKingdom",
          "CountryCode":"UK"
    }
 }
}

Now I am filtering data on basis on search criteria

var filter = Builders<Schema>.Filter.Or(
                Builders<Schema>.Filter.Where(p => p.SchemaData.ProjectName.ToLower().Contains(searchCriteria.ProjectName.ToLower())),
                Builders<Schema>.Filter.Where(p => p.SchemaData.Technology.ToLower().Contains(searchCriteria.Technology.ToLower())),
                Builders<Schema>.Filter.Where(p => p.SchemaData.Country.CountryName.ToLower().Contains(searchCriteria.Country.ToLower()))
            );
            var list = await collectionHandler.ReadOnly<Schema>().FindSync(filter).ToListAsync();
            return list;

I need to add condition

searchCriteria.ProjectName ="" || searchCriteria.Technology="" || searchCriteria.Country = "" = return all records

searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" || searchCriteria.Country = "" = return matched records

searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

searchCriteria.ProjectName ="" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

searchCriteria.Technology="" ="abc" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

say any property of search criteria can have combination of and and or with other property of search criteria

Body:
I did it this way:

Took as base this answer over here

        var idFilter = new BsonDocument { { "_id", new BsonDocument { { "$regex", codeRegex }, { "$options", "i" } } } };
        var nameFilter = new BsonDocument { { "Name", new BsonDocument { { "$regex", codeRegex }, { "$options", "i" } } } };

        var filter = new BsonDocument("$or", new BsonArray { idFilter, nameFilter });

        var query = _collection.Find(filter)
            .SortBy(c=>c.Id);
        return query.ToList();


问:
bootstrap4 dataTables search option is not working
I am using bootstrap4 dataTables for showing row limit & search options. I am using Ajax for populated data from server. Data is populated in dataTables but search option is & show row options is not working. here is my table images

I have used bellow code

HTML Code

```<code><table class="table table-bordered" id="tb_requisiton" width="100%" cellspacing="0">
<thead>
    <tr>
       <th>Std. ID</th>
        <th>Name</th>
    </tr>
</thead>
<tfoot>
  <tr>
    <th>Std. ID</th>
      <th>Name</th>
        </tr>
</tfoot>
</table>
</code>```

Ajax populate code

```<code>  var trHTML = '';
    for (var i = 0; i < data.length; i++) {
      var item = data[i];

      trHTML += '<tr>'
      trHTML += '<td>'+ item.client_id + '</td>'
      trHTML += '<td>'+ item.name + '</td>'
      trHTML += '</tr>'
    }

    $('#tb_requisiton tbody').append(trHTML);
</code>```

Onload I have used bellow code

```<code>    $(document).ready(function() {

    $('#tb_requisiton').DataTable();

} );
</code>```

I have used bellow js & css

```<code>  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet">
 <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">

<script src=" https://code.jquery.com/jquery-3.3.1.js"></script>
<script src=" https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</code>```

答:
Call the ajax inside the DataTable.</p>

```<code>$(document).ready(function() {

    $('#tb_requisiton').DataTable({
        "ajax": 'data.txt'//ajax url
    });

});
</code>```

Body:
I am using bootstrap4 dataTables for showing row limit & search options. I am using Ajax for populated data from server. Data is populated in dataTables but search option is & show row options is not working. here is my table images

I have used bellow code

HTML Code

       Std. ID
        Name

    Std. ID
      Name

Ajax populate code

  var trHTML = '';
    for (var i = 0; i < data.length; i++) {
      var item = data[i];

      trHTML += '
'
      trHTML += ''+ item.client_id + '	'
      trHTML += ''+ item.name + '	'
      trHTML += '
'
    }

    $('#tb_requisiton tbody').append(trHTML);

Onload I have used bellow code

    $(document).ready(function() {

    $('#tb_requisiton').DataTable();

} );

I have used bellow js & css

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet">
 <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">

Body:
Call the ajax inside the DataTable.

$(document).ready(function() {

    $('#tb_requisiton').DataTable({
        "ajax": 'data.txt'//ajax url
    });

});


问:
c# - using : bad practice to use?
I have read more that year ago that there are a few bad practice to use </p>

```<code>using (some code) {

}
</code>```

<p>. Could someone explain me all these bad practice?
Thanks.</p>

答: Why do you think it's a bad practice? It can be a very good (or best) practice since the object will be disposed immediately after the using block.</p>

Title: c# - using : bad practice to use?

Body:
I have read more that year ago that there are a few bad practice to use

using (some code) {

}

. Could someone explain me all these bad practice?
Thanks.


问:
clearable prop is not working for me, can anyone suggest please
I have a custom input field which i use in my entire project.

I am trying to use clearable props in my input component so that i can clear text with one click.

but setting clearable:"true" is not working.

I am using

<input :class="inputClass" v-bind="$attrs" :clearable="clearable" :value="value" @input="(e) => $emit('input', e.target.value)"/>

and clearable's value is coming via props which i am passing from component i have to use clearable in.

Please guide me..
thanks in Advance !!!!

答:
clearable is not a standard HTML attribute.  You're going to have to use a custom component for this, which would be easier to use with v-model.. I have supplied an example of how to accomplish this using events/default value as well as an example that shows how to do this using v-model:

[CodePen Mirror]

Edit: cleaned up the code a little bit...

const customInputNoVmodel = {
  template: "#custom-input-no-vmodel",
  props: {
    clearable: {
      type: Boolean,
      required: false,
      default: false
    },
  },
  methods: {
    onInput(e) {
      this.$emit("input", e.target.value);
    }
  },
  computed: {
    isClearable() {
      return this.clearable === true ? "search" : "text";
    }
  }
};

const vm = new Vue({
  el: "#app",
  components: {
    customInputNoVmodel
  },
  data: {
    value: "Initial Value Without v-model",
    cssClasses: "my-class-one"
  },
  methods: {
    handleInput(e) {
      this.value = e;
    }
  }
});

/* *************************** */

const customInputWithVmodel = {
  template: "#custom-input-with-vmodel",
  props: {
    value: {
      type: String,
      required: false,
    },
    clearable: {
      type: Boolean,
      required: false,
      default: false
    },
  },
  computed: {
    isClearable() {
      return this.clearable === true ? "search" : "text";
    },
    handleOnInput: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val)
      }
    },
  }
};

const vm2 = new Vue({
  el: "#app2",
  components: {
    customInputWithVmodel
  },
  data: {
    text: "Initial Value With v-model",
    cssClasses: "my-class-two"
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.my-class-one {
  background-color: blue;
  color: white;
  border: 1px solid red;
  width: 200px;
}

.my-class-two {
  background-color: black;
  color: red;
  border: 5px solid darkmagenta;
  width: 250px;
}</code>```

    Not using v-model:
    <custom-input-no-vmodel
      class="my-class-one"
      :clearable="true"
      :value="value"
      @input="handleInput"
    ></custom-input-no-vmodel>

    With v-model
    <custom-input-with-vmodel
      :class="cssClasses"
      :clearable="true"
      v-model="text"
    ></custom-input-with-vmodel>

```

Body:
clearable is not a standard HTML attribute.  You're going to have to use a custom component for this, which would be easier to use with v-model.. I have supplied an example of how to accomplish this using events/default value as well as an example that shows how to do this using v-model:

[CodePen Mirror]

Edit: cleaned up the code a little bit...

const customInputNoVmodel = {
  template: "#custom-input-no-vmodel",
  props: {
    clearable: {
      type: Boolean,
      required: false,
      default: false
    },
  },
  methods: {
    onInput(e) {
      this.$emit("input", e.target.value);
    }
  },
  computed: {
    isClearable() {
      return this.clearable === true ? "search" : "text";
    }
  }
};

const vm = new Vue({
  el: "#app",
  components: {
    customInputNoVmodel
  },
  data: {
    value: "Initial Value Without v-model",
    cssClasses: "my-class-one"
  },
  methods: {
    handleInput(e) {
      this.value = e;
    }
  }
});

/* *************************** */

const customInputWithVmodel = {
  template: "#custom-input-with-vmodel",
  props: {
    value: {
      type: String,
      required: false,
    },
    clearable: {
      type: Boolean,
      required: false,
      default: false
    },
  },
  computed: {
    isClearable() {
      return this.clearable === true ? "search" : "text";
    },
    handleOnInput: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val)
      }
    },
  }
};

const vm2 = new Vue({
  el: "#app2",
  components: {
    customInputWithVmodel
  },
  data: {
    text: "Initial Value With v-model",
    cssClasses: "my-class-two"
  }
})

.my-class-one {
  background-color: blue;
  color: white;
  border: 1px solid red;
  width: 200px;
}

.my-class-two {
  background-color: black;
  color: red;
  border: 5px solid darkmagenta;
  width: 250px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <div>
    Not using v-model:
    <custom-input-no-vmodel
      class="my-class-one"
      :clearable="true"
      :value="value"
      @input="handleInput"
    ></custom-input-no-vmodel>
  </div>
</div>

<br/>

<div id="app2">
  <div>
    With v-model
    <custom-input-with-vmodel
      :class="cssClasses"
      :clearable="true"
      v-model="text"
    ></custom-input-with-vmodel>
  </div>
</div>

<!-- SIMULATES COMPONENT ~~WITHOUT~~ V-MODEL -->
<script type="text/x-template" id="custom-input-no-vmodel">
    <input
      v-bind="$attrs"
      :type="isClearable"
      @input="onInput"
    />
</script>

<!-- SIMULATES COMPONENT WITH V-MODEL -->
<script type="text/x-template" id="custom-input-with-vmodel">
    <input
      v-bind="$attrs"
      :type="isClearable"
      v-model="handleOnInput"
    />
</script>


问:
Is there a method to check if an array has ANY value in it?
Say I want to have an if statement to test if an array is empty or not,
Looking it up I have found no way to check besides array[0], which in frameworks like React and Angular give errors on the array's item not existing.

```<code>let arr = [];

if (!arr[0]) {
  arr.map(val=>{
    return <div>{val.name}</div>
  });
}
</code>```

In this example I want it to Display the JSX and if not, do not display any JSX. But doing this throws an error. Is there anyway to do this? preferably without any outside libraries.

edit: "added 'this' after 'to do'"

答:
If you're not even certain your variable even is an array, this is what I would do:

```<code>if (Array.isArray(arr) && arr.length) { /*...*/ }
</code>```

For your special case you probably don't even need the 2nd check, though, because all of the Array iterators don't run even once if the Array they are called on is empty.

Example:

const arr = [];

console.log(arr.map(Number));
console.log(arr.some(parseInt));
console.log(arr.every(parseInt));
console.log(arr.filter(Number));```

None of the methods will throw an error provide arr is an array.

Body:
Say I want to have an if statement to test if an array is empty or not,
Looking it up I have found no way to check besides array[0], which in frameworks like React and Angular give errors on the array's item not existing.

let arr = [];

if (!arr[0]) {
  arr.map(val=>{
    return
{val.name}

  });
}

In this example I want it to Display the JSX and if not, do not display any JSX. But doing this throws an error. Is there anyway to do this? preferably without any outside libraries.

edit: "added 'this' after 'to do'"

Body:
If you're not even certain your variable even is an array, this is what I would do:

if (Array.isArray(arr) && arr.length) { /*...*/ }

For your special case you probably don't even need the 2nd check, though, because all of the Array iterators don't run even once if the Array they are called on is empty.

Example:

const arr = [];

console.log(arr.map(Number));
console.log(arr.some(parseInt));
console.log(arr.every(parseInt));
console.log(arr.filter(Number));

None of the methods will throw an error provide arr is an array.


问:
Cron job doesn't start nodejs correctly
This is a bit of a weird one and I have no clue what to do.
I have a small node express api which is hosted on my Raspberry Pi which is running raspbian.

The js file is started in a cron job:

@reboot sudo  /usr/bin/node /var/www/html/api/server.js &

And the API itself works fine, I can access it and it returns my requests without a problem.

But the API is also supposed to write to a log file when someone makes a request:

```<code>fs.appendFile("./ServerLog.log", "[" + dateTime + "]" + " [" + status + "] " + message + "\n", null, () => {
});
</code>```

This does not work. But when I kill the process which was started through the cronjob and start it manually it creates a log.

I tried launching node with bash, i.e:

```<code>@reboot sudo bash -c "sudo  /usr/bin/node /var/www/html/api/server.js &"
</code>```

But that did not change anything. I also changed the output to just write "TEST" but that did not work either. I do have a shebang at the beginning of my js file : #!/usr/bin/env node

These are the lines which are printed to the syslog:

```<code>Nov 18 20:20:05 raspberrypi cron[331]: (CRON) INFO (pidfile fd = 3)
Nov 18 20:20:05 raspberrypi cron[331]: (CRON) INFO (Running @reboot jobs)
</code>```

And in auth.log:

```<code>Nov 18 20:20:05 raspberrypi systemd-logind[309]: New seat seat0.
Nov 18 20:20:05 raspberrypi CRON[343]: pam_unix(cron:session): session opened for user root by (uid=0)
Nov 18 20:20:05 raspberrypi CRON[343]: pam_unix(cron:session): session closed for user root
Nov 18 20:20:05 raspberrypi sudo:     root : TTY=unknown ; PWD=/root ; USER=root ; COMMAND=/usr/bin/node /var/www/html/api/server.js
Nov 18 20:20:05 raspberrypi sudo: pam_unix(sudo:session): session opened for user root by (uid=0)
</code>```

答:
the issue is with the PATH.

for me I was using serveStatic and providing the path to the static folder like ./public. This was resolving to the wrong path. By providing complete URL i was able to resolve the issue.

You may solve the same issue with other solutions also, the point is that your code is not resolving to the write file because of PATH.

Title: Cron job doesn't start nodejs correctly

Body:
This is a bit of a weird one and I have no clue what to do.
I have a small node express api which is hosted on my Raspberry Pi which is running raspbian.

The js file is started in a cron job:

@reboot sudo  /usr/bin/node /var/www/html/api/server.js &

And the API itself works fine, I can access it and it returns my requests without a problem.

But the API is also supposed to write to a log file when someone makes a request:

fs.appendFile("./ServerLog.log", "[" + dateTime + "]" + " [" + status + "] " + message + "\n", null, () => {
});

This does not work. But when I kill the process which was started through the cronjob and start it manually it creates a log.

I tried launching node with bash, i.e:

@reboot sudo bash -c "sudo  /usr/bin/node /var/www/html/api/server.js &"

But that did not change anything. I also changed the output to just write "TEST" but that did not work either. I do have a shebang at the beginning of my js file : #!/usr/bin/env node

These are the lines which are printed to the syslog:

Nov 18 20:20:05 raspberrypi cron[331]: (CRON) INFO (pidfile fd = 3)
Nov 18 20:20:05 raspberrypi cron[331]: (CRON) INFO (Running @reboot jobs)

And in auth.log:

Nov 18 20:20:05 raspberrypi systemd-logind[309]: New seat seat0.
Nov 18 20:20:05 raspberrypi CRON[343]: pam_unix(cron:session): session opened for user root by (uid=0)
Nov 18 20:20:05 raspberrypi CRON[343]: pam_unix(cron:session): session closed for user root
Nov 18 20:20:05 raspberrypi sudo:     root : TTY=unknown ; PWD=/root ; USER=root ; COMMAND=/usr/bin/node /var/www/html/api/server.js
Nov 18 20:20:05 raspberrypi sudo: pam_unix(sudo:session): session opened for user root by (uid=0)


问:
Where to put ssl certificates when trying to connect to a remote database using psycopg2?
I have created a Google PostgreSQL instance and I'm trying to operate it from a remote webserver, I have whitelisted the IP and turned on SSL-only mode. I created client certificates, but I'm clueless as to where to put them or how to reference them. I can't find anything about it online.

Any help would be appreciated

My psycopg2 connect statement looks like this and gives me an error saying it needs client certificates:

```<code>conn = psycopg2.connect(
            user="postgres",
            password="password",
            host="{IP_ADDRESS}",
            port="5432",
            database="testdb",
            sslmode="require",
}
</code>```

答:
I figured it out myself, I got some instructions on how to connect with psql and that also applied to psycopg2.

Google instructed me I could connect through psql with this terminal command:

```<code>  psql "sslmode=verify-ca sslrootcert=server-ca.pem \
      sslcert=client-cert.pem sslkey=client-key.pem \
      hostaddr={IP_ADDRESS} \
      port=5432 \
      user=postgres dbname=postgres"
</code>```

So I edited my connect function to add these keys:

```<code>sslrootcert=server-ca.pem
sslcert=client-cert.pem
sslkey=client-key.pem
</code>```

Make sure to run

```<code>$ chmod 0600 client-key.pem
</code>```

Or it won't work

Body:
I have created a Google PostgreSQL instance and I'm trying to operate it from a remote webserver, I have whitelisted the IP and turned on SSL-only mode. I created client certificates, but I'm clueless as to where to put them or how to reference them. I can't find anything about it online.

Any help would be appreciated

My psycopg2 connect statement looks like this and gives me an error saying it needs client certificates:

conn = psycopg2.connect(
            user="postgres",
            password="password",
            host="{IP_ADDRESS}",
            port="5432",
            database="testdb",
            sslmode="require",
}

Body:
I figured it out myself, I got some instructions on how to connect with psql and that also applied to psycopg2.

Google instructed me I could connect through psql with this terminal command:

  psql "sslmode=verify-ca sslrootcert=server-ca.pem \
      sslcert=client-cert.pem sslkey=client-key.pem \
      hostaddr={IP_ADDRESS} \
      port=5432 \
      user=postgres dbname=postgres"

So I edited my connect function to add these keys:

sslrootcert=server-ca.pem
sslcert=client-cert.pem
sslkey=client-key.pem

Make sure to run

$ chmod 0600 client-key.pem

Or it won't work


问:
Firebase reading operation gave back an empty Array in Android
I'm trying to implement Firebase Database in my Android app, but when it give back the array which is supposed to be fill with the names of the strings, it is void. This is the function that I use to get back the names:

```<code>public class FirebaseOperation {

private static final String TAG1 = "Operacion de lectura";
FirebaseDatabase database = FirebaseDatabase.getInstance();
private final Callback callback;

public FirebaseOperation(Callback callback){
    this.callback = callback;
}

interface Callback{
    void dataIsLoaded(ArrayList<String> names);
}

public void  getUserNames(){
    final ArrayList<String> names = new ArrayList<>();

    DatabaseReference ref = database.getReference().child("idUsers");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()){
                String name = ds.getValue(String.class);
                names.add(name);
                Log.d(TAG1, "LEcturea correcta");
            }
            callback.dataIsLoaded(names);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.w(TAG1, "Error al leer los nombres de usuario");
        }
    });

}

}
</code>```

And here is where i called it:

```<code>idusers = new ArrayList<>();
new FirebaseOperation(new FirebaseOperation.Callback() {
    @Override
    public void dataIsLoaded(ArrayList<String> names) {
          idusers = names;
}
}).getUsernames();
if(idusers.isEmpty()){
                Log.w(TAG, "Array VACIOOOOO");
            }
</code>```

And it's supposed to return the ArrayList but when it returns is void, however in that function it enters in the onDataChange , so it's supposed to be Reading the values, but returns an empty array to the other class. Some ideas? I let you a capture of my database structure.

Database

Some ideas??

答:
Because new ValueEventListener() is an asynchronous callback, this means the return nombres happens before the Firebase RTD has responded.

If you want to keep your class FirebaseOperation then you should have to use another callback to pass the Firebase once has been retrieved:

```<code>public class FirebaseOperation {

    private final Callback callback;

    //Initializing the callback on the constructor for simplicity
    public FirebaseOperaion(Callback callback) {
        this.callback = callback;
    }

    //It doesn't return
    public void getUserNames(){
    final ArrayList<String> names = new ArrayList<>();

    DatabaseReference ref = database.getReference().child("idUsers");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()){
                String name = ds.getValue(String.class);
                names.add(name);
                Log.d(TAG1, "LEcturea correcta");
            }
            callback.rtdResponse(names);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.w(TAG1, "Error al leer los nombres de usuario");
        }
        });
    }

    interface Callback {
        void rtdResponse(List<String> names);
    }

}
</code>```

And now in the other class where you are using it, instead of

```<code>List<String> names = new FirebaseOperation().getUserNames();
</code>```

You will have to use the callback:

```<code>//Use this if you want the other class implements the callback
new FirebaseOperation(this).getUserNames();
//Or use an anonymous implementation
new FirebaseOperation(new Callback {
    @Override
    void rtdResponse(List<String> names) {
        //Do something with your list here
    }
}).getUserNames();
</code>```

Body:
I'm trying to implement Firebase Database in my Android app, but when it give back the array which is supposed to be fill with the names of the strings, it is void. This is the function that I use to get back the names:

public class FirebaseOperation {

private static final String TAG1 = "Operacion de lectura";
FirebaseDatabase database = FirebaseDatabase.getInstance();
private final Callback callback;

public FirebaseOperation(Callback callback){
    this.callback = callback;
}

interface Callback{
    void dataIsLoaded(ArrayList<String> names);
}

public void  getUserNames(){
    final ArrayList<String> names = new ArrayList<>();

    DatabaseReference ref = database.getReference().child("idUsers");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()){
                String name = ds.getValue(String.class);
                names.add(name);
                Log.d(TAG1, "LEcturea correcta");
            }
            callback.dataIsLoaded(names);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.w(TAG1, "Error al leer los nombres de usuario");
        }
    });

}

}

And here is where i called it:

idusers = new ArrayList<>();
new FirebaseOperation(new FirebaseOperation.Callback() {
    @Override
    public void dataIsLoaded(ArrayList<String> names) {
          idusers = names;
}
}).getUsernames();
if(idusers.isEmpty()){
                Log.w(TAG, "Array VACIOOOOO");
            }

And it's supposed to return the ArrayList but when it returns is void, however in that function it enters in the onDataChange , so it's supposed to be Reading the values, but returns an empty array to the other class. Some ideas? I let you a capture of my database structure.

Database

Some ideas??

Body:
Because new ValueEventListener() is an asynchronous callback, this means the return nombres happens before the Firebase RTD has responded.

If you want to keep your class FirebaseOperation then you should have to use another callback to pass the Firebase once has been retrieved:

public class FirebaseOperation {

    private final Callback callback;

    //Initializing the callback on the constructor for simplicity
    public FirebaseOperaion(Callback callback) {
        this.callback = callback;
    }

    //It doesn't return
    public void getUserNames(){
    final ArrayList<String> names = new ArrayList<>();

    DatabaseReference ref = database.getReference().child("idUsers");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()){
                String name = ds.getValue(String.class);
                names.add(name);
                Log.d(TAG1, "LEcturea correcta");
            }
            callback.rtdResponse(names);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.w(TAG1, "Error al leer los nombres de usuario");
        }
        });
    }

    interface Callback {
        void rtdResponse(List<String> names);
    }

}

And now in the other class where you are using it, instead of

List<String> names = new FirebaseOperation().getUserNames();

You will have to use the callback:

//Use this if you want the other class implements the callback
new FirebaseOperation(this).getUserNames();
//Or use an anonymous implementation
new FirebaseOperation(new Callback {
    @Override
    void rtdResponse(List<String> names) {
        //Do something with your list here
    }
}).getUserNames();


问:
"Bad Request" response on PredictHQ API ["error": invalid_client] "authentication" request
Currently looking to make an authentication request on the PredictHQ API using Alamofire.

I have generated client credentials in the developer's console, and transferred them to my project. The problem lies when I use the URL https://api.predicthq.com/oauth2/token/ in my function *receiveJSONData() to receive a network status of my requests.

Below are examples I followed from the PredictHQ website  https://developer.predicthq.com/oauth2/ on how the cURL request should be formatted as.

1) I first created my networkServiceClient class

```<code>import UIKit
import Alamofire

class networkServiceClient {

    private let token = "GENERATED_TOKEN_FROM_PREDICTHQ_API".data(using: String.Encoding.utf8)!.base64EncodedString()
    private let secret = "GENERATED_SECRET_KEY_FROM_PREDICTHQ_API".data(using: String.Encoding.utf8)!.base64EncodedString()
    private let id = "GENERATED_ID_FROM_PREDICTHQ_API".data(using: String.Encoding.utf8)!.base64EncodedString()
    private let contentType = "application/json"
    private var authURL = URL(string: "https://api.predicthq.com/oauth2/token/")
    private var tokenDataURL = URL(string: "https://api.predicthq.com/v1/events/")

    typealias webResponse = ([[String: Any]]?, Error?) -> Void

    func receiveJSONData(completion: @escaping webResponse){

        let loginString = String(format: "Basic %@:%@", id, secret)

        let postHeaders:HTTPHeaders =  ["Authorization": loginString, "Accept": contentType]

        let params: [String : Any] = ["grant_type": "client_credentials", "scope": "account events signals"]

         //post authentication request
        AF.request(authURL!, method: .post, parameters: params, headers: postHeaders).responseJSON { (response) in

            if let error = response.error {

                completion(nil, error)

            } else if let jsonArray = response.value as? [[String: Any]] {

                completion(jsonArray, nil)

            } else if let jsonDict = response.value as? [String: Any] {

                completion([jsonDict], nil)

            }

        }

}
</code>```

2) Then I implemented it in my TestingViewingController

```<code>import UIKit
import Alamofire

class TestingViewController: UIViewController {

    private let networkingClient = networkServiceClient()
    override func viewDidLoad() {
        super.viewDidLoad()
        networkingClient.receiveJSONData() { (json, error) in
            if let error = error {
                print(error.localizedDescription)
            } else if let json = json {

                print(json.description)
            }

        }

    }

}
</code>```

3) Lastly, here is my output in the TestingViewController console.

```<code>"error": invalid_client
</code>```

答: Hey it might be because you're base64 encoding the client_id and secret separately but they should be encoded together (separated by colon) like the screenshot shows.</p>

Body:
Currently looking to make an authentication request on the PredictHQ API using Alamofire.

I have generated client credentials in the developer's console, and transferred them to my project. The problem lies when I use the URL https://api.predicthq.com/oauth2/token/ in my function *receiveJSONData() to receive a network status of my requests.

Below are examples I followed from the PredictHQ website  https://developer.predicthq.com/oauth2/ on how the cURL request should be formatted as.

1) I first created my networkServiceClient class

import UIKit
import Alamofire

class networkServiceClient {

    private let token = "GENERATED_TOKEN_FROM_PREDICTHQ_API".data(using: String.Encoding.utf8)!.base64EncodedString()
    private let secret = "GENERATED_SECRET_KEY_FROM_PREDICTHQ_API".data(using: String.Encoding.utf8)!.base64EncodedString()
    private let id = "GENERATED_ID_FROM_PREDICTHQ_API".data(using: String.Encoding.utf8)!.base64EncodedString()
    private let contentType = "application/json"
    private var authURL = URL(string: "https://api.predicthq.com/oauth2/token/")
    private var tokenDataURL = URL(string: "https://api.predicthq.com/v1/events/")

    typealias webResponse = ([[String: Any]]?, Error?) -> Void

    func receiveJSONData(completion: @escaping webResponse){

        let loginString = String(format: "Basic %@:%@", id, secret)

        let postHeaders:HTTPHeaders =  ["Authorization": loginString, "Accept": contentType]

        let params: [String : Any] = ["grant_type": "client_credentials", "scope": "account events signals"]

         //post authentication request
        AF.request(authURL!, method: .post, parameters: params, headers: postHeaders).responseJSON { (response) in

            if let error = response.error {

                completion(nil, error)

            } else if let jsonArray = response.value as? [[String: Any]] {

                completion(jsonArray, nil)

            } else if let jsonDict = response.value as? [String: Any] {

                completion([jsonDict], nil)

            }

        }

}

2) Then I implemented it in my TestingViewingController

import UIKit
import Alamofire

class TestingViewController: UIViewController {

    private let networkingClient = networkServiceClient()
    override func viewDidLoad() {
        super.viewDidLoad()
        networkingClient.receiveJSONData() { (json, error) in
            if let error = error {
                print(error.localizedDescription)
            } else if let json = json {

                print(json.description)
            }

        }

    }

}

3) Lastly, here is my output in the TestingViewController console.

"error": invalid_client


问:
How to show  a default selecteditem in a flex combobox
In a flex application how to display default selecteditem from the dataprovider of the combobox.

I'm using {staticdataholder.currencylist}.

For example: I have to show INDIA so it should be selected as default from the list.

Where INDIA is one of the value in the currencylist.

All suggestions are welcome.

Thank you.

答:
You need to loop through your dataProvider and set the selected object:

Example:

```<code>for each ( var obj:Object in staticdataholder.currencylist ) {
    if ( obj == "INDIA" ) {
        cbx.selectedItem = obj;
        break;
    }
}
</code>```

Body:
You need to loop through your dataProvider and set the selected object:

Example:

for each ( var obj:Object in staticdataholder.currencylist ) {
    if ( obj == "INDIA" ) {
        cbx.selectedItem = obj;
        break;
    }
}


问:
Mockito: how to test method that changes private field value?
I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

```<code>private Map<String> myMap
</code>```

of the class.

Now I want to unit test the method create, how could I do it ?
Thanks!

答: You could access to you property with reflection (see here for instance) but the fact that you need to hack your class to check the outcome of a function execution sounds like a design smell. Unit testing should check the behaviour from end to end of your unit. Mutating the internal state of your object is a side effect that should be checked against an expectation that some mutation method has been invoked from your unit under test.....In practice, you can try to mock the Map.put() and verify that has been called instead of inspect the map itself </p>

Body:
I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

private Map<String> myMap

of the class.

Now I want to unit test the method create, how could I do it ?
Thanks!


问:
Tags in scraped content must have the same order as they have in the original HTML file
I try to build a web scraper. My scraper must find all rows which correspond with chosen tags and save them in the same order as original HTML to the new file.md file.

Tags are specified in an array:

```<code>list_of_tags_you_want_to_scrape = ['h1', 'h2', 'h3', 'p', 'li']
</code>```

then this gives me only the content within specified  tag:

```<code>soup_each_html = BeautifulSoup(particular_page_content, "html.parser")
inner_content = soup_each_html.find("article", "container")
</code>```

let's say that this is the result:

```<code><article class="container">
  <h1>this is headline 1</h1>
  <p>this is paragraph</p>
  <h2>this is headline 2</h2>
  <a href="bla.html">this won't be shown bcs 'a' tag is not in the array</a>
</article>
</code>```

then I have method which is responsible for writing a line to the file.md file if a tag from the array exists in the content

```<code>with open("file.md", 'a+') as f:
    for tag in list_of_tags_you_want_to_scrape:
        inner_content_tag = inner_content.find_all(tag)

        for x in inner_content_tag:
            f.write(str(x))
            f.write("\n")
</code>```

and it does. But the problem is, that it goes through the array (for each) and it will save all
 first, all
 on a second place, etc. And that's because that is the order specified in list_of_tags_you_want_to_scrape array.

this would be the result:

```<code><article class="container">
  <h1>this is headline 1</h1>
  <h2>this is headline 2</h2>
  <p>this is paragraph</p>
</article>
</code>```

so I would like to have them in the right order like the original HTML has. After the first
 should be
 element.

That means that I would probably need to do for each loop also with inner_content and check if each line from this inner_content is equals to at least one of the tags from the array. If yes then save and then move to another line. I tried to do it and made for each for inner_content to get line by line but it gave me an error and I am not sure if it is correct way how to do it. (First day using BeautifulSoup module)

Any tips or advices how to modify my method to achieve this please? thank you!

答:
To maintain the original order of the html input, you can use recursion to loop over the soup.contents attribute:

```<code>from bs4 import BeautifulSoup as soup
def parse(content, to_scrape = ['h1', 'h2', 'h3', 'p', 'li']):
   if content.name in to_scrape:
      yield content
   for i in getattr(content, 'contents', []):
      yield from parse(i)
</code>```

Example:

```<code>html = """
<html>
  <body>
      <h1>My website</h1>
      <p>This is my first site</p>
      <h2>See a listing of my interests below</h2>
      <ul>
         <li>programming</li>
         <li>math</li>
         <li>physics</li>
      </ul>
      <h3>Thanks for visiting!</h3>
  </body>
</html>
"""

result = list(parse(soup(html, 'html.parser')))
</code>```

Output:

```<code>[<h1>My website</h1>, <p>This is my first site</p>, <h2>See a listing of my interests below</h2>, <li>programming</li>, <li>math</li>, <li>physics</li>, <h3>Thanks for visiting!</h3>]
</code>```

As you can see, the original order of the html is maintained, and can now be written to the file:

```<code>with open('file.md', 'w') as f:
   f.write('\n'.join(map(str, result)))
</code>```

Each bs4 object contains a name and contents attribute, among others. The name attribute is the tag name itself, while the contents attribute stores all the child HTML. parse uses a generator to first check if the passed bs4 object has a tag that belongs to the to_scrape list and if so, yields that value. Lastly, parse iterates over the contents of content, and calls itself on each element.

Body:
I try to build a web scraper. My scraper must find all rows which correspond with chosen tags and save them in the same order as original HTML to the new file.md file.

Tags are specified in an array:

list_of_tags_you_want_to_scrape = ['h1', 'h2', 'h3', 'p', 'li']

then this gives me only the content within specified  tag:

soup_each_html = BeautifulSoup(particular_page_content, "html.parser")
inner_content = soup_each_html.find("article", "container")

let's say that this is the result:

this is headline 1

this is paragraph

this is headline 2

  this won't be shown bcs 'a' tag is not in the array

then I have method which is responsible for writing a line to the file.md file if a tag from the array exists in the content

with open("file.md", 'a+') as f:
    for tag in list_of_tags_you_want_to_scrape:
        inner_content_tag = inner_content.find_all(tag)

        for x in inner_content_tag:
            f.write(str(x))
            f.write("\n")

and it does. But the problem is, that it goes through the array (for each) and it will save all
 first, all
 on a second place, etc. And that's because that is the order specified in list_of_tags_you_want_to_scrape array.

this would be the result:

this is headline 1

this is headline 2

this is paragraph

so I would like to have them in the right order like the original HTML has. After the first
 should be
 element.

That means that I would probably need to do for each loop also with inner_content and check if each line from this inner_content is equals to at least one of the tags from the array. If yes then save and then move to another line. I tried to do it and made for each for inner_content to get line by line but it gave me an error and I am not sure if it is correct way how to do it. (First day using BeautifulSoup module)

Any tips or advices how to modify my method to achieve this please? thank you!

Body:
To maintain the original order of the html input, you can use recursion to loop over the soup.contents attribute:

from bs4 import BeautifulSoup as soup
def parse(content, to_scrape = ['h1', 'h2', 'h3', 'p', 'li']):
   if content.name in to_scrape:
      yield content
   for i in getattr(content, 'contents', []):
      yield from parse(i)

Example:

html = """
<html>
  <body>
      <h1>My website</h1>
      <p>This is my first site</p>
      <h2>See a listing of my interests below</h2>
      <ul>
         <li>programming</li>
         <li>math</li>
         <li>physics</li>
      </ul>
      <h3>Thanks for visiting!</h3>
  </body>
</html>
"""

result = list(parse(soup(html, 'html.parser')))

Output:

[<h1>My website</h1>, <p>This is my first site</p>, <h2>See a listing of my interests below</h2>, <li>programming</li>, <li>math</li>, <li>physics</li>, <h3>Thanks for visiting!</h3>]

As you can see, the original order of the html is maintained, and can now be written to the file:

with open('file.md', 'w') as f:
   f.write('\n'.join(map(str, result)))

Each bs4 object contains a name and contents attribute, among others. The name attribute is the tag name itself, while the contents attribute stores all the child HTML. parse uses a generator to first check if the passed bs4 object has a tag that belongs to the to_scrape list and if so, yields that value. Lastly, parse iterates over the contents of content, and calls itself on each element.


问:
Problem with random string, Error: 'variable' is not captured
I am trying to generate random string based on given alphabet.
If I define alphabet in string random_string then it works, but if I want to modify alphabet in main and then send it to function it give's Error: 'alphabet' is not captured.

```<code>string random_string( size_t length, string alphabet)
{
    auto randchar = []() -> char
    {
        const char charset[] = alphabet;
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    string str(length,0);
    generate_n( str.begin(), length, randchar );
    return str;
}
</code>```

In main:

```<code>string alphabet="ABCDE";
string txt= random_string(150, alphabet);
</code>```

Original Code which works:

```<code>string random_string( size_t length)
{
    auto randchar = []() -> char
    {
        const char charset[] = "ABCDE";
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    string str(length,0);
    generate_n( str.begin(), length, randchar );
    return str;
}
</code>```

答:
Your code could be fixed this way:

1) To avoid 'Error: 'alphabet' is not captured.' you should actually capture string alphabet into your lambda function: auto randchar = [&alphabet]() -> char { ... }. More about lambdas and capturing here;

2) Your don't need auxiliary buffer charset. If you have already had a reference to string, just get a random symbol from it;

3) Also I added const qualifier to string reference, because it's logically constness.

Here the fixed variant is:

```<code>string random_string( size_t length, const string &alphabet)
{
  auto randchar = [&alphabet]() -> char
    {
        const size_t max_index = (alphabet.size() - 1);
        return alphabet[ rand() % max_index ];
    };
    string str(length,0);
    generate_n( str.begin(), length, randchar );
    return str;
}
</code>```

Body:
I am trying to generate random string based on given alphabet.
If I define alphabet in string random_string then it works, but if I want to modify alphabet in main and then send it to function it give's Error: 'alphabet' is not captured.

string random_string( size_t length, string alphabet)
{
    auto randchar = []() -> char
    {
        const char charset[] = alphabet;
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    string str(length,0);
    generate_n( str.begin(), length, randchar );
    return str;
}

In main:

string alphabet="ABCDE";
string txt= random_string(150, alphabet);

Original Code which works:

string random_string( size_t length)
{
    auto randchar = []() -> char
    {
        const char charset[] = "ABCDE";
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    string str(length,0);
    generate_n( str.begin(), length, randchar );
    return str;
}

Body:
Your code could be fixed this way:

1) To avoid 'Error: 'alphabet' is not captured.' you should actually capture string alphabet into your lambda function: auto randchar = [&alphabet]() -> char { ... }. More about lambdas and capturing here;

2) Your don't need auxiliary buffer charset. If you have already had a reference to string, just get a random symbol from it;

3) Also I added const qualifier to string reference, because it's logically constness.

Here the fixed variant is:

string random_string( size_t length, const string &alphabet)
{
  auto randchar = [&alphabet]() -> char
    {
        const size_t max_index = (alphabet.size() - 1);
        return alphabet[ rand() % max_index ];
    };
    string str(length,0);
    generate_n( str.begin(), length, randchar );
    return str;
}


问:
mysql rand with condition
Could someone help me out with the correct syntax for this query please.

I have, table1:

```<code>id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)
</code>```

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

答:
```<code>SELECT `id`, `name` FROM `table1`
WHERE `on` = 1
ORDER BY RAND()
LIMIT 0,10
</code>```

Use backticks to delimit field names. In this case you actually have to in the WHERE condition, because "ON" is a keyword.

Title: mysql rand with condition

Body:
Could someone help me out with the correct syntax for this query please.

I have, table1:

id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

Body:
SELECT `id`, `name` FROM `table1`
WHERE `on` = 1
ORDER BY RAND()
LIMIT 0,10

Use backticks to delimit field names. In this case you actually have to in the WHERE condition, because "ON" is a keyword.


问:
Azure Cloud Shell Trouble running ps1 Scripts
In our Azure Cloud Shell, Powershell mode we can't run ps1 files. Although we are doing the same asin the MS Doc.
Any Suggestions, what am I doing wrong.</p>

```<code>    PS Azure:\> dir

    Directory: Azure:/Shared PAAS – Test/StorageAccounts/tstoweuyptobi/Files/azureshellfiles/goal0402preprod/powershell

Mode Name
---- ----
.    Build_goal.ps1
.    Test goal_Files.ps1
.    test.ps1

Azure:/Shared PAAS – Test/StorageAccounts/tstoweuyptobi/Files/azureshellfiles/goal0402preprod/powershell
PS Azure:\> ./test.ps1
./test.ps1 : The term './test.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ ./test.ps1
+ ~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (./test.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Azure:/Shared PAAS – Test/StorageAccounts/tstoweuyptobi/Files/azureshellfiles/goal0402preprod/powershell
PS Azure:\>
</code>```

答: The default directory for Cloud Shell does not seem to allow script running.  Copy the script to "$HOME\clouddrive", change to that dir, then run it from there.</p>

Body:
In our Azure Cloud Shell, Powershell mode we can't run ps1 files. Although we are doing the same asin the MS Doc.
Any Suggestions, what am I doing wrong.

    PS Azure:\> dir

    Directory: Azure:/Shared PAAS – Test/StorageAccounts/tstoweuyptobi/Files/azureshellfiles/goal0402preprod/powershell

Mode Name
---- ----
.    Build_goal.ps1
.    Test goal_Files.ps1
.    test.ps1

Azure:/Shared PAAS – Test/StorageAccounts/tstoweuyptobi/Files/azureshellfiles/goal0402preprod/powershell
PS Azure:\> ./test.ps1
./test.ps1 : The term './test.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ ./test.ps1
+ ~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (./test.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Azure:/Shared PAAS – Test/StorageAccounts/tstoweuyptobi/Files/azureshellfiles/goal0402preprod/powershell
PS Azure:\>


问:
Shows an error when using the Gate facade
When writing privileges and rights of a user shows error: 403
Forbidden

Controller code

```<code>class IndexController extends AdminController
{
    public function __construct(){

        parent::__construct();

        if (Gate::denies('VIEW_ADMIN')) {
            abort(403);
        }

        $this->template = env('THEME').'.admin.index';
 }
</code>```

AuthServiceProvider code

```<code>public function boot()
{
    $this->registerPolicies();

   Gate::define('VIEW_ADMIN', function($user){
        return $user->canDo('VIEW_ADMIN');
    });

    //
}
</code>```

Model User code

The User model is associated with the Roles model, and the Roles model is associated with the Permission model.

```<code>public function canDo($permission, $require = FALSE){

    if (is_array($permission)) {
        dump($permission);
    }
    else{
        foreach ($this->roles as $role) {
           foreach ($this->permissions as $permission) {
               if (str_is($permission,$permission->name)) {
                   return true;
               }
           }
        }
    }
}
</code>```

答:
You rewrite input $permission on line foreach ($this->permissions as $permission) { so your if (str_is($permission,$permission->name)) is always FALSE

because

```<code>str_is(array(), 'VIEW_ADMIN') === FALSE
</code>```

You should do this

```<code>public function canDo($permission, $require = FALSE){

    if (is_array($permission)) {
        dump($permission);
    }
    else{
        foreach ($this->roles as $role) {
           foreach ($this->permissions as $permissionObject) {
               if (str_is($permission,$permissionObject->name)) {
                   return true;
               }
           }
        }
    }
}
</code>```

Also you should add return FALSE because return type is boolean in this case.

Body:
When writing privileges and rights of a user shows error: 403
Forbidden

Controller code

class IndexController extends AdminController
{
    public function __construct(){

        parent::__construct();

        if (Gate::denies('VIEW_ADMIN')) {
            abort(403);
        }

        $this->template = env('THEME').'.admin.index';
 }

AuthServiceProvider code

public function boot()
{
    $this->registerPolicies();

   Gate::define('VIEW_ADMIN', function($user){
        return $user->canDo('VIEW_ADMIN');
    });

    //
}

Model User code

The User model is associated with the Roles model, and the Roles model is associated with the Permission model.

public function canDo($permission, $require = FALSE){

    if (is_array($permission)) {
        dump($permission);
    }
    else{
        foreach ($this->roles as $role) {
           foreach ($this->permissions as $permission) {
               if (str_is($permission,$permission->name)) {
                   return true;
               }
           }
        }
    }
}

Body:
You rewrite input $permission on line foreach ($this->permissions as $permission) { so your if (str_is($permission,$permission->name)) is always FALSE

because

str_is(array(), 'VIEW_ADMIN') === FALSE

You should do this

public function canDo($permission, $require = FALSE){

    if (is_array($permission)) {
        dump($permission);
    }
    else{
        foreach ($this->roles as $role) {
           foreach ($this->permissions as $permissionObject) {
               if (str_is($permission,$permissionObject->name)) {
                   return true;
               }
           }
        }
    }
}

Also you should add return FALSE because return type is boolean in this case.


问:
Why am i getting a class cast exception when adding a button in android studio?
I'm on Android Studio 3.4, and using Material Design.
When I add a button to the layout i'm getting a java.lang.ClassCastException@11378fc8 and i can't use anymore the layout editor until I remove the button.

I have already tried to "invalidate/restart", to rebuild, to clean and build.

This is my tree structure :
Tree structure

Build.Gradle :

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "fr.aurelien.test_dessin_android"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'com.google.code.gson:gson:2.8.5'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
</code>```

Class cast exception :

```<code>java.lang.IllegalArgumentException: java.lang.ClassCastException@126d0c4
    at sun.reflect.GeneratedMethodAccessor1380.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at android.animation.PropertyValuesHolder_Delegate.callMethod(PropertyValuesHolder_Delegate.java:108)
    at android.animation.PropertyValuesHolder_Delegate.nCallFloatMethod(PropertyValuesHolder_Delegate.java:143)
    at android.animation.PropertyValuesHolder.nCallFloatMethod(PropertyValuesHolder.java)
    at android.animation.PropertyValuesHolder.access$400(PropertyValuesHolder.java:38)
    at android.animation.PropertyValuesHolder$FloatPropertyValuesHolder.setAnimatedValue(PropertyValuesHolder.java:1387)
    at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:990)
    at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:674)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1071)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1088)
    at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
    at android.animation.ValueAnimator.startWithoutPulsing(ValueAnimator.java:1081)
    at android.animation.AnimatorSet.handleAnimationEvents(AnimatorSet.java:1142)
    at android.animation.AnimatorSet.doAnimationFrame(AnimatorSet.java:1046)
    at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
    at android.animation.AnimationHandler.access$100(AnimationHandler.java:37)
    at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:947)
    at android.view.Choreographer.doCallbacks(Choreographer.java:761)
    at android.view.Choreographer_Delegate.doFrame(Choreographer_Delegate.java:66)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:563)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:425)
    at com.android.layoutlib.bridge.BridgeRenderSession.render(BridgeRenderSession.java:120)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:151)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:133)
    at com.android.tools.idea.rendering.RenderTask.lambda$null$8(RenderTask.java:755)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

MainActivity :

```<code>package fr.aurelien.test_dessin_android;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, new SimpleFragment());
        fragmentTransaction.commit();
    }
}
</code>```

Fragment class :

```<code>package fr.aurelien.test_dessin_android;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SimpleFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_layout, container, false);
        return retView;
    }
}
</code>```

Manifest.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.aurelien.test_dessin_android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.default">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

XML code :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="55dp"
        android:layout_marginTop="31dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="189dp" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答: It's a bug in Android Studio. You can track it here, it's apparently fixed for 3.5.2 https://issuetracker.google.com/issues/132316448</p>

Body:
I'm on Android Studio 3.4, and using Material Design.
When I add a button to the layout i'm getting a java.lang.ClassCastException@11378fc8 and i can't use anymore the layout editor until I remove the button.

I have already tried to "invalidate/restart", to rebuild, to clean and build.

This is my tree structure :
Tree structure

Build.Gradle :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "fr.aurelien.test_dessin_android"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'com.google.code.gson:gson:2.8.5'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

Class cast exception :

java.lang.IllegalArgumentException: java.lang.ClassCastException@126d0c4
    at sun.reflect.GeneratedMethodAccessor1380.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at android.animation.PropertyValuesHolder_Delegate.callMethod(PropertyValuesHolder_Delegate.java:108)
    at android.animation.PropertyValuesHolder_Delegate.nCallFloatMethod(PropertyValuesHolder_Delegate.java:143)
    at android.animation.PropertyValuesHolder.nCallFloatMethod(PropertyValuesHolder.java)
    at android.animation.PropertyValuesHolder.access$400(PropertyValuesHolder.java:38)
    at android.animation.PropertyValuesHolder$FloatPropertyValuesHolder.setAnimatedValue(PropertyValuesHolder.java:1387)
    at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:990)
    at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:674)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1071)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1088)
    at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
    at android.animation.ValueAnimator.startWithoutPulsing(ValueAnimator.java:1081)
    at android.animation.AnimatorSet.handleAnimationEvents(AnimatorSet.java:1142)
    at android.animation.AnimatorSet.doAnimationFrame(AnimatorSet.java:1046)
    at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
    at android.animation.AnimationHandler.access$100(AnimationHandler.java:37)
    at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:947)
    at android.view.Choreographer.doCallbacks(Choreographer.java:761)
    at android.view.Choreographer_Delegate.doFrame(Choreographer_Delegate.java:66)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:563)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:425)
    at com.android.layoutlib.bridge.BridgeRenderSession.render(BridgeRenderSession.java:120)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:151)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:133)
    at com.android.tools.idea.rendering.RenderTask.lambda$null$8(RenderTask.java:755)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

MainActivity :

package fr.aurelien.test_dessin_android;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, new SimpleFragment());
        fragmentTransaction.commit();
    }
}

Fragment class :

package fr.aurelien.test_dessin_android;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SimpleFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_layout, container, false);
        return retView;
    }
}

Manifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.aurelien.test_dessin_android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.default">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

XML code :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="55dp"
        android:layout_marginTop="31dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="189dp" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Download optimized image - Google Insight
After google insight analysis, there was an option to download optimised contents (CSS, JS, Images). Now the option is not visible anywhere in the new design. Was it removed? </p>

<p>Could some one give a screenshot if it's available. </p>

答:
Not sure if this is the case, but GPSI sometimes offers nothing to download,  if the analysis result is satisfactory.

Also GPSI is sometimes unhappy with its own files (images) it offers for download and re-optimizes them again, after you use them and re-test.

Body:
After google insight analysis, there was an option to download optimised contents (CSS, JS, Images). Now the option is not visible anywhere in the new design. Was it removed?

Could some one give a screenshot if it's available.


问:
Java: how to convert HashMap<String, Object> to array
I need to convert a HashMap<String, Object> to an array; could anyone show me how it's done?

答:
If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

```<code>map.entrySet()
    .stream()
    .map(e -> new Object[]{e.getKey(), e.getValue()})
    .toArray(Object[][]::new);
</code>```

If your Objects are Strings and you need a String[][], try:

```<code>map.entrySet()
    .stream()
    .map(e -> new String[]{e.getKey(), e.getValue().toString()})
    .toArray(String[][]::new);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

map.entrySet()
    .stream()
    .map(e -> new Object[]{e.getKey(), e.getValue()})
    .toArray(Object[][]::new);

If your Objects are Strings and you need a String[][], try:

map.entrySet()
    .stream()
    .map(e -> new String[]{e.getKey(), e.getValue().toString()})
    .toArray(String[][]::new);


问:
Cannot set user email, removeLoginEmails, or addLoginEmails with setAccountInfo
I've tried the following:

Sending

```<code>profile: {
  email: 'new.email@domain.com',
}
</code>```

to accounts.setAccountInfo,

Sending

```<code>addLoginEmails: 'new.email@domain.com'
</code>```

Followed by

```<code>removeLoginEmails: 'old.email@domain.com'
</code>```

to accounts.setAccountInfo.
Nothing seems to work. I've also tried toggling conflictHandling: saveProfileAndFail on and off.

The odd thing is that I can freely edit the user's settings in the Gigya console, just not using the REST APIs. Has anyone else experienced this? Any tips? I tried dumping the logs from the network tab when I was using the Gigya console and the payload of their request is almost identical to mine.

Thanks

答:
Thanks for the comment, @Levi.

It turns out that there's a bit of an undocumented requirement here:

I was using exclusively emails which contained a + symbol, I was frequently generating new emails to test some business logic, and it turns out that if the + symbol is not URI Encoded (to %2B), the calls to addLoginEmails, and setting profile.email would fail, and the removeLoginEmails would simply do nothing.

My new payload looks like this:

```<code>profile: {
  email: 'new.email%2Btest@domain.com',
},
addLoginEmails: 'new.email%2Btest@domain.com',
removeLoginEmails: 'old.email%2Btest@domain.com',
...
</code>```

and everything functions as expected. The emails are also reflected in the Identity Access area of the console, and my request returns 200 OK as expected.

It seems a bit strange that this wasn't documented and I'm waiting for the next unexpected character error.

Body:
I've tried the following:

Sending

profile: {
  email: 'new.email@domain.com',
}

to accounts.setAccountInfo,

Sending

addLoginEmails: 'new.email@domain.com'

Followed by

removeLoginEmails: 'old.email@domain.com'

to accounts.setAccountInfo.
Nothing seems to work. I've also tried toggling conflictHandling: saveProfileAndFail on and off.

The odd thing is that I can freely edit the user's settings in the Gigya console, just not using the REST APIs. Has anyone else experienced this? Any tips? I tried dumping the logs from the network tab when I was using the Gigya console and the payload of their request is almost identical to mine.

Thanks

Body:
Thanks for the comment, @Levi.

It turns out that there's a bit of an undocumented requirement here:

I was using exclusively emails which contained a + symbol, I was frequently generating new emails to test some business logic, and it turns out that if the + symbol is not URI Encoded (to %2B), the calls to addLoginEmails, and setting profile.email would fail, and the removeLoginEmails would simply do nothing.

My new payload looks like this:

profile: {
  email: 'new.email%2Btest@domain.com',
},
addLoginEmails: 'new.email%2Btest@domain.com',
removeLoginEmails: 'old.email%2Btest@domain.com',
...

and everything functions as expected. The emails are also reflected in the Identity Access area of the console, and my request returns 200 OK as expected.

It seems a bit strange that this wasn't documented and I'm waiting for the next unexpected character error.


问:
How to customize a serialization
I'm newbie with graphql and spqr. I would like to serialize my dates with personal format. How I can do it?</p>

答:
The best answer I'd offer is: don't! SPQR serializes all temporal scalars as ISO 8601 strings in UTC zone for a reason. It is the most portable format, that any client can easily parse and understand, and any conversion and display logic is better left to the client itself.

If this is for some reason impossible (e.g. backwards compatibility with a legacy client), your best bet is providing your own scalar implementations. In the future there might be a feature to avoid this, but currently you have to implement your own scalars and a TypeMapper that will map the desired Java types to those scalars. See the existing ScalarMapper for inspiration. Once you have the mapper, register it via generator.withTypeMappers.

Title: How to customize a serialization


问:
Regex on validates_format_of
I have a field in a form, and I need it to be registered only if its format equals one of the two regex I am using.

I have tried to use methods, the helper structure validates_format_of with Proc.new, but may not be using the correct syntax or the correct data type

```<code>private def format_field
  errors.add(
    :field, "The field does not have a valid format."
  )unless[
    /[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}/,
    /[0-9]{2}\.?[0-9]{3}\.?[0-9]{3}\/?[0-9]{4}\-?[0-9]{2}/
  ].include?(field.format)
end
</code>```

答:
A simple approach to this is the following:</p>

```<code>FORMAT_REGEXES = [
  /[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}/,
  /[0-9]{2}\.?[0-9]{3}\.?[0-9]{3}\/?[0-9]{4}\-?[0-9]{2}/
].freeze

def validate_format
  return unless FORMAT_REGEXES.find { |regex| field.format =~ regex }
  errors.add(:field, :invalid, message: 'The field does not have a valid format')
end
</code>```

Title: Regex on validates_format_of

Body:
I have a field in a form, and I need it to be registered only if its format equals one of the two regex I am using.

I have tried to use methods, the helper structure validates_format_of with Proc.new, but may not be using the correct syntax or the correct data type

private def format_field
  errors.add(
    :field, "The field does not have a valid format."
  )unless[
    /[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}/,
    /[0-9]{2}\.?[0-9]{3}\.?[0-9]{3}\/?[0-9]{4}\-?[0-9]{2}/
  ].include?(field.format)
end

Body:
A simple approach to this is the following:

FORMAT_REGEXES = [
  /[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}/,
  /[0-9]{2}\.?[0-9]{3}\.?[0-9]{3}\/?[0-9]{4}\-?[0-9]{2}/
].freeze

def validate_format
  return unless FORMAT_REGEXES.find { |regex| field.format =~ regex }
  errors.add(:field, :invalid, message: 'The field does not have a valid format')
end


问:
Program that displays all multiples of 7 between 1 and 100 C++
How to write this program with switch condition statement instead of if?

```<code>#include <iostream>

using namespace std;
int main() {
  int i;
  for (i = 1; i <= 100; i++) {
    if ((i % 7 == 0) && (i > 0)) {
      cout << i << endl;
    }
  }

  return 0;
}
</code>```

答:
It is possible to replace the if statement with switch/case statement for your case. But I think you have some misunderstanding about where to use if and where switch/case statements. I will suggest you use this statement as they are used in real life.

Use if, if you're going to check the condition. For example:

if (a > b){...} or if (a == 7){...} or if (functionReturnsTrue()){...}

The switch/case statement could be used when you have a set of conditions and the logic is different for each element in that set. For example:

```<code>enum HttpMethod {
  GET,
  POST,
  PUT,
  DELETE,
};

...

void handleHttpRequest(HttpRequest req)
{
  ...
  switch(req.getHttpMethod())
  {
    case GET: handleGETRequest(req); break;
    case POST: handlePOSTRequest(req); break;
    case PUT: handlePUTRequest(req); break;
    case DELETE: handleDELETERequest(req); break;
    default: throw InvalidHttpMethod(); // in case when noone corresponds to the variable
  }
}
</code>```

Of course, you can write the same using if statement, but switch/case statement also have some compilation effects. When you switch the variable of enum type, you might get a compiler warning at least, if you dont check your variable for all possible flows.

Body:
How to write this program with switch condition statement instead of if?

#include <iostream>

using namespace std;
int main() {
  int i;
  for (i = 1; i <= 100; i++) {
    if ((i % 7 == 0) && (i > 0)) {
      cout << i << endl;
    }
  }

  return 0;
}

Body:
It is possible to replace the if statement with switch/case statement for your case. But I think you have some misunderstanding about where to use if and where switch/case statements. I will suggest you use this statement as they are used in real life.

Use if, if you're going to check the condition. For example:

if (a > b){...} or if (a == 7){...} or if (functionReturnsTrue()){...}

The switch/case statement could be used when you have a set of conditions and the logic is different for each element in that set. For example:

enum HttpMethod {
  GET,
  POST,
  PUT,
  DELETE,
};

...

void handleHttpRequest(HttpRequest req)
{
  ...
  switch(req.getHttpMethod())
  {
    case GET: handleGETRequest(req); break;
    case POST: handlePOSTRequest(req); break;
    case PUT: handlePUTRequest(req); break;
    case DELETE: handleDELETERequest(req); break;
    default: throw InvalidHttpMethod(); // in case when noone corresponds to the variable
  }
}

Of course, you can write the same using if statement, but switch/case statement also have some compilation effects. When you switch the variable of enum type, you might get a compiler warning at least, if you dont check your variable for all possible flows.


问:
Show true python source instead of pycharm stubs for an extention module
When navigating python code with third party libraries - opencv in this case - why does pycharm display its stubs instead of the actual source?

Consider when clicking on the following imshow() method

```<code>cv2.imshow("Faces found", image)
</code>```

Then instead of navigating to the opencv sources - or at least to a decompiled equivalent-  we see the following:

This compares poorly to the results on intellij for jvm languages such as java and scala - in which we have the option to Attach sources or at the least to show decompiled code.  Are there any better options for python than this?

答:
Python extensions are written in C/C++ (so there is no "python source" to speak of) which, unlike Java, can't be easily decompiled.

To debug them, you'll need to do that like any other binary module, using a native debugger (that would use C-level debug information if present in the module to link machine code to the sources). PyCharm doesn't have a native debugger, this feature is reserved for JetBrains' paid product, CLion.

Body:
When navigating python code with third party libraries - opencv in this case - why does pycharm display its stubs instead of the actual source?

Consider when clicking on the following imshow() method

cv2.imshow("Faces found", image)

Then instead of navigating to the opencv sources - or at least to a decompiled equivalent-  we see the following:

This compares poorly to the results on intellij for jvm languages such as java and scala - in which we have the option to Attach sources or at the least to show decompiled code.  Are there any better options for python than this?