问:
Firestore returns 'instance of querysnapshot' even if the collection does not exists
```<code>StreamBuilder(
   stream: Firestore.instance.collection('aaaaaaaaaaaaaaaa').snapshots(),
    builder: ( context , snap){

      if(snap.data == null){
         print('A');
      }
      if(snap.data != null){
        print(snap.data);
        print('B');
      }
</code>```

Obviously collection ('aaaaaaaaaaaaaa') does not even exists then why it is not returning null?

答:
Querying a non-existing (or empty) collection is not an error. So when there are no results, Firestore gives you an empty QuerySnapshot, instead of an error.

To detect if there were any results, check if the QuerySnapshot has any documents (FlutterFire doesn't seem to wrap the native QuerySnapshot.isEmpty() method.

Body:
StreamBuilder(
   stream: Firestore.instance.collection('aaaaaaaaaaaaaaaa').snapshots(),
    builder: ( context , snap){

      if(snap.data == null){
         print('A');
      }
      if(snap.data != null){
        print(snap.data);
        print('B');
      }

Obviously collection ('aaaaaaaaaaaaaa') does not even exists then why it is not returning null?


来源: stackexchange

问:
Javascript load background-image asynchrously
Is it possible to load a background-image asynchronously?

I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.

EDIT

I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).

The host is free and slow at the moment, so the background image takes some time to load.

The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.

If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)

Here is the method to set my positions:

```<code>function setPositions(){
    var oH = $('#overlay-header');
    var overlayHeaderOffset = oH.offset();
    var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
    if (overlayRightWidth >= 0) {
        $('#overlay-right').width(overlayRightWidth);
    } else {
        $('#overlay-right').width(0);
    }
    var lW =  $('#loader-wrapper');
    lW.offset({
        left: (overlayHeaderOffset.left + oH.width() - lW.width())
    });
}
</code>```

The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);

any ideas?

答:
I like to use CSS to fill the background with a color for page load.

After DOM ready event, I use jQuery to modify the CSS and add a background image.  That way, the image isn't loaded until after page loads.  Not sure about async, but this method gives the user a decent experience.

Example: http://it.highpoint.edu/

The right side navigation links have a background image.  The page initializes with a background color.  It is replaced with a background image after page load, via jQuery.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to load a background-image asynchronously?

I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.

EDIT

I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).

The host is free and slow at the moment, so the background image takes some time to load.

The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.

If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)

Here is the method to set my positions:

function setPositions(){
    var oH = $('#overlay-header');
    var overlayHeaderOffset = oH.offset();
    var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
    if (overlayRightWidth >= 0) {
        $('#overlay-right').width(overlayRightWidth);
    } else {
        $('#overlay-right').width(0);
    }
    var lW =  $('#loader-wrapper');
    lW.offset({
        left: (overlayHeaderOffset.left + oH.width() - lW.width())
    });
}

The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);

any ideas?

ContentLicense: CC BY-SA 3.0


问:
Setting Password Never Expires for new AD user using System.DirectoryServices.DirectoryEntry (ADLDS, ADAM, Active Directory Application Mode)
I've seen this question and tried with both "userPrincipalName" and "userFlags" and I'm receiving "The specified directory service attribute or value does not exist" in both cases.

I am able to set the attribute with the following in Powershell

```<code>Get-ADUser -Filter 'cn -like "*username*"' -Server <serveraddrress> -SearchBase "<searchbase>" | Set-ADUser -PasswordNeverExpires:$True
</code>```

My C# code is as follows, it works fine if I remove the line setting userAccountControl, but it creates the user with Password Never Expires = FALSE

```<code>using (var dirEntry = entry.Children.Add("CN=" + username, "user"))
{
    dirEntry.Properties["userPrincipalName"].Value = string.Format("{0}@principal", username);
    dirEntry.CommitChanges();
    dirEntry.Options.PasswordPort = port;
    dirEntry.Options.PasswordEncoding = PasswordEncodingMethod.PasswordEncodingClear;
    dirEntry.Invoke("SetPassword", password);

    if (!string.IsNullOrEmpty(email))
         dirEntry.Properties["mail"].Value = email;
    dirEntry.Properties["msDS-UserAccountDisabled"].Value = "FALSE";

    //this doesn't work with both "userAccountControl" and "userFlags"
    dirEntry.Properties["userAccountControl"].Value = (int)(dirEntry.Properties["userAccountControl"].Value ?? 0) | 0x10000;

    dirEntry.CommitChanges();
}
</code>```

答:
Are you using Active Directory Application Mode (ADAM)? This line makes me think you are:

```<code>dirEntry.Properties["msDS-UserAccountDisabled"].Value = "FALSE";
</code>```

That attribute doesn't exist in normal Active Directory. So if that's working for you, then you are using ADAM.

If you are using ADAM, then use the msDS-UserDontExpirePassword attribute to make the password not expire:

```<code>dirEntry.Properties["msDS-UserDontExpirePassword"].Value = true;
</code>```

If you are not using ADAM, then the "msDS-UserAccountDisabled doesn't exist and you shouldn't be using that. Instead, use userAccountControl to set both.

Since you just created the account, you don't need to worry about what the value already was, you can just set it to a specific value. Assuming you want it enabled with the "don't expire password" flag, then you can use this:

```<code>//NORMAL_ACCOUNT | DONT_EXPIRE_PASSWORD
dirEntry.Properties["userAccountControl"].Value = 0x0200 | 0x10000;
</code>```

You can leave each value separated like that, or just use the resulting decimal value of 66048.

Body:
I've seen this question and tried with both "userPrincipalName" and "userFlags" and I'm receiving "The specified directory service attribute or value does not exist" in both cases.

I am able to set the attribute with the following in Powershell

Get-ADUser -Filter 'cn -like "*username*"' -Server <serveraddrress> -SearchBase "<searchbase>" | Set-ADUser -PasswordNeverExpires:$True

My C# code is as follows, it works fine if I remove the line setting userAccountControl, but it creates the user with Password Never Expires = FALSE

using (var dirEntry = entry.Children.Add("CN=" + username, "user"))
{
    dirEntry.Properties["userPrincipalName"].Value = string.Format("{0}@principal", username);
    dirEntry.CommitChanges();
    dirEntry.Options.PasswordPort = port;
    dirEntry.Options.PasswordEncoding = PasswordEncodingMethod.PasswordEncodingClear;
    dirEntry.Invoke("SetPassword", password);

    if (!string.IsNullOrEmpty(email))
         dirEntry.Properties["mail"].Value = email;
    dirEntry.Properties["msDS-UserAccountDisabled"].Value = "FALSE";

    //this doesn't work with both "userAccountControl" and "userFlags"
    dirEntry.Properties["userAccountControl"].Value = (int)(dirEntry.Properties["userAccountControl"].Value ?? 0) | 0x10000;

    dirEntry.CommitChanges();
}

Body:
Are you using Active Directory Application Mode (ADAM)? This line makes me think you are:

dirEntry.Properties["msDS-UserAccountDisabled"].Value = "FALSE";

That attribute doesn't exist in normal Active Directory. So if that's working for you, then you are using ADAM.

If you are using ADAM, then use the msDS-UserDontExpirePassword attribute to make the password not expire:

dirEntry.Properties["msDS-UserDontExpirePassword"].Value = true;

If you are not using ADAM, then the "msDS-UserAccountDisabled doesn't exist and you shouldn't be using that. Instead, use userAccountControl to set both.

Since you just created the account, you don't need to worry about what the value already was, you can just set it to a specific value. Assuming you want it enabled with the "don't expire password" flag, then you can use this:

//NORMAL_ACCOUNT | DONT_EXPIRE_PASSWORD
dirEntry.Properties["userAccountControl"].Value = 0x0200 | 0x10000;

You can leave each value separated like that, or just use the resulting decimal value of 66048.


问:
Mongoose Node.JS Error Cannot create field
Im trying to update an element inside my collection. Its a two dimensional array. I tried directly modifiying it, i tried to update the whole array structure and tried to use the set method. Nothing did give me success.

This is my model:

```<code>var nestedInside = mongoose.Schema({
    x: Number,
    y: Number,
    block: {
        type: Boolean,
        default: false
    },
    answer: String,
    question: String,
    questionnr: Number,
    vertical: Boolean,
    questionnr2: Number,
    question2: String,
    vertical2: Boolean,
    tmp: String,
    question_vertical: String,
    question_horizontal: String,
    question_num: Number
})

var schema = mongoose.Schema({
    grid: [[nestedInside]]
})

var create = mongoose.model('puzzles', schema);
</code>```

This is my error when i do the following code:

```<code>puzzle.findOne({_id:req.params.id}).exec(function(err,data) {
   var grid = data.grid;
   grid[req.body.xo].id(req.body._id)["question_vertical"] = req.body.question_vertical
   data.save();
</code>```

```<code>errorMongoError: Cannot create field 'question_vertical' in element {0: [ { block: false, _id: ObjectId('5dec2f1dde95855cf9130f50')...
</code>```

When i try to replace the whole array it says: Cast to Array failed for value

Anyone any idea? I'm out of options which i know.

sample data:

```<code>
   "_id":{
      "$oid":"5da1097076a05f2c50f34001"
   },
   "free":false,
   "package":{
      "$numberInt":"6"
   },
   "grid":[
      [
         {
            "block":false,
            "_id":{
               "$oid":"5da1097076a05f2c50f34008"
            },
            "x":{
               "$numberInt":"1"
            },
            "y":{
               "$numberInt":"1"
            },
            "answer":"G",
            "question_num":{
               "$numberInt":"1"
            },
            "question_vertical":"Abk.: Grundgesetz",
            "question_horizontal":"kostenlos"
         },
    ....
       ]
    ],
    ....
</code>```

答: You said that you updated your array structure. Did you delete the old items from the database (or even better deleted the current database)? Otherwise this could lead to wrong document parsing (Mongoose - Redefining schema structure).</p>

Body:
Im trying to update an element inside my collection. Its a two dimensional array. I tried directly modifiying it, i tried to update the whole array structure and tried to use the set method. Nothing did give me success.

This is my model:

var nestedInside = mongoose.Schema({
    x: Number,
    y: Number,
    block: {
        type: Boolean,
        default: false
    },
    answer: String,
    question: String,
    questionnr: Number,
    vertical: Boolean,
    questionnr2: Number,
    question2: String,
    vertical2: Boolean,
    tmp: String,
    question_vertical: String,
    question_horizontal: String,
    question_num: Number
})

var schema = mongoose.Schema({
    grid: [[nestedInside]]
})

var create = mongoose.model('puzzles', schema);

This is my error when i do the following code:

puzzle.findOne({_id:req.params.id}).exec(function(err,data) {
   var grid = data.grid;
   grid[req.body.xo].id(req.body._id)["question_vertical"] = req.body.question_vertical
   data.save();

errorMongoError: Cannot create field 'question_vertical' in element {0: [ { block: false, _id: ObjectId('5dec2f1dde95855cf9130f50')...

When i try to replace the whole array it says: Cast to Array failed for value

Anyone any idea? I'm out of options which i know.

sample data:

   "_id":{
      "$oid":"5da1097076a05f2c50f34001"
   },
   "free":false,
   "package":{
      "$numberInt":"6"
   },
   "grid":[
      [
         {
            "block":false,
            "_id":{
               "$oid":"5da1097076a05f2c50f34008"
            },
            "x":{
               "$numberInt":"1"
            },
            "y":{
               "$numberInt":"1"
            },
            "answer":"G",
            "question_num":{
               "$numberInt":"1"
            },
            "question_vertical":"Abk.: Grundgesetz",
            "question_horizontal":"kostenlos"
         },
    ....
       ]
    ],
    ....


问:
What does requestValidationMode="2.0" actually do?

I'm trying to solve a "A potentially dangerous Request.Form value was detected from the client" problem, and SO answers and  Scott Hanselman recommend setting

```<code><httpRuntime requestValidationMode="2.0" />
</code>```

in Web.config (along with adding an attribute to problematic Methods).

I realize this changes the validation mode to ASP.NET 2.0's, but what does that mean?

And also, does this change has any side effects I should be aware of?

Thanks.

答:
Take a look at ASP.NET Request Validation>

The request validation feature in ASP.NET provides a certain level of
  default protection against cross-site scripting (XSS) attacks. In
  previous versions of ASP.NET, request validation was enabled by
  default. However, it applied only to ASP.NET pages (.aspx files and
  their class files) and only when those pages were executing.

In ASP.NET 4, by default, request validation is enabled for all
  requests, because it is enabled before the BeginRequest phase of an
  HTTP request. As a result, request validation applies to requests for
  all ASP.NET resources, not just .aspx page requests. This includes
  requests such as Web service calls and custom HTTP handlers. Request
  validation is also active when custom HTTP modules are reading the
  contents of an HTTP request.

As a result, request validation errors might now occur for requests
  that previously did not trigger errors. To revert to the behavior of
  the ASP.NET 2.0 request validation feature, add the following setting
  in the Web.config file:

```<code><httpRuntime requestValidationMode="2.0" />
</code>```

However, we recommend that you analyze any request validation errors
  to determine whether existing handlers, modules, or other custom code
  accesses potentially unsafe HTTP inputs that could be XSS attack
  vectors.

Body:
I'm trying to solve a "A potentially dangerous Request.Form value was detected from the client" problem, and SO answers and  Scott Hanselman recommend setting

<httpRuntime requestValidationMode="2.0" />

in Web.config (along with adding an attribute to problematic Methods).

I realize this changes the validation mode to ASP.NET 2.0's, but what does that mean?

And also, does this change has any side effects I should be aware of?

Thanks.

Body:
Take a look at ASP.NET Request Validation>

The request validation feature in ASP.NET provides a certain level of
  default protection against cross-site scripting (XSS) attacks. In
  previous versions of ASP.NET, request validation was enabled by
  default. However, it applied only to ASP.NET pages (.aspx files and
  their class files) and only when those pages were executing.

In ASP.NET 4, by default, request validation is enabled for all
  requests, because it is enabled before the BeginRequest phase of an
  HTTP request. As a result, request validation applies to requests for
  all ASP.NET resources, not just .aspx page requests. This includes
  requests such as Web service calls and custom HTTP handlers. Request
  validation is also active when custom HTTP modules are reading the
  contents of an HTTP request.

As a result, request validation errors might now occur for requests
  that previously did not trigger errors. To revert to the behavior of
  the ASP.NET 2.0 request validation feature, add the following setting
  in the Web.config file:

<httpRuntime requestValidationMode="2.0" />

However, we recommend that you analyze any request validation errors
  to determine whether existing handlers, modules, or other custom code
  accesses potentially unsafe HTTP inputs that could be XSS attack
  vectors.


问:
How can I add custom margin in grid system and keep it responsive?
So I am trying to add 4 "cards" (non bootstrap) to my HTML, with space in between them, here is a picture on how it should look:

The issue is that well 1. It is no longer responsive after I changed "col" class to "col-6", here is how it looks right now:

And here is how it looks when I make my browser smaller:

The margin in between each "card" is
Horizontal - 464px
Vertical - 100px (from image to text)

I haven't really worked with the grid system in bootstrap before, read through the documentation and tried a bunch of different "col" values, but doesn't seem to work.

I also tried to just place the cards on the screen, then adding a div around the "images", saying "img_div:nth-child(1) ..." and the same on 3. But that didn't work either!

Here is my HTML code:

```<code><div class="container">
  <h1 class="home-title">XelTool</h1>
  <div class="row">
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar Prices</h2>
        <div class="img_div">
          <img
            class="home_img"
            src="/static/img/bazaar prices.png"
            alt="Bazaar Prices"
          />
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar Flipper</h2>
        <div class="img_div">
          <img
            class="home_img"
            src="/static/img/bazaar prices.png"
            alt="Bazaar Flipper"
          />
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar High Demand</h2>
        <div class="img_div">
          <img
            class="home_img"
            src="/static/img/bazaar prices.png"
            alt="Bazaar High Demand"
          />
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar NPC Re-Sell</h2>
        <div class="img_div">
          <img
            class="home_img"
            src="/static/img/bazaar prices.png"
            alt="Bazaar NPC Re-Sell"
          />
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Thanks!

答:
Everything is perfect, you just didn't give your image a css property of width 100%

  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

XelTool

Bazaar Prices

Bazaar Flipper

Bazaar High Demand

Bazaar NPC Re-Sell

```

Body:
So I am trying to add 4 "cards" (non bootstrap) to my HTML, with space in between them, here is a picture on how it should look:

The issue is that well 1. It is no longer responsive after I changed "col" class to "col-6", here is how it looks right now:

And here is how it looks when I make my browser smaller:

The margin in between each "card" is
Horizontal - 464px
Vertical - 100px (from image to text)

I haven't really worked with the grid system in bootstrap before, read through the documentation and tried a bunch of different "col" values, but doesn't seem to work.

I also tried to just place the cards on the screen, then adding a div around the "images", saying "img_div:nth-child(1) ..." and the same on 3. But that didn't work either!

Here is my HTML code:

XelTool

Bazaar Prices

Bazaar Flipper

Bazaar High Demand

Bazaar NPC Re-Sell

Thanks!

Body:
Everything is perfect, you just didn't give your image a css property of width 100%

  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<div class="container">
  <h1 class="home-title">XelTool</h1>
  <div class="row">
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar Prices</h2>
        <div class="img_div">
          <img class="home_img" src="https://images.unsplash.com/photo-1590594841715-70fe3b7c51ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Bazaar Prices" width="100%" />
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar Flipper</h2>
        <div class="img_div">
          <img class="home_img" src="https://images.unsplash.com/photo-1590594841715-70fe3b7c51ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Bazaar Flipper" width="100%" />
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar High Demand</h2>
        <div class="img_div">
          <img class="home_img" src="https://images.unsplash.com/photo-1590594841715-70fe3b7c51ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Bazaar High Demand" width="100%" />
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="home_card">
        <h2 class="card_title">Bazaar NPC Re-Sell</h2>
        <div class="img_div">
          <img class="home_img" src="https://images.unsplash.com/photo-1590594841715-70fe3b7c51ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Bazaar NPC Re-Sell" width="100%" />
        </div>
      </div>
    </div>
  </div>
</div>


问:
Replace 'A' to 1, 'B' to 2, in R dataframe column
We have a column of a dataframe with letters A to Z

```<code>df$Col1 <- c("B", "C", "Q", ... , "A")
</code>```

I want to change those letters to numbers 1-26.

Naturally I could just do the following 26 times, but it isn't efficient nor pretty.

```<code>df$Col1  <- gsub("A","1",df$Col1)
</code>```

What would be the best way to approach this problem?

答:
For fun:</p>

```<code>sapply(Col1, utf8ToInt, USE.NAMES = FALSE) - 64
[1]  2  3 17  1
</code>```

Body:
We have a column of a dataframe with letters A to Z

df$Col1 <- c("B", "C", "Q", ... , "A")

I want to change those letters to numbers 1-26.

Naturally I could just do the following 26 times, but it isn't efficient nor pretty.

df$Col1  <- gsub("A","1",df$Col1)

What would be the best way to approach this problem?

Body:
For fun:

sapply(Col1, utf8ToInt, USE.NAMES = FALSE) - 64
[1]  2  3 17  1


问:
Get a word after specific word using regexp_substr in sql oracle
I have tried

```<code>select regexp_substr ('sys: error: This is a message ''123:'' for column EMP_NB', '[[:alpha:]_]+',1,9) from dual
</code>```

I have column filled with this type of data.

```<code>sys: error: This is a message '123:' for column EMP_NB.
sys: error: This is a message '45346:' for column EM_NM.
sys: error: This is a message '78324f9:' for column DEPT_NO_VL.
</code>```

I need an output like below this using regexp_substr in Oracle SQL. The challenge is the length of string tend to change and I need to extract only the characters after the column word in string.

Expected outputs:

```<code>EMP_NB
EM_NM
DEPT_NO_VL
</code>```

答:
You may use

```<code>select regexp_substr ('sys: error: This is a message ''123:'' for column EMP_NB', 'column[[:space:]]*([[:alpha:]_]+)', 1, 1, NULL, 1) from dual
</code>```

Here,

column - matches column word

[[:space:]]* - 0  or more whitespace chars

([[:alpha:]_]+) - captures into Group 1 any one or more letters or underscores.

The value captured is returned only, since the last group ID argument is set to 1.

Body:
I have tried

select regexp_substr ('sys: error: This is a message ''123:'' for column EMP_NB', '[[:alpha:]_]+',1,9) from dual

I have column filled with this type of data.

sys: error: This is a message '123:' for column EMP_NB.
sys: error: This is a message '45346:' for column EM_NM.
sys: error: This is a message '78324f9:' for column DEPT_NO_VL.

I need an output like below this using regexp_substr in Oracle SQL. The challenge is the length of string tend to change and I need to extract only the characters after the column word in string.

Expected outputs:

EMP_NB
EM_NM
DEPT_NO_VL

Body:
You may use

select regexp_substr ('sys: error: This is a message ''123:'' for column EMP_NB', 'column[[:space:]]*([[:alpha:]_]+)', 1, 1, NULL, 1) from dual

Here,

column - matches column word

[[:space:]]* - 0  or more whitespace chars

([[:alpha:]_]+) - captures into Group 1 any one or more letters or underscores.

The value captured is returned only, since the last group ID argument is set to 1.


问:
I want to shorten this method, can you help me?
I want to write this method in a shorter way. Do you have any ideas? I didn´t get something which runs...</p>

```<code>public static AudioFile getInstance(String pathname) {
    String ending = null;
    int auxvar = pathname.lastIndexOf('.');

    if (auxvar<0) {
        throw new RuntimeException("Unknown suffix for AudioFile: \""+ pathname + "\"");
    }else {
        ending = pathname.substring(auxvar+1);
        ending = ending.toLowerCase();
        if (ending.equalsIgnoreCase("wav")) {
            return new WavFile(pathname);
        }else if (ending.equalsIgnoreCase("mp3") || ending.equalsIgnoreCase("ogg")) {
            return new TaggedFile(pathname);
        }else {
            throw new RuntimeException("Unknown suffix for AudioFile: \" "+ pathname + "\" ");
        }
    }
}
</code>```

答:
Monad-style solution with regex:</p>

```<code>final static Pattern audioFilePattern = Pattern.compile(".*\\.(\\w+)");

public static AudioFile getInstance(String path) {
    return Optional.of(path)
        .map(audioFilePattern::matcher).filter(Matcher::matches)
        .map(m -> m.group(1).toLowerCase())
        .filter(s -> Stream.of("wav", "mp3", "ogg").anyMatch(s::equals))
        .map(s -> "wav".equals(s) ? new WavFile(path) : new TaggedFile(path))
        .orElseThrow(() -> new IllegalArgumentException("Unknown suffix for AudioFile: \"" + path + "\""));
}
</code>```

Body:
I want to write this method in a shorter way. Do you have any ideas? I didn´t get something which runs...

public static AudioFile getInstance(String pathname) {
    String ending = null;
    int auxvar = pathname.lastIndexOf('.');

    if (auxvar<0) {
        throw new RuntimeException("Unknown suffix for AudioFile: \""+ pathname + "\"");
    }else {
        ending = pathname.substring(auxvar+1);
        ending = ending.toLowerCase();
        if (ending.equalsIgnoreCase("wav")) {
            return new WavFile(pathname);
        }else if (ending.equalsIgnoreCase("mp3") || ending.equalsIgnoreCase("ogg")) {
            return new TaggedFile(pathname);
        }else {
            throw new RuntimeException("Unknown suffix for AudioFile: \" "+ pathname + "\" ");
        }
    }
}

Body:
Monad-style solution with regex:

final static Pattern audioFilePattern = Pattern.compile(".*\\.(\\w+)");

public static AudioFile getInstance(String path) {
    return Optional.of(path)
        .map(audioFilePattern::matcher).filter(Matcher::matches)
        .map(m -> m.group(1).toLowerCase())
        .filter(s -> Stream.of("wav", "mp3", "ogg").anyMatch(s::equals))
        .map(s -> "wav".equals(s) ? new WavFile(path) : new TaggedFile(path))
        .orElseThrow(() -> new IllegalArgumentException("Unknown suffix for AudioFile: \"" + path + "\""));
}


问:
How does this __iter__ and __next__ algorithem work? How does it print all those prime numbers?
```<code>class PrimesBelow():
    def __init__(self,bound):
        self.candidate_numbers = list(range(2,bound))

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.candidate_numbers) == 0:
            raise StopIteration
        next_prime = self.candidate_numbers[0]
        self.candidate_numbers = [x for x in self.candidate_numbers if x % next_prime != 0]
        return next_prime
primes_to_hundread = [prime for prime in PrimesBelow(100)]
print(primes_to_hundread)
</code>```

Output:

```<code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
</code>```

答:
For large (or possibly infinite) bounds, a more (memory-)efficient implemention would use generators:

```<code>from itertools import count
from math import gcd

class Sieve:
    def __init__(self, bound=None):
        self.candidates = count(2) if bound is None else iter(range(2, bound))

    def __iter__(self):
        return self

    def __next__(self):
        prime = next(self.candidates)
        self.candidates = filter(lambda x, d=prime: x % d != 0, self.candidates)
        return prime
</code>```

When Sieve is first instantiated, the candidates attribute is a sequence of integers starting with 2.

__next__ has one precondition: the first element of the candidates attribute must be a prime number. This is satisfied by the first call because 2 is a prime number.

__next__ then

Removes the first element from candidates and calls it prime

Replaces candidates with a new iterable that consists only of those former candidates that are not divisible by prime.

These two actions fulfill the precondition for the next call to __next__, as the ith call to __next__ removes all numbers divisible by the ith prime number. Thus each remaining candidate is not divisible by any previously seen prime number.

Body:
class PrimesBelow():
    def __init__(self,bound):
        self.candidate_numbers = list(range(2,bound))

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.candidate_numbers) == 0:
            raise StopIteration
        next_prime = self.candidate_numbers[0]
        self.candidate_numbers = [x for x in self.candidate_numbers if x % next_prime != 0]
        return next_prime
primes_to_hundread = [prime for prime in PrimesBelow(100)]
print(primes_to_hundread)

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Body:
For large (or possibly infinite) bounds, a more (memory-)efficient implemention would use generators:

from itertools import count
from math import gcd

class Sieve:
    def __init__(self, bound=None):
        self.candidates = count(2) if bound is None else iter(range(2, bound))

    def __iter__(self):
        return self

    def __next__(self):
        prime = next(self.candidates)
        self.candidates = filter(lambda x, d=prime: x % d != 0, self.candidates)
        return prime

When Sieve is first instantiated, the candidates attribute is a sequence of integers starting with 2.

__next__ has one precondition: the first element of the candidates attribute must be a prime number. This is satisfied by the first call because 2 is a prime number.

__next__ then

Removes the first element from candidates and calls it prime

Replaces candidates with a new iterable that consists only of those former candidates that are not divisible by prime.

These two actions fulfill the precondition for the next call to __next__, as the ith call to __next__ removes all numbers divisible by the ith prime number. Thus each remaining candidate is not divisible by any previously seen prime number.


问:
Javascript: Proper way to separate metadata from HTML?
What is the proper way of separating my meta-data from the HTML? As my projects grow bigger and bigger tying up meta-data with HTML becomes more and more messy. Any good alternatives?

Meta Data: Everything the JS needs to know about an HTML element which isn't straight-forwardly encoded in the HTML elements and their attributes. E.g. a geolocation, enabled, disabled action.

Example: Say I have a list of places I want to show up on a map whenever I click on one of them. How do I identify that exact same place in JS so I could tell the map 'hey, move to that location'? Easiest way, that becomes messy in the end, is to tie it into the HTML, say the li id will be the geolocation. That's easy, but it is a code smell. How do I do this properly? .data() in jQuery also becomes horrible to maintain soon afterwards.

Conclusion: that's it, I'm going to find/write good MVC for JS.

答:
Depends what kind of metadata.  If it truly belongs with your HTML elements, that's a good place for it.  There are a few ideas I can think of:

Put only basic keys on your html elements and query the server for it (return it in JSON format).  This seems like bad design because the server has to remember / reassemble the state each time the client needs the metadata.  The more state / work you can push to the client, the more scalable your design.

Pass back javascript objects with your HTML, in a non-executable script tag (like you would for client side templating).

Store it in local storage (client side database for HTML 5)


问:
How to do a 'null' check in 'if' condition action of Azure Logic App
I've created a logic app which contains some trigger, an 'http' connector and then an 'If' condition activity. The 'http' connector returns a 'json' result say jsonObj.

I'm able to check condition as @equal(body('HTTP')['jsonObj'].someProperty,'someValue') but not able to do a null check on that someProperty value.

Below are some ways I tried which are not working.

```<code>@equal(body('HTTP')['jsonObj'].someProperty, null) --Unable to save
@equal(body('HTTP')['jsonObj']?.someProperty,'null') --Comparing with string value 'null'
</code>```

答:
Another option is to do a string concatenation in the designer and check for a value > '' (a space.)

For example below I am iterating over a set of agents where their email is potentially NULL, joining a null string to an empty string results in an empty string.

This has the advantage of working in both the designer and code view.

```<code>@concat('', items('iterateAgents')?['email'])
</code>```

This end up looking like the following in the code view

```<code>                "expression": {
                    "and": [
                        {
                            "greater": [
                                "@concat('', items('iterateAgents')?['email'])",
                                "  "
                            ]
                        }
                    ]
                },
</code>```

2021
You can now also do the following in an if statement, check if the value is null with an EQUALS statement, and return out a known value if it is null, which you can check for. Otherwise return out the actual value you are interested in.

```<code>if( equals(body('basicEventJSON')?['type'], null), '_IS_NULL_VALUE',body('basicEventJSON')?['type'])
</code>```

Body:
I've created a logic app which contains some trigger, an 'http' connector and then an 'If' condition activity. The 'http' connector returns a 'json' result say jsonObj.

I'm able to check condition as @equal(body('HTTP')['jsonObj'].someProperty,'someValue') but not able to do a null check on that someProperty value.

Below are some ways I tried which are not working.

@equal(body('HTTP')['jsonObj'].someProperty, null) --Unable to save
@equal(body('HTTP')['jsonObj']?.someProperty,'null') --Comparing with string value 'null'

Body:
Another option is to do a string concatenation in the designer and check for a value > '' (a space.)

For example below I am iterating over a set of agents where their email is potentially NULL, joining a null string to an empty string results in an empty string.

This has the advantage of working in both the designer and code view.

@concat('', items('iterateAgents')?['email'])

This end up looking like the following in the code view

                "expression": {
                    "and": [
                        {
                            "greater": [
                                "@concat('', items('iterateAgents')?['email'])",
                                "  "
                            ]
                        }
                    ]
                },

2021
You can now also do the following in an if statement, check if the value is null with an EQUALS statement, and return out a known value if it is null, which you can check for. Otherwise return out the actual value you are interested in.

if( equals(body('basicEventJSON')?['type'], null), '_IS_NULL_VALUE',body('basicEventJSON')?['type'])


问:
Publish to Azure Service Bus using MassTransit is causing errors
I am new to both MassTransit and Azure Service Bus. I am attempting to use an architecture where either RabbitMq or Azure Service Bus is used in a .NET Core 3.1 API. I have the RabbitMq portion working and just started on the Azure Service Bus. I have an API that will take an incoming payload and publish it to a queue. When I attempt to publish via the Azure Service Bus approach, I get an error "SubCode=40000. Cannot operate on type Topic because the namespace 'servicehubqa' is using 'Basic' tier.

I am attempting to use a queue approach and am hoping to create the queue as messages are published. Currently, the service bus is using a Basic pricing tier as the documentation says that I can play with queues at that level. I am not sure if I need to manually create the queue (I had to do this approach using RabbitMq since no queue would be created if no consumer exists). Is topic the default approach if nothing is specified? How do I specify queue vs topic?

My code is as follows below.

Startup - ConfigureServices

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(Configuration);

        services.AddScoped<IMassTransitRabbitMqTransport, MassTransitRabbitMqTransport>();
        services.AddScoped<IMassTransitAzureServiceBusTransport, MassTransitAzureServiceBusTransport>();

        var messageProvider = ConfigProvider.GetConfig("MessageService", "Messaging_Service");
        switch (messageProvider)
        {
            case "AzureServiceBus":
                services.AddScoped<IMessagingService, MassTransitAzureServiceBusMessagingService>();
                break;
            case "RabbitMq":
                services.AddScoped<IMessagingService, MassTransitRabbitMqMessagingService>();
                break;
            default:
                throw new ArgumentException("Invalid message service");
        };

        services.AddControllers();
    }
</code>```

Controller

```<code>public class ListenerController : ControllerBase
{
    readonly ILogger<ListenerController> logger;
    readonly IMessagingService messenger;

    public ListenerController(
        ILogger<ListenerController> logger,
        IMessagingService messenger)
    {
        this.logger = logger;
        this.messenger = messenger;
    }

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        var payload = new
        {
            ...
        };

        await messenger.Publish(payload);

        return Ok();
    }
}
</code>```

IMessagingService

```<code>public interface IMessagingService
{
    Task Publish(object payload);
}
</code>```

IMassTransitTransport

```<code>public interface IMassTransitTransport
{
    IBusControl BusControl { get; }
}

public interface IMassTransitRabbitMqTransport : IMassTransitTransport { }

public interface IMassTransitAzureServiceBusTransport : IMassTransitTransport { }
</code>```

MassTransitAzureServiceBusTransport

```<code>public sealed class MassTransitAzureServiceBusTransport : IMassTransitAzureServiceBusTransport
{
    public IBusControl BusControl { get; }

    public MassTransitAzureServiceBusTransport()
    {
        BusControl = ConfigureBus();
        BusControl.StartAsync();
    }

    IBusControl ConfigureBus()
    {
        return Bus.Factory.CreateUsingAzureServiceBus(config => {
            var host = config.Host(ConfigProvider.GetConfig("AzureServiceBus", "AzureServiceBus_ConnStr"), host => { });
        });
    }
}
</code>```

MassTransitAzureServiceBusMessagingService

```<code>public class MassTransitAzureServiceBusMessagingService : IMessagingService
{
    readonly IMassTransitAzureServiceBusTransport massTransitTransport;

    public MassTransitAzureServiceBusMessagingService(IMassTransitAzureServiceBusTransport massTransitTransport)
    {
        //transport bus config already happens in massTransitTransport constructor
        this.massTransitTransport = massTransitTransport;
    }

    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                //IRegisterCommandUpdateStatus is an interface specifying the properties needed
                await massTransitTransport.BusControl.Publish<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }
}
</code>```

答: The Azure Service Bus basic tier does not allow the use of topics. So you would not be able to use publish. That said, MassTransit doesn't really work with the basic tier, despite attempts in the past that may have been successful.</p>

Body:
I am new to both MassTransit and Azure Service Bus. I am attempting to use an architecture where either RabbitMq or Azure Service Bus is used in a .NET Core 3.1 API. I have the RabbitMq portion working and just started on the Azure Service Bus. I have an API that will take an incoming payload and publish it to a queue. When I attempt to publish via the Azure Service Bus approach, I get an error "SubCode=40000. Cannot operate on type Topic because the namespace 'servicehubqa' is using 'Basic' tier.

I am attempting to use a queue approach and am hoping to create the queue as messages are published. Currently, the service bus is using a Basic pricing tier as the documentation says that I can play with queues at that level. I am not sure if I need to manually create the queue (I had to do this approach using RabbitMq since no queue would be created if no consumer exists). Is topic the default approach if nothing is specified? How do I specify queue vs topic?

My code is as follows below.

Startup - ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(Configuration);

        services.AddScoped<IMassTransitRabbitMqTransport, MassTransitRabbitMqTransport>();
        services.AddScoped<IMassTransitAzureServiceBusTransport, MassTransitAzureServiceBusTransport>();

        var messageProvider = ConfigProvider.GetConfig("MessageService", "Messaging_Service");
        switch (messageProvider)
        {
            case "AzureServiceBus":
                services.AddScoped<IMessagingService, MassTransitAzureServiceBusMessagingService>();
                break;
            case "RabbitMq":
                services.AddScoped<IMessagingService, MassTransitRabbitMqMessagingService>();
                break;
            default:
                throw new ArgumentException("Invalid message service");
        };

        services.AddControllers();
    }

Controller

public class ListenerController : ControllerBase
{
    readonly ILogger<ListenerController> logger;
    readonly IMessagingService messenger;

    public ListenerController(
        ILogger<ListenerController> logger,
        IMessagingService messenger)
    {
        this.logger = logger;
        this.messenger = messenger;
    }

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        var payload = new
        {
            ...
        };

        await messenger.Publish(payload);

        return Ok();
    }
}

IMessagingService

public interface IMessagingService
{
    Task Publish(object payload);
}

IMassTransitTransport

public interface IMassTransitTransport
{
    IBusControl BusControl { get; }
}

public interface IMassTransitRabbitMqTransport : IMassTransitTransport { }

public interface IMassTransitAzureServiceBusTransport : IMassTransitTransport { }

MassTransitAzureServiceBusTransport

public sealed class MassTransitAzureServiceBusTransport : IMassTransitAzureServiceBusTransport
{
    public IBusControl BusControl { get; }

    public MassTransitAzureServiceBusTransport()
    {
        BusControl = ConfigureBus();
        BusControl.StartAsync();
    }

    IBusControl ConfigureBus()
    {
        return Bus.Factory.CreateUsingAzureServiceBus(config => {
            var host = config.Host(ConfigProvider.GetConfig("AzureServiceBus", "AzureServiceBus_ConnStr"), host => { });
        });
    }
}

MassTransitAzureServiceBusMessagingService

public class MassTransitAzureServiceBusMessagingService : IMessagingService
{
    readonly IMassTransitAzureServiceBusTransport massTransitTransport;

    public MassTransitAzureServiceBusMessagingService(IMassTransitAzureServiceBusTransport massTransitTransport)
    {
        //transport bus config already happens in massTransitTransport constructor
        this.massTransitTransport = massTransitTransport;
    }

    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                //IRegisterCommandUpdateStatus is an interface specifying the properties needed
                await massTransitTransport.BusControl.Publish<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }
}


问:
A bug when creating parameters for request.get
I'm iterating this website and try to scrape the links of news articles.
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

First, I need to get the links of the pages, so I used this code:

```<code>def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    params = {
        'q': 'China%20COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China%20COVID-19',
    }
    pagelinks = []

    myarticle = []
    for page_no in range(1,3):
        try:# to avoid "No connection adapters were found for" error
            params['gsc.page'] = page_no
            response = requests.get(url=url,
                                    headers=user_agent,
                                    params=params)
            print(response.request.url)

        except Exception as e:
            print(e)
</code>```
```<code>scrape('https://www.usnews.com/search/')
</code>```

However, the results are not correct:

```<code>https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=2
</code>```

The expected results should like this:

```<code>https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=2
</code>```

Could someone help me solve this bug? I'd appreciate that very much!

答:
If you open up in a browser the URLs that you get, you'll see that the search string is China%2520COVID-19, and not China COVID-19, as you expect.

The %20 that you see in the query string is a urlencoded space character. See percent-encoding on MDN. If you urldecode China%2520COVID-19, you'll get China%20COVID-19, and by this I get that %25 is the encoded percent character.

Probably requests already urlencodes your query string values, so you don't need to. What you could change for it to work is to use the decoded values, e.g. spaces () instead of %20.

    params = {
        'q': 'China COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China COVID-19',
    }
```

Body:
I'm iterating this website and try to scrape the links of news articles.
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

First, I need to get the links of the pages, so I used this code:

def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    params = {
        'q': 'China%20COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China%20COVID-19',
    }
    pagelinks = []

    myarticle = []
    for page_no in range(1,3):
        try:# to avoid "No connection adapters were found for" error
            params['gsc.page'] = page_no
            response = requests.get(url=url,
                                    headers=user_agent,
                                    params=params)
            print(response.request.url)

        except Exception as e:
            print(e)

scrape('https://www.usnews.com/search/')

However, the results are not correct:

https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=2

The expected results should like this:

https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=2

Could someone help me solve this bug? I'd appreciate that very much!


问:
Problem with logo in a footer of Moodle website
I replaced Moodle logo with a logo of my web place keeping the same file name and file size and the new logo shows up when I run my website in Firefox or Edge, but the logo doesn't show up in Chrome, Brave and maybe other web browsers.
What I did:

I put my logo in this file: /pix/moodlelogo_grayhat.png

I changed logo link in: /lib/outputrenderers.php
If someone wants to take a look, this is my website.

Thank you in advance!

答:
Your theme's markup doesn't contain the filename extension. For some reason (either server configuration or file problems) the browser thinks that the image is an SVG file.

The best solution may be to modify the theme to add .png to the markup. If the filename is dynamically injected via template code you may just need to rename the file with the extension present.


问:
Telegram-Bot does not respond correctly
I am doing a telegram bot, I have a merger that is to divide that does not work but to add if it does, does anyone know why?

```<code>import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

def start(update, context):
    update.message.reply_text('Hola!')

def help(update, context):
    update.message.reply_text('Help!')

def sumar(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        suma = numero1 + numero2
        update.message.reply_text('La suma es '+str(suma))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def dividir(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        div= numero1 / numero2
        update.message.reply_text('La division da '+str(div))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("1225696978:AAFsJYex51HMRbKL814tLJJPczJMu3nLlYY", use_context=True)

    # Get the dispatcher to register handlers
    botm3 = updater.dispatcher

    # on different commands - answer in Telegram
    botm3.add_handler(CommandHandler("start", start))
    botm3.add_handler(CommandHandler("help", help))
    botm3.add_handler(CommandHandler("Sumar", sumar))
    botm3.add_handler(CommandHandler("Division", dividir))

    # on noncommand i.e message - echo the message on Telegram
    botm3.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    botm3.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

I have two functions for the bot, one works the other does not and they are the same structure but it does not take effect.
I leave you my token so you can do the tests if you want the name of the bot is:
@ moha_m03_1bot

答:
it is 'division' not 'dividir' don't try the function name in telegram try 'division'

```<code>botm3.add_handler(CommandHandler("Division", dividir))
</code>```

It is working perfectly for me

Title: Telegram-Bot does not respond correctly

Body:
I am doing a telegram bot, I have a merger that is to divide that does not work but to add if it does, does anyone know why?

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

def start(update, context):
    update.message.reply_text('Hola!')

def help(update, context):
    update.message.reply_text('Help!')

def sumar(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        suma = numero1 + numero2
        update.message.reply_text('La suma es '+str(suma))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def dividir(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        div= numero1 / numero2
        update.message.reply_text('La division da '+str(div))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("1225696978:AAFsJYex51HMRbKL814tLJJPczJMu3nLlYY", use_context=True)

    # Get the dispatcher to register handlers
    botm3 = updater.dispatcher

    # on different commands - answer in Telegram
    botm3.add_handler(CommandHandler("start", start))
    botm3.add_handler(CommandHandler("help", help))
    botm3.add_handler(CommandHandler("Sumar", sumar))
    botm3.add_handler(CommandHandler("Division", dividir))

    # on noncommand i.e message - echo the message on Telegram
    botm3.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    botm3.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

I have two functions for the bot, one works the other does not and they are the same structure but it does not take effect.
I leave you my token so you can do the tests if you want the name of the bot is:
@ moha_m03_1bot

Body:
it is 'division' not 'dividir' don't try the function name in telegram try 'division'

botm3.add_handler(CommandHandler("Division", dividir))

It is working perfectly for me


问:
Pandas DataFrame concatenate along new axis
I have a directory with 1000+ csv files, which I want to read in and store in a dataframe, to then save that to a file. I would like the dataframe dimensions to be [file, line in file, content of line]. This is what I have come up with so far:

import pandas as pd
import glob

csv_files = glob.glob("data/*sample.csv")
df = (pd.read_csv(f) for f in csv_files)
dataset = pd.concat(df, ignore_index=True)
```

This gives me a dataframe with the shape [line, content of line] but I can no longer see which file the line is from. Can somebody help me here?

答:
You can create list of all filenames withour extension in list and then pass to parameter keys in concat, so MultiIndex is created. Last remove second level and convert it to index:

```<code>from os.path import splitext, basename

csv_files = glob.glob("data/*sample.csv")
names = (splitext(basename(x))[0] for x in csv_files)
dfs = (pd.read_csv(f) for f in csv_files)

df = (pd.concat(dfs, keys=names)
        .reset_index(level=1, drop=True)
        .rename_axis('New')
        .reset_index())
</code>```

Body:
I have a directory with 1000+ csv files, which I want to read in and store in a dataframe, to then save that to a file. I would like the dataframe dimensions to be [file, line in file, content of line]. This is what I have come up with so far:

import pandas as pd
import glob

csv_files = glob.glob("data/*sample.csv")
df = (pd.read_csv(f) for f in csv_files)
dataset = pd.concat(df, ignore_index=True)

This gives me a dataframe with the shape [line, content of line] but I can no longer see which file the line is from. Can somebody help me here?

Body:
You can create list of all filenames withour extension in list and then pass to parameter keys in concat, so MultiIndex is created. Last remove second level and convert it to index:

from os.path import splitext, basename

csv_files = glob.glob("data/*sample.csv")
names = (splitext(basename(x))[0] for x in csv_files)
dfs = (pd.read_csv(f) for f in csv_files)

df = (pd.concat(dfs, keys=names)
        .reset_index(level=1, drop=True)
        .rename_axis('New')
        .reset_index())


问:
Best way to implement HTML5 video
I understand that HTML5 video is way more complicated than its proponents would like us to believe. Safari uses the proprietary H.264 codec, whereas Firefox, Chrome and Opera all support the open-source Theora. Internet Explorer doesn't support either, so needs a fallback, such as .mov or Flash.

I found a superb guide somewhere that put together a step-by-step guide for HTML5 on all these browsers, but I can't find it anywhere. Very annoying :(

What's the best way to implement HTML5 video so that all these browsers are covered? (Unfortunately, Flash is not an option.)

Edit: Ok, from what I've read, here is my own answer: This is the best way to implement HTML 5 video...

```<code>    <video id="video" width="450" height="170" preload="auto" autoplay="autoplay">
        <source src="../static/video/video.mp4" />
        <source src="../static/video/video.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/video.ogv" type='video/ogg; codecs="theora, vorbis"' />
        <!-- Fallback (either Flash, an image, or a "Video not supported" message, etc.) -->
    </video>
</code>```

It's the only way that's worked as expected on every browser so far. Unfortunately autoplay doesn't seem to be working in Chrome? :(

Update: Chrome doesn't support Autoplay. Update update: Autoplay works with the "muted" attribute.

答:
I suspect this guide from Kroc Camen is the one you want http://camendesign.com/code/video_for_everybody.

It's not quite as hard as he outlines there if you are happy to use Flash to support older IEs.

Two versions of each video, one Theora and one H.264 will cover everything possible. One H.264 is enough if you don't mind browsers using Flash instead of Theora.

Worth reading up on WebM as well, it's set to replace theora.

Title: Best way to implement HTML5 video

Body:
I understand that HTML5 video is way more complicated than its proponents would like us to believe. Safari uses the proprietary H.264 codec, whereas Firefox, Chrome and Opera all support the open-source Theora. Internet Explorer doesn't support either, so needs a fallback, such as .mov or Flash.

I found a superb guide somewhere that put together a step-by-step guide for HTML5 on all these browsers, but I can't find it anywhere. Very annoying :(

What's the best way to implement HTML5 video so that all these browsers are covered? (Unfortunately, Flash is not an option.)

Edit: Ok, from what I've read, here is my own answer: This is the best way to implement HTML 5 video...

    <video id="video" width="450" height="170" preload="auto" autoplay="autoplay">
        <source src="../static/video/video.mp4" />
        <source src="../static/video/video.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/video.ogv" type='video/ogg; codecs="theora, vorbis"' />

    </video>

It's the only way that's worked as expected on every browser so far. Unfortunately autoplay doesn't seem to be working in Chrome? :(

Update: Chrome doesn't support Autoplay. Update update: Autoplay works with the "muted" attribute.


问:
React-materialize Chip - Javascript Plugin - autocomplete : how to update state variable
I would like to update a state variable array but I can't figure out how to update on change.
I want to change the array "countries", but when I try to link it with the React-materialize Chip, it does not work.
After I have selected an option :

either I have no way to update the state variable and I see the chips with the X to delete it

either I have the function to update the state but then I do not see the chips with the X to delete it

How can I get the selected chip displayed normally and still update the state variable?
Thank you

Below is my code also available in CodeSandbox

```<code>import React from "react";
import ReactDOM from "react-dom";
import { Icon, Chip} from 'react-materialize';
import 'materialize-css';

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          name: "Venom",
          countries: [{ name: 'France' }, { name: 'Germany' }],
        };
      }
      handleAddCountry = (e) => {
        console.log("Chip :")
        console.log(e.target.name)
        this.setState({ countries: this.state.countries.concat([{ name: e.target.value }]) });
      }
      handleAddFrance = (e) => {
        console.log("Button:")
        console.log(e.target.value)
        this.setState({ countries: this.state.countries.concat([{ name: e.target.value }]) });
      }
      render() {
        const { countries} = this.state
        return (
        <div>
              <div>
                <h1>{this.state.name}</h1>
              </div>

            <div>
                <Chip
                        onChange={ this.handleAddCountry }
                        close={false}
                        closeIcon={<Icon className="close">close</Icon>}
                        options={{
                        placeholder: 'saisir un territoire',
                        secondaryPlaceholder: '+territoire',
                        autocompleteOptions: {
                        data: {
                        '   France métropolitaine  '   :   null,
                        '   DOM - TOM   '   :   null,
                        '   DOM '   :   null,
                        '   Afghanistan '   :   null,
                        },
                        limit: Infinity,
                        minLength: 1,
                        onAutocomplete: function noRefCheck(){}
                        }
                        }}
                />
            </div>
            <button type="button" onClick={this.handleAddFrance} value="France" className="small">Add France</button>
                <br></br>
                {countries.map(country => <div>{country.name}</div>)}
          </div>
        );
      }
    }
    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      rootElement

);
</code>```

答:
At the end this is the workaround I found :

```<code><Chip close={false}
                closeIcon={<Icon className="close">close</Icon>}
                options={{
                  onChipAdd: this.addProdTerritory,
                  placeholder: "saisir territoire",
                  secondaryPlaceholder: "+territoire",
                  autocompleteOptions: {
                    data: {
                      " France métropolitaine " : null  ,
                      " Algérie " : null  ,
                      " Allemagne " : null  ,
                      " Andorre " : null  ,

                    },
                    limit: Infinity,
                    minLength: 1,
                    onAutocomplete: function noRefCheck() {}},}}
            />
</code>```

with

```<code>    this.state = {
      countriesProd: [{ name: "France" }]
                   }
    this.addProdTerritory = this.addProdTerritory.bind(this);

</code>```

```<code>addProdTerritory = foo => {
    var ret = foo.text().replace('close','');
    this.setState({
      countriesProd: this.state.countriesProd.concat([{ name: ret }])
    });
  };

  deleteProdTerritory(i) {
    const { countriesProd } = this.state;
    countriesProd.splice(i, 1);
    this.setState({ countriesProd });
  }
</code>```

and below the autocomplete field, I display a table with chips in column 1 and delete button in column 2

I figured it out on GitHub

Body:
I would like to update a state variable array but I can't figure out how to update on change.
I want to change the array "countries", but when I try to link it with the React-materialize Chip, it does not work.
After I have selected an option :

either I have no way to update the state variable and I see the chips with the X to delete it

either I have the function to update the state but then I do not see the chips with the X to delete it

How can I get the selected chip displayed normally and still update the state variable?
Thank you

Below is my code also available in CodeSandbox

import React from "react";
import ReactDOM from "react-dom";
import { Icon, Chip} from 'react-materialize';
import 'materialize-css';

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          name: "Venom",
          countries: [{ name: 'France' }, { name: 'Germany' }],
        };
      }
      handleAddCountry = (e) => {
        console.log("Chip :")
        console.log(e.target.name)
        this.setState({ countries: this.state.countries.concat([{ name: e.target.value }]) });
      }
      handleAddFrance = (e) => {
        console.log("Button:")
        console.log(e.target.value)
        this.setState({ countries: this.state.countries.concat([{ name: e.target.value }]) });
      }
      render() {
        const { countries} = this.state
        return (

{this.state.name}

                <Chip
                        onChange={ this.handleAddCountry }
                        close={false}
                        closeIcon={<Icon className="close">close</Icon>}
                        options={{
                        placeholder: 'saisir un territoire',
                        secondaryPlaceholder: '+territoire',
                        autocompleteOptions: {
                        data: {
                        '   France métropolitaine  '   :   null,
                        '   DOM - TOM   '   :   null,
                        '   DOM '   :   null,
                        '   Afghanistan '   :   null,
                        },
                        limit: Infinity,
                        minLength: 1,
                        onAutocomplete: function noRefCheck(){}
                        }
                        }}
                />

            <button type="button" onClick={this.handleAddFrance} value="France" className="small">Add France</button>

                {countries.map(country =>
{country.name}
)}

        );
      }
    }
    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      rootElement

);

Body:
At the end this is the workaround I found :

<Chip close={false}
                closeIcon={<Icon className="close">close</Icon>}
                options={{
                  onChipAdd: this.addProdTerritory,
                  placeholder: "saisir territoire",
                  secondaryPlaceholder: "+territoire",
                  autocompleteOptions: {
                    data: {
                      " France métropolitaine " : null  ,
                      " Algérie " : null  ,
                      " Allemagne " : null  ,
                      " Andorre " : null  ,

                    },
                    limit: Infinity,
                    minLength: 1,
                    onAutocomplete: function noRefCheck() {}},}}
            />

with

    this.state = {
      countriesProd: [{ name: "France" }]
                   }
    this.addProdTerritory = this.addProdTerritory.bind(this);

addProdTerritory = foo => {
    var ret = foo.text().replace('close','');
    this.setState({
      countriesProd: this.state.countriesProd.concat([{ name: ret }])
    });
  };

  deleteProdTerritory(i) {
    const { countriesProd } = this.state;
    countriesProd.splice(i, 1);
    this.setState({ countriesProd });
  }

and below the autocomplete field, I display a table with chips in column 1 and delete button in column 2

I figured it out on GitHub


问:
How do you make a choropleth map with Mapbox GL JS, and an object?
I'm struggling to find the right information in order to create a choropleth map using mapbox. Their examples are very vague.

I currently have a geojson showing the polygons for all the UK counties. I used map.addLayer to add this to the map, but at the moment, the whole map is the same color:

```<code>        map.addLayer({
        "id": 'counties',
        "type": "fill",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": counties
            }
        },
        "layout": {},
        "paint": {
            "fill-color": fill,
            "fill-opacity": 0.8
        }
    });
</code>```

counties is the geojson file, which also includes a property called 'County'. In addition, I have returned an object, which returns key, value pairs of counties, and the number of times it appeared in my data, respectively:

```<code>{
    "Bristol": 2,
    "Cheshire": 1,
    "City and County of the City of London": 14,
    "City of Aberdeen": 1,
    "City of Edinburgh": 3
}
</code>```

How can I create a choropleth map using the data from my object, to return as different shades/color for the layer (e.g, counties such as Cheshire would be a lighter color, because the value is one, but City and County of the City of London would have a darker color because the value is 14?

答: The simplest way is using the mapbox-choropleth library.</p>

Body:
I'm struggling to find the right information in order to create a choropleth map using mapbox. Their examples are very vague.

I currently have a geojson showing the polygons for all the UK counties. I used map.addLayer to add this to the map, but at the moment, the whole map is the same color:

        map.addLayer({
        "id": 'counties',
        "type": "fill",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": counties
            }
        },
        "layout": {},
        "paint": {
            "fill-color": fill,
            "fill-opacity": 0.8
        }
    });

counties is the geojson file, which also includes a property called 'County'. In addition, I have returned an object, which returns key, value pairs of counties, and the number of times it appeared in my data, respectively:

{
    "Bristol": 2,
    "Cheshire": 1,
    "City and County of the City of London": 14,
    "City of Aberdeen": 1,
    "City of Edinburgh": 3
}

How can I create a choropleth map using the data from my object, to return as different shades/color for the layer (e.g, counties such as Cheshire would be a lighter color, because the value is one, but City and County of the City of London would have a darker color because the value is 14?


答:
Just anchor the pattern to the end of the string:

```<code>select regexp_substr('sys: error: This is a message ''123:'' for column EMP_NB', '[[:alpha:]_]+$')
from dual
</code>```

Here is a db<>fiddle.

Your example data has a period at the end.  If that is part of the string, then you can use regexp_replace():

```<code>select regexp_replace(message, '^.*[^[:alpha:]_]([[:alpha:]_]+)[^[:alpha:]_]*$', '\1')
from (select 'sys: error: This is a message ''123:'' for column EMP_NB' as message from dual union all
      select 'sys: error: This is a message ''45346:'' for column EM_NM.' as message from dual union all
      select 'sys: error: This is a message ''78324f9:'' for column DEPT_NO_VL.' as message from dual
     ) x
</code>```

Title: Get a word after specific word using regexp_substr in sql oracle

Body:
I have tried

select regexp_substr ('sys: error: This is a message ''123:'' for column EMP_NB', '[[:alpha:]_]+',1,9) from dual

I have column filled with this type of data.

sys: error: This is a message '123:' for column EMP_NB.
sys: error: This is a message '45346:' for column EM_NM.
sys: error: This is a message '78324f9:' for column DEPT_NO_VL.

I need an output like below this using regexp_substr in Oracle SQL. The challenge is the length of string tend to change and I need to extract only the characters after the column word in string.

Expected outputs:

EMP_NB
EM_NM
DEPT_NO_VL

Body:
Just anchor the pattern to the end of the string:

select regexp_substr('sys: error: This is a message ''123:'' for column EMP_NB', '[[:alpha:]_]+$')
from dual

Here is a db<>fiddle.

Your example data has a period at the end.  If that is part of the string, then you can use regexp_replace():

select regexp_replace(message, '^.*[^[:alpha:]_]([[:alpha:]_]+)[^[:alpha:]_]*$', '\1')
from (select 'sys: error: This is a message ''123:'' for column EMP_NB' as message from dual union all
      select 'sys: error: This is a message ''45346:'' for column EM_NM.' as message from dual union all
      select 'sys: error: This is a message ''78324f9:'' for column DEPT_NO_VL.' as message from dual
     ) x


问:
Function that should be targeting a specific open workbook seems to be using the activebook instead
This cell counting formula that I am using seems to be targeting the activesheet rather than the sheet that I clearly specified for it to use. Could anyone help me debug this? I'm relatively new to VBA. I was getting some unexplainable results from this formula, and after some testing it seems that whichever sheet I have as active is what this formula calculates for. That is not the intended result

```<code>        Dim totalRows as double
        totalRows = Workbooks("Mastersheet").Worksheets("masterBudgetSheet").range("A8:A" & Cells(Rows.Count, "A").End(xlUp).Row).Rows.Count
</code>```

Does specifying workbook and worksheet not target those two elements?

**ANSWERED: **
The targeting formula that I was using had an implicit call to the activesheet. This was fixed by ensuring that all the times that I called the "range" function that it included the exact sheet that I was trying to reference. (If none is included, it defaults to the active)

答:
You need to always reference your ranges, you forgot to reference the Cells(Rows.Count...).

Also you could make your code more readable like this:

```<code>Dim totalRows As Double
With Workbooks("Mastersheet").Worksheets("masterBudgetSheet")
    totalRows = .Range("A8:A" & .Cells(.Rows.Count, "A").End(xlUp).Row).Rows.Count
End with
</code>```

This way, with the single use of the dot in front of your range, you are referencing the With Workbooks("Mastersheet").Worksheets("masterBudgetSheet") in between the With statement

Body:
This cell counting formula that I am using seems to be targeting the activesheet rather than the sheet that I clearly specified for it to use. Could anyone help me debug this? I'm relatively new to VBA. I was getting some unexplainable results from this formula, and after some testing it seems that whichever sheet I have as active is what this formula calculates for. That is not the intended result

        Dim totalRows as double
        totalRows = Workbooks("Mastersheet").Worksheets("masterBudgetSheet").range("A8:A" & Cells(Rows.Count, "A").End(xlUp).Row).Rows.Count

Does specifying workbook and worksheet not target those two elements?

**ANSWERED: **
The targeting formula that I was using had an implicit call to the activesheet. This was fixed by ensuring that all the times that I called the "range" function that it included the exact sheet that I was trying to reference. (If none is included, it defaults to the active)

Body:
You need to always reference your ranges, you forgot to reference the Cells(Rows.Count...).

Also you could make your code more readable like this:

Dim totalRows As Double
With Workbooks("Mastersheet").Worksheets("masterBudgetSheet")
    totalRows = .Range("A8:A" & .Cells(.Rows.Count, "A").End(xlUp).Row).Rows.Count
End with

This way, with the single use of the dot in front of your range, you are referencing the With Workbooks("Mastersheet").Worksheets("masterBudgetSheet") in between the With statement


问:
How does React.useState triggers re-render?

import { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (

You clicked {count} times

      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>

  );
}
```

<p>In the above example whenever <code>setCount(count + 1)</code> is invoked a re-render  happens. I am curious to learn the flow.</p>

<p>I tried looking into the source code. I could not find any reference of <code>useState</code> or other hooks at github.com/facebook/react.</p>

<p>I installed <code>react@next</code> via <code>npm i react@next</code> and found the following at <code>node_modules/react/cjs/react.development.js</code></p>

<pre class="lang-js prettyprint-override"><code>function useState(initialState) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}
</code>```

On tracing back for dispatcher.useState(), I could only find the following ...

function resolveDispatcher() {
  var dispatcher = ReactCurrentOwner.currentDispatcher;
  !(dispatcher !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component.') : void 0;
  return dispatcher;
}
```

<pre class="lang-js prettyprint-override"><code>var ReactCurrentOwner = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: null,
  currentDispatcher: null
};
</code>```

I wonder where can I find dispatcher.useState() implementation and learn how it triggers re-render when <s>setState</s> setCount is invoked.

Any pointer would be helpful.

Thanks!

答:
The key in understanding this is the following paragraph from the Hooks FAQ

How does React associate Hook calls with components?

React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components).

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

(This also explains the Rules of Hooks. Hooks need to be called unconditionally in the same order, otherwise the association of memory cell and hook is messed up.)

Let's walk through your counter example, and see what happens. For simplicity I will refer to the compiled development React source code and React DOM source code, both version 16.13.1.

The example starts when the component mounts and useState() (defined on line 1581) is called for the first time.

```<code>function useState(initialState) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}
</code>```

As you have noticed, this calls resolveDispatcher() (defined on line 1546). The dispatcher refers internally to the component that's currently being rendered. Within a component you can (if you dare to get fired), have a look at the dispatcher, e.g. via

```<code>console.log(React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current)
</code>```

If you apply this in case of the counter example, you will notice that the dispatcher.useState() refers to the react-dom code. When the component is first mounted, useState refers to the one defined on line 15986 which calls mountState(). Upon re-rendering, the dispatcher has changed and the function useState() on line 16077 is triggered, which calls updateState(). Both methods, mountState() on line 15352 and updateState() on line 15371, return the count, setCount pair.

Tracing ReactCurrentDispatcher gets quite messy. However, the fact of its existence is already enough to understand how the re-rendering happens. The magic happens behind the scene. As the FAQ states, React keeps track of the currently rendered component. This means, useState() knows which component it is attached to, how to find the state information and how to trigger the re-rendering.

Body:
import { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (

You clicked {count} times

      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>

  );
}

In the above example whenever setCount(count + 1) is invoked a re-render  happens. I am curious to learn the flow.

I tried looking into the source code. I could not find any reference of useState or other hooks at github.com/facebook/react.

I installed react@next via npm i react@next and found the following at node_modules/react/cjs/react.development.js

function useState(initialState) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}

On tracing back for dispatcher.useState(), I could only find the following ...

function resolveDispatcher() {
  var dispatcher = ReactCurrentOwner.currentDispatcher;
  !(dispatcher !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component.') : void 0;
  return dispatcher;
}

var ReactCurrentOwner = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: null,
  currentDispatcher: null
};

I wonder where can I find dispatcher.useState() implementation and learn how it triggers re-render when <s>setState</s> setCount is invoked.

Any pointer would be helpful.

Thanks!

Body:
The key in understanding this is the following paragraph from the Hooks FAQ

How does React associate Hook calls with components?

React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components).

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

(This also explains the Rules of Hooks. Hooks need to be called unconditionally in the same order, otherwise the association of memory cell and hook is messed up.)

Let's walk through your counter example, and see what happens. For simplicity I will refer to the compiled development React source code and React DOM source code, both version 16.13.1.

The example starts when the component mounts and useState() (defined on line 1581) is called for the first time.

function useState(initialState) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}

As you have noticed, this calls resolveDispatcher() (defined on line 1546). The dispatcher refers internally to the component that's currently being rendered. Within a component you can (if you dare to get fired), have a look at the dispatcher, e.g. via

console.log(React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current)

If you apply this in case of the counter example, you will notice that the dispatcher.useState() refers to the react-dom code. When the component is first mounted, useState refers to the one defined on line 15986 which calls mountState(). Upon re-rendering, the dispatcher has changed and the function useState() on line 16077 is triggered, which calls updateState(). Both methods, mountState() on line 15352 and updateState() on line 15371, return the count, setCount pair.

Tracing ReactCurrentDispatcher gets quite messy. However, the fact of its existence is already enough to understand how the re-rendering happens. The magic happens behind the scene. As the FAQ states, React keeps track of the currently rendered component. This means, useState() knows which component it is attached to, how to find the state information and how to trigger the re-rendering.


问:
Download .exe file giving error in Angular frontend
I am using this in node JS:-

```<code>let file = `${process.cwd()}/server/downloads/JRuler.exe`;
   let filename = path.basename(file);
   let stat = fs.statSync(file);

   res.writeHead(200, {
       'Content-Type': 'application/octet-stream',
       'Content-Length': stat.size,
       'Content-disposition': 'attachment; filename=' + filename
   });

   let readStream = fs.createReadStream(file);
   readStream.pipe(res);
</code>```

And this is in Angular

```<code>  download() {
    this.clientAPI.get(Endpoints.DOWNLOAD).toPromise()
    .then(res => {
      console.log('res')
      let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
      console.log('blob',blob);
      let a = document.createElement('a');
      var ua=navigator.userAgent;
      var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
      if(msie){
        navigator.msSaveOrOpenBlob(blob,res.filename);
      }
      else{
      a.href = (URL.createObjectURL(blob));
      a.download = res.filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      }
    })
    .catch(err => console.error("download error = ", err))
  }
</code>```

But I am getting the error:-

Please suggest me how i can handle at angular frontend.

答:
responseType blob is required for http client to know that how to parse response and return to subscriber or promise in your case.</p>

```<code> download() {
        this.clientAPI.get(Endpoints.DOWNLOAD, {responseType: 'blob'}).toPromise()
        .then(res => {
          console.log('res')
          let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
          console.log('blob',blob);
          let a = document.createElement('a');
          var ua=navigator.userAgent;
          var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
          if(msie){
            navigator.msSaveOrOpenBlob(blob,res.filename);
          }
          else{
          a.href = (URL.createObjectURL(blob));
          a.download = res.filename;
          document.body.appendChild(a);
          a.click();
          a.remove();
          }
        })
        .catch(err => console.error("download error = ", err))
      }
</code>```

Body:
I am using this in node JS:-

let file = `${process.cwd()}/server/downloads/JRuler.exe`;
   let filename = path.basename(file);
   let stat = fs.statSync(file);

   res.writeHead(200, {
       'Content-Type': 'application/octet-stream',
       'Content-Length': stat.size,
       'Content-disposition': 'attachment; filename=' + filename
   });

   let readStream = fs.createReadStream(file);
   readStream.pipe(res);

And this is in Angular

  download() {
    this.clientAPI.get(Endpoints.DOWNLOAD).toPromise()
    .then(res => {
      console.log('res')
      let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
      console.log('blob',blob);
      let a = document.createElement('a');
      var ua=navigator.userAgent;
      var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
      if(msie){
        navigator.msSaveOrOpenBlob(blob,res.filename);
      }
      else{
      a.href = (URL.createObjectURL(blob));
      a.download = res.filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      }
    })
    .catch(err => console.error("download error = ", err))
  }

But I am getting the error:-

Please suggest me how i can handle at angular frontend.

Body:
responseType blob is required for http client to know that how to parse response and return to subscriber or promise in your case.

 download() {
        this.clientAPI.get(Endpoints.DOWNLOAD, {responseType: 'blob'}).toPromise()
        .then(res => {
          console.log('res')
          let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
          console.log('blob',blob);
          let a = document.createElement('a');
          var ua=navigator.userAgent;
          var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
          if(msie){
            navigator.msSaveOrOpenBlob(blob,res.filename);
          }
          else{
          a.href = (URL.createObjectURL(blob));
          a.download = res.filename;
          document.body.appendChild(a);
          a.click();
          a.remove();
          }
        })
        .catch(err => console.error("download error = ", err))
      }


问:
Benefits (and tips) of an upgrade from JBoss 4.2.x to JBoss 5.x, 6.x, 7.x and WildFly 8.x?
Please assume that I do not need to worry about development time and costs: I am interested in general technical benefits (improved performance? improved APIs?) and new features.

I am currently working on products using 4.2.x, and we consider a major shift for versions that are a long time ahead and need to converge.

I had a brief look at the release notes of each version and some articles about each release for 5.x, 6.x, 7.x and 8.x. But I would be glad to have first-hand feedback from people who have made the switch.

I noticed there are some important changes surrounding messaging (switching from JBoss MQ to JBoss Messenging), and that for JBoss 7.x it seems to change a fair bit its configuration layer. Then there's a lot more going on when switching to JBoss/WildFly 8.x.

Please recommend good articles pointing at pitfalls if you can. I found a few for migrations to JBoss 5.x, but not that many for 6.x or even 7.x, and someone else is evaluating 8.x for us now. Feel free to recommend alternatives as well if you think they are relevant, though I'd prefer to focus only on JBoss.

For information, we use a mix of JPF- and OSGi-enabled (using Eclipse Equinox) plugin-based systems, with clients developed in Swing (some deployed via WebStart).

Update: Though this question brought some great answers already, I think it deserves an update for WildFly (and actually, our internal projects delayed making the switch from 4.2.x to 7.x as originally planned to wait for WildFly). New thoughts and answers are welcome.

答:
I can only speak from production experience with JBoss 5.1.0 and some investigation of version 6.

JBoss 5 is Java EE 5 and JBoss 6 and 7 are Java EE 6. The disparity in API features is best documented in those specs. JBoss 6 is likely to have a very short shelf-life; it is only certified for the Java EE 6 web profile and bugfixes are being targeted at version 7 (in its 3rd beta at time of writing).

I think you'd get better answers on the JBoss community forum.


问:
is there a way to configure webex to automatically mute a participant when they start typing?
I would like to know if we can configure webex session to mute participants audio while they are typing.

WebEx should automatically detect typing noise and mute that audio.

答: I don't see an option to to configure webex automatically to detect if a participant is typing and mute their audio</p>


问:
Entity Framework Core OwnsOne Creates Separate Tables, Rather than adding properties to the Same Table as Expected
I thought that Entity Framework Core owned types by default get added to the same table as their owner. But I'm not seeing this in the migration.

Would someone clue me in here?

Is there a way to get the desired migration with Name properties added directly to the Person table?

```<code>public class Person
{
    public Name Name { get; set; }
}

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> person)
    {
          person.OwnsOne(p => p.Name);
    }
}
</code>```

dotnet ef migrations add DidNotSeeThatComing
results in

```<code>public partial class DidNotSeeThatComing : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Name",
            columns: table => new
            {
                FirstName = table.Column<string>(type: "varchar", nullable: true),
                LastName = table.Column<string>(type: "varchar", nullable: true),
                PersonId = table.Column<Guid>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Name", x => x.PersonId);
                table.ForeignKey(
                    name: "FK_Name_Person_PersonId",
                    column: x => x.PersonId,
                    principalTable: "Person",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });
        );
    }
}
</code>```

答:
@Davious i had exact the same problem today thanks for sharing your solution. Here is my solution where you don't need the OwnedAttribute because you can also use entity.IsOwned(). I always try to do all confiugration via the DbContext.

```<code>///[Owned] // Not needed anymore
public class Name { ... }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);
   modelbuilder.Entity<Person>().OwnsOne(p => p.Name)

   foreach (var entity in modelBuilder.Model.GetEntityTypes())
   {
       if(!entity.IsOwned())
       {
            entity.Relational().TableName = entity.Name;
       }
   }
}

</code>```

Body:
I thought that Entity Framework Core owned types by default get added to the same table as their owner. But I'm not seeing this in the migration.

Would someone clue me in here?

Is there a way to get the desired migration with Name properties added directly to the Person table?

public class Person
{
    public Name Name { get; set; }
}

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> person)
    {
          person.OwnsOne(p => p.Name);
    }
}

dotnet ef migrations add DidNotSeeThatComing
results in

public partial class DidNotSeeThatComing : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Name",
            columns: table => new
            {
                FirstName = table.Column<string>(type: "varchar", nullable: true),
                LastName = table.Column<string>(type: "varchar", nullable: true),
                PersonId = table.Column<Guid>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Name", x => x.PersonId);
                table.ForeignKey(
                    name: "FK_Name_Person_PersonId",
                    column: x => x.PersonId,
                    principalTable: "Person",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });
        );
    }
}

Body:
@Davious i had exact the same problem today thanks for sharing your solution. Here is my solution where you don't need the OwnedAttribute because you can also use entity.IsOwned(). I always try to do all confiugration via the DbContext.

///[Owned] // Not needed anymore
public class Name { ... }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);
   modelbuilder.Entity<Person>().OwnsOne(p => p.Name)

   foreach (var entity in modelBuilder.Model.GetEntityTypes())
   {
       if(!entity.IsOwned())
       {
            entity.Relational().TableName = entity.Name;
       }
   }
}