问:
Difference between InnoDB and MyISAM?

Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

```<code>$q = ("SELECT * ... );
$r = mysql_query($q);
</code>```

答:
InnoDB uses row locking, MyISAM uses
table locking, therefore...

InnoDB is slower when it comes to
SELECT

InnoDB enforces referential integrity
(which is as very good thing)

InnoDB allows transactions

Title: Difference between InnoDB and MyISAM?

Body:
Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

$q = ("SELECT * ... );
$r = mysql_query($q);


来源: stackexchange

问:
How to get a float value with a string as input parameter in Python?
I wrote the following:

```<code>def payment(order):

B = 2.00
W = 2.50
S = 1.50

order = ["B", "W", "S"]

return(order)

payment('BBSWS')
</code>```

I need to get 9.5 as output, however, my output is ('B', 'W', 'S').

What do I need to change in my code to get the right answer 9.5?

Thank you.

答:
EDITED:

def payment(order):
    total = 0
    data = {"B": 2.00, "W": 2.50, "S": 1.50}
    for i in order:
        total += data.get(i, 0)
    return total

print(payment("BBSWS"))
```

ContentLicense: CC BY-SA 4.0

Body:
I wrote the following:

def payment(order):

B = 2.00
W = 2.50
S = 1.50

order = ["B", "W", "S"]

return(order)

payment('BBSWS')

I need to get 9.5 as output, however, my output is ('B', 'W', 'S').

What do I need to change in my code to get the right answer 9.5?

Thank you.


答:
If I've understand what you mean :</p>

```<code>def payment(arg):
    letters = {'B': 2.00, 'W': 2.50, 'S': 1.50}
    order = 0
    for item, value in letters.items():
        order += arg.count(item)*value

    return(order)

print(payment('BBSWS'))
</code>```

Title: How to get a float value with a string as input parameter in Python?

Body:
If I've understand what you mean :

def payment(arg):
    letters = {'B': 2.00, 'W': 2.50, 'S': 1.50}
    order = 0
    for item, value in letters.items():
        order += arg.count(item)*value

    return(order)

print(payment('BBSWS'))


问:
Remove 5 second mana regen rule Azerothcore
I am looking to remove the 5 second rule in the code. I see a bunch of mana regen handles inside Player.cpp but i am not sure which to remove or change.

The 5 second rule is a timer to where when you do not cast a spell for 5 seconds you start to regen mana faster.

Thank you

答: just remove them all, recompile, test, if it works, then remove only half of them, recompile, test etc...</p>


问:
What is the difference between Aes and AesManaged
I found two class in C# related to AES, and example code of them MSDN provides are similar, what is the difference between these two classes?

Aes Class

https://msdn.microsoft.com/en-us/library/system.security.cryptography.aes(v=vs.110).aspx

AesManaged Class

https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged(v=vs.110).aspx

答:
While I know there is already an accepted answer, which I felt was a good start, it left me wanting to understand more why there were several implementations of Aes in .Net that all seemed to do the same thing. So, I decided to dig in a little deeper.

As mentioned the Aes class is an abstract class, so you cannot new up an implementation of this class only call the “Create” static method. This static method creates an implementation of AES based on the CryptoConfig settings, which as best as I can tell allows you to specify specific implementations in the machine config otherwise it defaults to giving you the AesCryptoServiceProvider.

The AesCryptoServiceProvider will in turn provide you with the native Cryptographic Application Programming Interfaces (CAPI) handle.

AesManaged uses one key piece of information to determine which implementation to give you and that is the AllowOnlyFipsAlgorithms flag.  According to documentation it “indicates whether the runtime should enforce the policy to create only Federal Information Processing Standard (FIPS) certified algorithms”. If it’s true then you get AesCryptoServiceProvider otherwise RijndaelManaged.

Lastly, not mentioned in the original post is the AesCng. According to Microsoft CNG is the “next generation” of the CAPI that is geared toward cloud usage scenarios.

ContentLicense: CC BY-SA 3.0


问:
Time Series Cross Validation for LASSO model
As the title might suggest, my aim is to perform a Time Series Cross Validation using a L1 penalty (Lasso).
As the data frame is a time series format, clearly the results of a time series analysis should be more appropriate than a normal cv.

Here are the lines of codes I tried

```<code>library(caret)
library(ggplot2)
library(pls)
economics
timeSlices <- createTimeSlices(1:nrow(economics),
                               initialWindow = 36, horizon = 12, fixedWindow = FALSE)
trainSlices <- timeSlices[[1]]
testSlices <- timeSlices[[2]]
</code>```

This allows to create two slices for a training set (always getting one more observations) while keeping constant the lenght of the test set.
The problem arises here

```<code>plsFitTime <- train(unemploy ~ pce + pop + psavert,
                data = economics[trainSlices[[1]],],
                method = "glmnet",
                alpha = 1)
</code>```

Here the error

Something is wrong; all the RMSE metric values are missing:

```<code>      RMSE        Rsquared        MAE
 Min.   : NA   Min.   : NA   Min.   : NA
 1st Qu.: NA   1st Qu.: NA   1st Qu.: NA
 Median : NA   Median : NA   Median : NA
 Mean   :NaN   Mean   :NaN   Mean   :NaN
 3rd Qu.: NA   3rd Qu.: NA   3rd Qu.: NA
 Max.   : NA   Max.   : NA   Max.   : NA
 NA's   :9     NA's   :9     NA's   :9
Error: Stopping
In addition: Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.
</code>```

I really don t get what might be wrong with that.

My final objective would be then to perform

```<code>pred <- predict(plsFitTime,economics[testSlices[[1]],])
true <- economics$unemploy[testSlices[[1]]]
</code>```

Any suggestion with that?

答:
If you look at the warnings:

50: model fit failed for Resample17: alpha=0.55, lambda=42.28 Error in
  (function (x, y, family = c("gaussian", "binomial", "poisson",  :

  formal argument "alpha" matched by multiple actual arguments

By default, training for glmnet is done on lambda and alpha. And the alpha you have specified clashes with that generated by caret.

If you want a fixed alpha, it should be specified in the tuneGrid.

```<code>t_grid = expand.grid(lambda=seq(0,1,by=0.1),alpha=1)
plsFitTime <- train(unemploy ~ pce + pop + psavert,
                    data = economics[trainSlices[[1]],],
                    method = "glmnet",
                    tuneGrid = t_grid)
</code>```

You can check the hyper parameters here

Body:
As the title might suggest, my aim is to perform a Time Series Cross Validation using a L1 penalty (Lasso).
As the data frame is a time series format, clearly the results of a time series analysis should be more appropriate than a normal cv.

Here are the lines of codes I tried

library(caret)
library(ggplot2)
library(pls)
economics
timeSlices <- createTimeSlices(1:nrow(economics),
                               initialWindow = 36, horizon = 12, fixedWindow = FALSE)
trainSlices <- timeSlices[[1]]
testSlices <- timeSlices[[2]]

This allows to create two slices for a training set (always getting one more observations) while keeping constant the lenght of the test set.
The problem arises here

plsFitTime <- train(unemploy ~ pce + pop + psavert,
                data = economics[trainSlices[[1]],],
                method = "glmnet",
                alpha = 1)

Here the error

Something is wrong; all the RMSE metric values are missing:

      RMSE        Rsquared        MAE
 Min.   : NA   Min.   : NA   Min.   : NA
 1st Qu.: NA   1st Qu.: NA   1st Qu.: NA
 Median : NA   Median : NA   Median : NA
 Mean   :NaN   Mean   :NaN   Mean   :NaN
 3rd Qu.: NA   3rd Qu.: NA   3rd Qu.: NA
 Max.   : NA   Max.   : NA   Max.   : NA
 NA's   :9     NA's   :9     NA's   :9
Error: Stopping
In addition: Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

I really don t get what might be wrong with that.

My final objective would be then to perform

pred <- predict(plsFitTime,economics[testSlices[[1]],])
true <- economics$unemploy[testSlices[[1]]]

Any suggestion with that?

Body:
If you look at the warnings:

50: model fit failed for Resample17: alpha=0.55, lambda=42.28 Error in
  (function (x, y, family = c("gaussian", "binomial", "poisson",  :

  formal argument "alpha" matched by multiple actual arguments

By default, training for glmnet is done on lambda and alpha. And the alpha you have specified clashes with that generated by caret.

If you want a fixed alpha, it should be specified in the tuneGrid.

t_grid = expand.grid(lambda=seq(0,1,by=0.1),alpha=1)
plsFitTime <- train(unemploy ~ pce + pop + psavert,
                    data = economics[trainSlices[[1]],],
                    method = "glmnet",
                    tuneGrid = t_grid)

You can check the hyper parameters here


问:
CloudKit CKShare userDidAcceptCloudKitShareWith Never Fires on Mac App
I am working on accepting a CKShare in a macOS app in Swift 4. I've already done all the following:

Create the CKShare and save it with its rootRecord to CloudKit

Add a participant (CKShare.Participant)

I've confirmed that the CKShare is on the CloudKit server and that the person I invited has access to it. Here's a screenshot: https://d.pr/i/0sMFQq

When I click the share link associated with the CKShare, it opens my app, but nothing happens and userDidAcceptCloudKitShareWith doesn't fire.

```<code>func application(_ application: NSApplication, userDidAcceptCloudKitShareWith metadata: CKShareMetadata) {
  print("Made it!") //<-- This never gets logged :(
  let shareOperation = CKAcceptSharesOperation(shareMetadatas: [metadata])
  shareOperation.qualityOfService = .userInteractive

  shareOperation.perShareCompletionBlock = {meta, share, error in
    print("meta \(meta)\nshare \(share)\nerror \(error)")
  }
  shareOperation.acceptSharesCompletionBlock = { error in
    if let error = error{
      print("error in accept share completion \(error)")
    }else{
      //Send your user to where they need to go in your app
      print("successful share:\n\(metadata)")
    }
  }

  CKContainer.default().add(shareOperation)
}
</code>```

Is there some kind of URL scheme I have to include in my info.plist? Or perhaps a protocol I need to conform to in my NSApplicationDelegate delegate? I can't, for the life of me, figure out what to do. Thanks in advance!

Update

I've tried a few more things on this. When I open the share link in a web browser, I see this:

Clicking OK makes the screen fade away to this:

Not particularly helpful. :) After doing this, the participant's status in CloudKit is still Invited, so the share still hasn't been accepted.

When I click on a share link within Messages, I am shown a popup like this:

After I click open, a new copy of my app shows up in the dock, then the app suddenly closes. The crash log states:

Terminating app due to uncaught exception 'CKException', reason: 'The application is missing required entitlement com.apple.developer.icloud-services'

I've tried turning iCloud off and on again in the Capabilities section of Xcode, but nothing changes. I know this exception can't be right because I can start my app normally and use CloudKit all day long. Only the CKShare causes this crash.

This is a mess. Save me, Obi-wan Kenobi, you're my only hope.

答:
If your app is a Mac Catalyst app running on any version of macOS Catalina at least up to and including 10.15.4 Beta 1, a UIApplicationDelegate  userDidAcceptCloudKitShareWith method will never be invoked.

After some significant debugging, we discovered that the MacCatalyst UIKit doesn’t even have an implementation for userDidAcceptCloudKitShareWithMetadata in its UIApplication delegate. It’s not broken, it’s just not there.  So, at least temporarily, our workaround is the following, which seems to work, even if it’s very inelegant:

```<code>// Add CloudKit sharing acceptance handling to UINSApplicationDelegate, which is missing it.
#if targetEnvironment(macCatalyst)
extension NSObject {
    @objc func application(_ application: NSObject, userDidAcceptCloudKitShareWithMetadata cloudKitShareMetadata: CKShare.Metadata) {
        YourClass.acceptCloudKitShare(cloudKitShareMetadata: cloudKitShareMetadata)
    }
}
#endif
</code>```

Body:
I am working on accepting a CKShare in a macOS app in Swift 4. I've already done all the following:

Create the CKShare and save it with its rootRecord to CloudKit

Add a participant (CKShare.Participant)

I've confirmed that the CKShare is on the CloudKit server and that the person I invited has access to it. Here's a screenshot: https://d.pr/i/0sMFQq

When I click the share link associated with the CKShare, it opens my app, but nothing happens and userDidAcceptCloudKitShareWith doesn't fire.

func application(_ application: NSApplication, userDidAcceptCloudKitShareWith metadata: CKShareMetadata) {
  print("Made it!") //<-- This never gets logged :(
  let shareOperation = CKAcceptSharesOperation(shareMetadatas: [metadata])
  shareOperation.qualityOfService = .userInteractive

  shareOperation.perShareCompletionBlock = {meta, share, error in
    print("meta \(meta)\nshare \(share)\nerror \(error)")
  }
  shareOperation.acceptSharesCompletionBlock = { error in
    if let error = error{
      print("error in accept share completion \(error)")
    }else{
      //Send your user to where they need to go in your app
      print("successful share:\n\(metadata)")
    }
  }

  CKContainer.default().add(shareOperation)
}

Is there some kind of URL scheme I have to include in my info.plist? Or perhaps a protocol I need to conform to in my NSApplicationDelegate delegate? I can't, for the life of me, figure out what to do. Thanks in advance!

Update

I've tried a few more things on this. When I open the share link in a web browser, I see this:

Clicking OK makes the screen fade away to this:

Not particularly helpful. :) After doing this, the participant's status in CloudKit is still Invited, so the share still hasn't been accepted.

When I click on a share link within Messages, I am shown a popup like this:

After I click open, a new copy of my app shows up in the dock, then the app suddenly closes. The crash log states:

Terminating app due to uncaught exception 'CKException', reason: 'The application is missing required entitlement com.apple.developer.icloud-services'

I've tried turning iCloud off and on again in the Capabilities section of Xcode, but nothing changes. I know this exception can't be right because I can start my app normally and use CloudKit all day long. Only the CKShare causes this crash.

This is a mess. Save me, Obi-wan Kenobi, you're my only hope.

Body:
If your app is a Mac Catalyst app running on any version of macOS Catalina at least up to and including 10.15.4 Beta 1, a UIApplicationDelegate  userDidAcceptCloudKitShareWith method will never be invoked.

After some significant debugging, we discovered that the MacCatalyst UIKit doesn’t even have an implementation for userDidAcceptCloudKitShareWithMetadata in its UIApplication delegate. It’s not broken, it’s just not there.  So, at least temporarily, our workaround is the following, which seems to work, even if it’s very inelegant:

// Add CloudKit sharing acceptance handling to UINSApplicationDelegate, which is missing it.
#if targetEnvironment(macCatalyst)
extension NSObject {
    @objc func application(_ application: NSObject, userDidAcceptCloudKitShareWithMetadata cloudKitShareMetadata: CKShare.Metadata) {
        YourClass.acceptCloudKitShare(cloudKitShareMetadata: cloudKitShareMetadata)
    }
}
#endif


问:
Parsing string to decimal throws a FormatException for DateTime
I have a Web project which has data of different tools, Im able to insert and delete tools into a RadGrid (which is connected to a database), but Im having issues with the edit command

One of the values of the tools is "Cost" which is decimal, when Im trying to edit, half of the time it gets me this error:

"Input String was not in correct format error"

This is my Edit Method when the user clicks on the edit form modal to submit the edit

```<code>protected void btnMdlEditar_OnClick(object sender, EventArgs e)
       {
           NumberStyles style;
           CultureInfo provider;
           style = NumberStyles.AllowDecimalPoint;
           provider = new CultureInfo("en-US");
           decimal costoDecimal;
           var costo = editCosto.Text;
           costoDecimal = decimal.Parse(costo.ToString(),style,provider);
           try
           {
               var id = CDatos.DHerramientas.UpdateHerramientas(int.Parse(txtId.Text), editCodigo.Text, editNombreCorto.Text, editDescripcion.Text, costoDecimal, editConsumible.Text);
               rgHerramientas.DataBind();
               rgHerramientas.Rebind();
               upHerramientas.Update();
               this.ShowMessage(Resources.Language.mess_insert, "success");

           }
           catch (Exception ex) { this.ShowMessage(ex.Message, "danger"); }
           this.CloseModal("mdlHerramientaEdit");
       }
</code>```

In the line

costoDecimal = decimal.Parse(costo.ToString(),style,provider);

Is where I get the error, with a FormatException poping up, mentioning an issue while parsing a string to DataTime, for some reason.
I have no idea why Im getting this error when Im using the exact code to parse decimal from string in my Insert Method

```<code>protected void btnAutorizar_OnClick(object sender, EventArgs e)
       {
           NumberStyles style;
           CultureInfo provider;
           style = NumberStyles.AllowDecimalPoint;
           provider = new CultureInfo("en-US");
           decimal costoDecimal;
           var costo = txtCosto.Text;
           costoDecimal = decimal.Parse(costo.ToString(),style,provider);
           try
           {

               var id = CDatos.DHerramientas.InsertHerramientas(txtCodigo.Text, txtNombreCorto.Text, txtDescripcion.Text, costoDecimal, txtConsumible.Text);
               this.upDatos.Update();
               this.ShowMessage(Resources.Language.mess_insert, "success");

           }
           catch (Exception ex){this.ShowMessage(ex.Message, "danger"); }
           this.CloseModal("mdlHerramienta");
       }
</code>```

When I edit the data by only deleting some a part of the number or when the number is not changed it throws the error, but if I delete the number completely and enter another decimal number, it allows me to edit it

```<code>7.85 to 7.89 = Error

7.85 to 6.12 = No error
</code>```

Im already have

using System.Globalization;

And my current culture is "es-ES"

Edit:
I tried to delete the "provider" from

costoDecimal = decimal.Parse(costo.ToString(), style, provider);
  which allows me to edit succesfully if I only change part of the number, but if I type a new number using "." it throws me the error again

I think the issue is using "." instead of "," which is the method used in Spain for decimals, is there a way to use both "." and ","?

答:
Got it, the issue origin was using "," instead of "."

Because of the nature of my project I have to use culture as "es-ES" for the entire project.

If "." was used instead of "," it threw the error, so to be able for the users to use "." and the system to use "," I had to change the code

```<code>protected void btnMdlEditar_OnClick(object sender, EventArgs e)
        {
            NumberStyles style;
            CultureInfo provider;
            style = NumberStyles.AllowDecimalPoint;
            provider = new CultureInfo("en-US");
            decimal costoDecimal = 0;
            var costo = editCosto.Text;
            if (editCosto.Text.Contains("."))
            {
                costoDecimal = decimal.Parse(costo.ToString(), style, provider);
            }
            else if (editCosto.Text.Contains(","))
            {
                costoDecimal = decimal.Parse(costo.ToString(), style);
            }

            try
            {
                var id = CDatos.DHerramientas.UpdateHerramientas(int.Parse(txtId.Text), editCodigo.Text, editNombreCorto.Text, editDescripcion.Text, costoDecimal, editConsumible.Text);
                rgHerramientas.DataBind();
                rgHerramientas.Rebind();
                upHerramientas.Update();
                this.ShowMessage(Resources.Language.mess_insert, "success");

            }
            catch (Exception ex) { this.ShowMessage(ex.Message, "danger"); }
            this.CloseModal("mdlHerramientaEdit");
        }
</code>```

Changing the culture depending if "," or "." was used

Body:
I have a Web project which has data of different tools, Im able to insert and delete tools into a RadGrid (which is connected to a database), but Im having issues with the edit command

One of the values of the tools is "Cost" which is decimal, when Im trying to edit, half of the time it gets me this error:

"Input String was not in correct format error"

This is my Edit Method when the user clicks on the edit form modal to submit the edit

protected void btnMdlEditar_OnClick(object sender, EventArgs e)
       {
           NumberStyles style;
           CultureInfo provider;
           style = NumberStyles.AllowDecimalPoint;
           provider = new CultureInfo("en-US");
           decimal costoDecimal;
           var costo = editCosto.Text;
           costoDecimal = decimal.Parse(costo.ToString(),style,provider);
           try
           {
               var id = CDatos.DHerramientas.UpdateHerramientas(int.Parse(txtId.Text), editCodigo.Text, editNombreCorto.Text, editDescripcion.Text, costoDecimal, editConsumible.Text);
               rgHerramientas.DataBind();
               rgHerramientas.Rebind();
               upHerramientas.Update();
               this.ShowMessage(Resources.Language.mess_insert, "success");

           }
           catch (Exception ex) { this.ShowMessage(ex.Message, "danger"); }
           this.CloseModal("mdlHerramientaEdit");
       }

In the line

costoDecimal = decimal.Parse(costo.ToString(),style,provider);

Is where I get the error, with a FormatException poping up, mentioning an issue while parsing a string to DataTime, for some reason.
I have no idea why Im getting this error when Im using the exact code to parse decimal from string in my Insert Method

protected void btnAutorizar_OnClick(object sender, EventArgs e)
       {
           NumberStyles style;
           CultureInfo provider;
           style = NumberStyles.AllowDecimalPoint;
           provider = new CultureInfo("en-US");
           decimal costoDecimal;
           var costo = txtCosto.Text;
           costoDecimal = decimal.Parse(costo.ToString(),style,provider);
           try
           {

               var id = CDatos.DHerramientas.InsertHerramientas(txtCodigo.Text, txtNombreCorto.Text, txtDescripcion.Text, costoDecimal, txtConsumible.Text);
               this.upDatos.Update();
               this.ShowMessage(Resources.Language.mess_insert, "success");

           }
           catch (Exception ex){this.ShowMessage(ex.Message, "danger"); }
           this.CloseModal("mdlHerramienta");
       }

When I edit the data by only deleting some a part of the number or when the number is not changed it throws the error, but if I delete the number completely and enter another decimal number, it allows me to edit it

7.85 to 7.89 = Error

7.85 to 6.12 = No error

Im already have

using System.Globalization;

And my current culture is "es-ES"

Edit:
I tried to delete the "provider" from

costoDecimal = decimal.Parse(costo.ToString(), style, provider);
  which allows me to edit succesfully if I only change part of the number, but if I type a new number using "." it throws me the error again

I think the issue is using "." instead of "," which is the method used in Spain for decimals, is there a way to use both "." and ","?

Body:
Got it, the issue origin was using "," instead of "."

Because of the nature of my project I have to use culture as "es-ES" for the entire project.

If "." was used instead of "," it threw the error, so to be able for the users to use "." and the system to use "," I had to change the code

protected void btnMdlEditar_OnClick(object sender, EventArgs e)
        {
            NumberStyles style;
            CultureInfo provider;
            style = NumberStyles.AllowDecimalPoint;
            provider = new CultureInfo("en-US");
            decimal costoDecimal = 0;
            var costo = editCosto.Text;
            if (editCosto.Text.Contains("."))
            {
                costoDecimal = decimal.Parse(costo.ToString(), style, provider);
            }
            else if (editCosto.Text.Contains(","))
            {
                costoDecimal = decimal.Parse(costo.ToString(), style);
            }

            try
            {
                var id = CDatos.DHerramientas.UpdateHerramientas(int.Parse(txtId.Text), editCodigo.Text, editNombreCorto.Text, editDescripcion.Text, costoDecimal, editConsumible.Text);
                rgHerramientas.DataBind();
                rgHerramientas.Rebind();
                upHerramientas.Update();
                this.ShowMessage(Resources.Language.mess_insert, "success");

            }
            catch (Exception ex) { this.ShowMessage(ex.Message, "danger"); }
            this.CloseModal("mdlHerramientaEdit");
        }

Changing the culture depending if "," or "." was used


问:
TypeError: expected string when using re.findall on web page text -- why?
I'm trying to learn how to screen-scrape with BeautifulSoup.

```<code>from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()

patFinderTitle = re.compile('<h4 class="itemtitle"><a href=(.*)</a></h4>')

findPatTitle = re.findall(patFinderTitle,webpage)
listIterator = []
listIterator[:] = range(1, 5)

for i in listIterator:
    print findPatTitle[i]
    print("\n")
</code>```

Error

```<code>Traceback (most recent call last):
File "//da-srv1/users/xxxxx/Desktop/fetcher", line 14, in <module>
print findPatTitle[i]
**IndexError: list index out of range**
</code>```

答:
Use the following expression:

```<code>patFinderTitle.findall(webpage)
</code>```

You can't do the equivalent of re.findall(re.compile(<expression>), <string>) since re.findall only accepts a regular expression as a string -- and re.compile(<expression>) returns a compiled regex object. So you need to use your compiled regex object patFinderTitle and call its findall() method (see above).

EDIT: Oh. Turns out you can do re.findall(re.compile(<expression>), <string>). The more you know.

Body:
I'm trying to learn how to screen-scrape with BeautifulSoup.

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()

patFinderTitle = re.compile('
<a href=(.*)
')

findPatTitle = re.findall(patFinderTitle,webpage)
listIterator = []
listIterator[:] = range(1, 5)

for i in listIterator:
    print findPatTitle[i]
    print("\n")

Error

Traceback (most recent call last):
File "//da-srv1/users/xxxxx/Desktop/fetcher", line 14, in <module>
print findPatTitle[i]
**IndexError: list index out of range**

Body:
Use the following expression:

patFinderTitle.findall(webpage)

You can't do the equivalent of re.findall(re.compile(<expression>), <string>) since re.findall only accepts a regular expression as a string -- and re.compile(<expression>) returns a compiled regex object. So you need to use your compiled regex object patFinderTitle and call its findall() method (see above).

EDIT: Oh. Turns out you can do re.findall(re.compile(<expression>), <string>). The more you know.


问:
Perl angle brackets in regex substitution
I have encountered the following code:

```<code>my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;
</code>```

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

```<code>$string =~ s/(\d+)/$1\./g;
</code>```

What do angle brackets mean?

答:
Perl documentation for regex specifies delimiter characters. A few possible cases usage of different delimiters

```<code>$string =~ s/pattern/replacement/g;
$string =~ s{pattern}{replacement}g;
$string =~ s!pattern!replacement!g;
$string =~ s|pattern|replacement|g;
$string =~ s<pattern><replacement>g;
$string =~ s#pattern#replacement#g;
$string =~ s'pattern'replacement'g;
$string =~ s,pattern,replacement,g;
</code>```

Most common used delimiter is / but in some situations it's usage make pattern less readable

```<code>$path = '/home/user1/dir1/dir2';
</code>```

compare these three

```<code>$path =~ s/user1\/dir1\/dir2/user2\/dir3\/dir4/;
$path =~ s!user/dir1/dir2!user2/dir3/dir4!;
$path =~ s#user/dir1/dir2#user2/dir3/dir4#;
</code>```

Please see perlrequick documentation to understand regular expressions and what symbols can be used as delimiters.

Perhaps you will find following website useful in your study perl programming.

Tutorial perl regular expressions

Stackoverflow question 21335765

Body:
I have encountered the following code:

my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

$string =~ s/(\d+)/$1\./g;

What do angle brackets mean?

Body:
Perl documentation for regex specifies delimiter characters. A few possible cases usage of different delimiters

$string =~ s/pattern/replacement/g;
$string =~ s{pattern}{replacement}g;
$string =~ s!pattern!replacement!g;
$string =~ s|pattern|replacement|g;
$string =~ s<pattern><replacement>g;
$string =~ s#pattern#replacement#g;
$string =~ s'pattern'replacement'g;
$string =~ s,pattern,replacement,g;

Most common used delimiter is / but in some situations it's usage make pattern less readable

$path = '/home/user1/dir1/dir2';

compare these three

$path =~ s/user1\/dir1\/dir2/user2\/dir3\/dir4/;
$path =~ s!user/dir1/dir2!user2/dir3/dir4!;
$path =~ s#user/dir1/dir2#user2/dir3/dir4#;

Please see perlrequick documentation to understand regular expressions and what symbols can be used as delimiters.

Perhaps you will find following website useful in your study perl programming.

Tutorial perl regular expressions

Stackoverflow question 21335765


问:
Why can SMTP APIs use any from address? How can I blacklist my email?
I'm using SendGrid's SMTP API, and I realized that I can set the from address to any email.

I find this concerning. It's very clear that anybody with an SMTP API could just start sending emails pretending to be me.

Is there a way I can add my email or a group of emails to an "SMTP Blacklist"?

```<code>from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='any@from.email',
    to_emails='any@to.email',
    subject='Title',
    html_content='Hello world')
try:
    sg = SendGridAPIClient('FREE_API_KEY')
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
</code>```

答:
Read up on DMARC and SPF Records. These two "solutions" make it much more difficult for unauthorized email to get delivered successfully.

EDIT: Also read up on DKIM.

Body:
I'm using SendGrid's SMTP API, and I realized that I can set the from address to any email.

I find this concerning. It's very clear that anybody with an SMTP API could just start sending emails pretending to be me.

Is there a way I can add my email or a group of emails to an "SMTP Blacklist"?

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='any@from.email',
    to_emails='any@to.email',
    subject='Title',
    html_content='Hello world')
try:
    sg = SendGridAPIClient('FREE_API_KEY')
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)


问:
How to declare inheritance of uicontrol objects in MATLAB
I'm learning how to programmatically create an app in MATLAB with a graphical user interface. I'm using MATLAB 2015a.

I don't understand why I am getting this error:

```<code>Error using GuiTitle
The specified superclass 'uicontrol' contains a parse error, cannot be found on MATLAB's search path, or
is shadowed by another file with the same name.
</code>```

I'm trying to make a class called GuiTitle that has uicontrol as the superclass. My class GuiTitle looks like this:

```<code>classdef GuiTitle < uicontrol
    methods
        function obj = GuiTitle(text)
            if nargin == 0
                text = '';
            end

            obj@uicontrol('Style', 'text', 'String', upper(text));
        end
    end
end
</code>```

Here is my code:

```<code>function hello_gui
% Test GUI

GuiConstants % contains constants that
GuiTitle %%

f = figure('Visible','off','Position',[POS_FROM_LEFT,POS_FROM_BOTTOM,...
                                       WINDOW_WIDTH,WINDOW_HEIGHT]);
set(f, 'MenuBar', 'none')

titleText    = 'process variable names';

%title = uicontrol('Style', 'text', 'String', upper(titleText));

title        = GuiTitle(titleText) %%

title.Position = [0, 0, WINDOW_WIDTH, WINDOW_HEIGHT];
title.FontSize = FONT_SIZE;

f.Visible = 'on';

end
</code>```

When I comment out lines with %% and uncomment

```<code>title = uicontrol('Style', 'text', 'String', upper(titleText));
</code>```

The window displays properly:

What am I missing?

答:
uicontrol is a function that creates an object of type matlab.ui.control.UIControl:

h = uicontrol;
class(h)    % returns 'matlab.ui.control.UIControl'
```

<p>However, this class is sealed and cannot be used as a superclass:</p>

<pre class="lang-matlab prettyprint-override"><code>classdef myclass < matlab.ui.control.UIControl
   ...
</code>```

```<code>>> a=myclass
Error using myclass
Class 'matlab.ui.control.UIControl' is Sealed and may not be used as a superclass.
</code>```

Note that GUIs in MATLAB are designed very differently from what you might be used in other languages. There is no need to derive from UI classes to change their behavior, you define their behavior by setting callback functions:

h = uicontrol;
h.String = 'button';
h.Callback = @(src,event) msgbox('pressed the button!');
```

Body:
I'm learning how to programmatically create an app in MATLAB with a graphical user interface. I'm using MATLAB 2015a.

I don't understand why I am getting this error:

Error using GuiTitle
The specified superclass 'uicontrol' contains a parse error, cannot be found on MATLAB's search path, or
is shadowed by another file with the same name.

I'm trying to make a class called GuiTitle that has uicontrol as the superclass. My class GuiTitle looks like this:

classdef GuiTitle < uicontrol
    methods
        function obj = GuiTitle(text)
            if nargin == 0
                text = '';
            end

            obj@uicontrol('Style', 'text', 'String', upper(text));
        end
    end
end

Here is my code:

function hello_gui
% Test GUI

GuiConstants % contains constants that
GuiTitle %%

f = figure('Visible','off','Position',[POS_FROM_LEFT,POS_FROM_BOTTOM,...
                                       WINDOW_WIDTH,WINDOW_HEIGHT]);
set(f, 'MenuBar', 'none')

titleText    = 'process variable names';

%title = uicontrol('Style', 'text', 'String', upper(titleText));

title        = GuiTitle(titleText) %%

title.Position = [0, 0, WINDOW_WIDTH, WINDOW_HEIGHT];
title.FontSize = FONT_SIZE;

f.Visible = 'on';

end

When I comment out lines with %% and uncomment

title = uicontrol('Style', 'text', 'String', upper(titleText));

The window displays properly:

What am I missing?

Body:
uicontrol is a function that creates an object of type matlab.ui.control.UIControl:

h = uicontrol;
class(h)    % returns 'matlab.ui.control.UIControl'

However, this class is sealed and cannot be used as a superclass:

classdef myclass < matlab.ui.control.UIControl
   ...

>> a=myclass
Error using myclass
Class 'matlab.ui.control.UIControl' is Sealed and may not be used as a superclass.

Note that GUIs in MATLAB are designed very differently from what you might be used in other languages. There is no need to derive from UI classes to change their behavior, you define their behavior by setting callback functions:

h = uicontrol;
h.String = 'button';
h.Callback = @(src,event) msgbox('pressed the button!');


问:
Using Tensorflow Interleave to Improve Performance
I have an input pipe that is performing poorly with low CPU, GPU, and disk utilization. I've been reading the tensorflow "Better performance with tf.data API" doc and the Dataset docs, but I don't understand what's going on well enough to apply it to my situation. Here's my current setup:

```<code>img_files = sorted(tf.io.gfile.glob(...))
imgd = tf.data.FixedLengthRecordDataset(img_files, inrez*inrez)
#POINT1A
imgd = imgd.map(lambda s: tf.reshape(tf.io.decode_raw(s, tf.int8), (inrez,inrez,1)))
imgd = imgd.map(lambda x: tf.cast(x, dtype=tf.float32))

out_files = sorted(tf.io.gfile.glob(...))
outd = tf.data.FixedLengthRecordDataset(out_files, 4, compression_type="GZIP")
#POINT1B
outd = outd.map(lambda s: tf.io.decode_raw(s, tf.float32))

xsrc = tf.data.Dataset.zip((imgd, outd)).batch(batchsize)
xsrc = xsrc.repeat()        # indefinitely
#POINT2
xsrc = xsrc.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
</code>```

Should I interleave the whole pipe right at the end (POINT2), before the prefetch? Or interleave imgd and outd separately, after each FixedLengthRecordDataset (POINT1A, POINT1B), and parallelize the maps? (need to keep the imgd and outd synced up!) What's up with Dataset.range(rvalue)---seems it's necessary but not obvious what rvalue to use? Is there a better overall plan?

Note that the datasets are very large and do not fit in RAM.

答:
Interleave lets you process each file in a separate logical thread (in parallel), then combine the data from the files into a single dataset. Since your data comes from two corresponding files, you need to be careful to preserve the order.

Here is an example of how you could put the interleave near the end of the dataset:

```<code>img_files = ...
out_files = ...
files = tf.data.Dataset.zip(img_files, out_files)

def parse_img_file(img_file):
  imgd = tf.data.FixedLengthRecordDataset(img_files, inrez*inrez)
  ...

def parse_out_file(out_file):
  ...

def parse_files_fn(img_file, out_file):
  img_file_dataset = parse_img_file(img_file)
  out_file_dataset = parse_out_file(out_file)
  return tf.data.Dataset.zip(img_file_dataset, out_file_dataset)

dataset = files.interleave(parse_files_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.repeat()
</code>```

Each thread of the interleave will produce elements from a different pair of (img, out) files, and the elements produced from each pair of files will be interleaved together.

Body:
I have an input pipe that is performing poorly with low CPU, GPU, and disk utilization. I've been reading the tensorflow "Better performance with tf.data API" doc and the Dataset docs, but I don't understand what's going on well enough to apply it to my situation. Here's my current setup:

img_files = sorted(tf.io.gfile.glob(...))
imgd = tf.data.FixedLengthRecordDataset(img_files, inrez*inrez)
#POINT1A
imgd = imgd.map(lambda s: tf.reshape(tf.io.decode_raw(s, tf.int8), (inrez,inrez,1)))
imgd = imgd.map(lambda x: tf.cast(x, dtype=tf.float32))

out_files = sorted(tf.io.gfile.glob(...))
outd = tf.data.FixedLengthRecordDataset(out_files, 4, compression_type="GZIP")
#POINT1B
outd = outd.map(lambda s: tf.io.decode_raw(s, tf.float32))

xsrc = tf.data.Dataset.zip((imgd, outd)).batch(batchsize)
xsrc = xsrc.repeat()        # indefinitely
#POINT2
xsrc = xsrc.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)

Should I interleave the whole pipe right at the end (POINT2), before the prefetch? Or interleave imgd and outd separately, after each FixedLengthRecordDataset (POINT1A, POINT1B), and parallelize the maps? (need to keep the imgd and outd synced up!) What's up with Dataset.range(rvalue)---seems it's necessary but not obvious what rvalue to use? Is there a better overall plan?

Note that the datasets are very large and do not fit in RAM.

Body:
Interleave lets you process each file in a separate logical thread (in parallel), then combine the data from the files into a single dataset. Since your data comes from two corresponding files, you need to be careful to preserve the order.

Here is an example of how you could put the interleave near the end of the dataset:

img_files = ...
out_files = ...
files = tf.data.Dataset.zip(img_files, out_files)

def parse_img_file(img_file):
  imgd = tf.data.FixedLengthRecordDataset(img_files, inrez*inrez)
  ...

def parse_out_file(out_file):
  ...

def parse_files_fn(img_file, out_file):
  img_file_dataset = parse_img_file(img_file)
  out_file_dataset = parse_out_file(out_file)
  return tf.data.Dataset.zip(img_file_dataset, out_file_dataset)

dataset = files.interleave(parse_files_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.repeat()

Each thread of the interleave will produce elements from a different pair of (img, out) files, and the elements produced from each pair of files will be interleaved together.


问:
Show hidden div in order
I have this code:

CODE

$('button').click(function(){
    var a = $(this).text();
    $('.'+a).show();
    $('.'+a).css("order", "1");

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <div class='1' style='display:none'><input type='text' value='1'></input>
  </div>
  <div class='2' style='display:none'><input type='text' value='2'></input>
  </div>
  <div class='3' style='display:none'><input type='text' value='3'></input>
  </div>

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

I need them to be in the order in which I click the button.
I tried to use .css('order','1'), but it doesn't seem to work

答:
https://jsfiddle.net/fxsa3e85/3/

$( 'button' ).click(function() {

  console.log( $( ".div[style*='display: unset']" ).length );

  var a = $( this ).text();
  $( '.' + a ).css( "display", "unset" );
  $( '.' + a ).css( "order", $( ".div[style*='display: unset']" ).length + 1 );

} );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="orders" style="display:grid">
  <div class="div 1" style="display: none"><input type="text" value="1"></div>
  <div class="div 2" style="display: none"><input type="text" value="2"></div>
  <div class="div 3" style="display: none"><input type="text" value="3"></div>
</div>

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

Title: Show hidden div in order

Body:
I have this code:

CODE

$('button').click(function(){
    var a = $(this).text();
    $('.'+a).show();
    $('.'+a).css("order", "1");

});

<input type='text' value='1'></input>

<input type='text' value='2'></input>

<input type='text' value='3'></input>

  <button>1</button>
  <button>2</button>
  <button>3</button>

I need them to be in the order in which I click the button.
I tried to use .css('order','1'), but it doesn't seem to work

Body:
https://jsfiddle.net/fxsa3e85/3/

$( 'button' ).click(function() {

  console.log( $( ".div[style*='display: unset']" ).length );

  var a = $( this ).text();
  $( '.' + a ).css( "display", "unset" );
  $( '.' + a ).css( "order", $( ".div[style*='display: unset']" ).length + 1 );

} );

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

<div id="orders" style="display:grid">
  <div class="div 1" style="display: none"><input type="text" value="1"></div>
  <div class="div 2" style="display: none"><input type="text" value="2"></div>
  <div class="div 3" style="display: none"><input type="text" value="3"></div>
</div>

<button>1</button>
<button>2</button>
<button>3</button>


问:
Implementing Event Handler in React
I only recently started coding in React and I'm in need of some assistance. I'm building a simple calculator and I'm trying to pass an event handler to a child component. In the flow of the app, the App component is the parent component. It houses a child "Button Panel" component, which in turn houses child "Button" components as follows:

```<code>import React from 'react';
import Display from './display';
import ButtonPanel from './button-panel';
import method from '../logic/calculate';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      total: null,
      next: null,
      operation: null,
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(buttonName) {
    // Updates this.state based on buttonName
  }

  render() {
    const { total } = this.state;
    return (
      <div id="app">
        <Display result={total} />
        <ButtonPanel onClick={this.handleClick} />
      </div>
    );
  }
}

export default App;

------------------------------------------------------------------------------------------------

import React from 'react';
import PropTypes from 'prop-types';
import Button from './button';

class ButtonPanel extends React.Component {
  constructor(props) {
    super(props);
    this.passInfo = this.passInfo.bind(this);
  }

  passInfo(buttonName) {
    const { handleClick } = this.props;
    handleClick(buttonName);
  }

  render() {
    return (
      <div>
        <div className="panel-row">
          <Button name="AC" color="white" onClick={this.passInfo} />
          <Button name="+/-" color="white" onClick={this.passInfo} />
          <Button name="%" color="white" onClick={this.passInfo} />
          <Button name="/" onClick={this.passInfo} />
        </div>
        <div className="panel-row">
          <Button name="7" color="white" onClick={this.passInfo} />
          <Button name="8" color="white" onClick={this.passInfo} />
          <Button name="9" color="white" onClick={this.passInfo} />
          <Button name="X" />
        </div>
        <div className="panel-row">
          <Button name="4" color="white" onClick={this.passInfo} />
          <Button name="5" color="white" onClick={this.passInfo} />
          <Button name="6" color="white" onClick={this.passInfo} />
          <Button name="-" onClick={this.passInfo} />
        </div>
        <div className="panel-row">
          <Button name="1" color="white" onClick={this.passInfo} />
          <Button name="2" color="white" onClick={this.passInfo} />
          <Button name="3" color="white" onClick={this.passInfo} />
          <Button name="+" />
        </div>
        <div className="panel-row">
          <Button name="0" color="white" wide onClick={this.passInfo} />
          <Button name="." color="white" onClick={this.passInfo} />
          <Button name="=" onClick={this.passInfo} />
        </div>
      </div>
    );
  }
}

ButtonPanel.propTypes = {
  handleClick: PropTypes.func.isRequired,
};

export default ButtonPanel;

------------------------------------------------------------------------------------------------

import React from 'react';
import PropTypes from 'prop-types';

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.namePass = this.namePass.bind(this);
  }

  namePass(e) {
    const { name } = e.target;
    const { handleClick } = this.props;
    handleClick(name);
  }

  render() {
    const { name, color, wide } = this.props;
    const classes = color === 'white' && wide ? 'white wide' : color;
    return (
      <div
        className={classes}
        onClick={this.namePass}
        onKeyPress={this.namePass}
        role="button"
        tabIndex="-1"
      >
        {name}
      </div>
    );
  }
}

Button.propTypes = {
  name: PropTypes.string.isRequired,
  color: PropTypes.string,
  wide: PropTypes.bool,
  handleClick: PropTypes.func.isRequired,
};
Button.defaultProps = {
  color: 'orange',
  wide: false,
};

export default Button;

</code>```

(please excuse the hard-coding, I'm trying to get everything working before refactoring).

At the moment though, I'm getting the following errors:

1) "Warning: Failed prop type: The prop handleClick is marked as required in ButtonPanel, but its value is undefined in ButtonPanel"

2) "Warning: Failed prop type: The prop handleClick is marked as required in Button, but its value is undefined in Button"

Any assistance in solving this would be greatly appreciated.

答:
Change handleClick in proptypes to onClick OR rename onClick to handleClick.

The warning is coming from Proptypes. It is expecting handleClick prop for both custom components but you are using onClick instead.

I would go with the latter as onClick is normally a default prop for many elements.

```<code>ButtonPanel.propTypes = {
  onClick: PropTypes.func.isRequired,
};

Button.propTypes = {
  onClick: PropTypes.func.isRequired,
  ...
};
</code>```

OR

```<code><ButtonPanel handleClick={this.handleClick} />
<Button handleClick={this.handleClick} ..... />
</code>```

Title: Implementing Event Handler in React

Body:
I only recently started coding in React and I'm in need of some assistance. I'm building a simple calculator and I'm trying to pass an event handler to a child component. In the flow of the app, the App component is the parent component. It houses a child "Button Panel" component, which in turn houses child "Button" components as follows:

import React from 'react';
import Display from './display';
import ButtonPanel from './button-panel';
import method from '../logic/calculate';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      total: null,
      next: null,
      operation: null,
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(buttonName) {
    // Updates this.state based on buttonName
  }

  render() {
    const { total } = this.state;
    return (

        <Display result={total} />
        <ButtonPanel onClick={this.handleClick} />

    );
  }
}

export default App;

------------------------------------------------------------------------------------------------

import React from 'react';
import PropTypes from 'prop-types';
import Button from './button';

class ButtonPanel extends React.Component {
  constructor(props) {
    super(props);
    this.passInfo = this.passInfo.bind(this);
  }

  passInfo(buttonName) {
    const { handleClick } = this.props;
    handleClick(buttonName);
  }

  render() {
    return (

          <Button name="AC" color="white" onClick={this.passInfo} />
          <Button name="+/-" color="white" onClick={this.passInfo} />
          <Button name="%" color="white" onClick={this.passInfo} />
          <Button name="/" onClick={this.passInfo} />

          <Button name="7" color="white" onClick={this.passInfo} />
          <Button name="8" color="white" onClick={this.passInfo} />
          <Button name="9" color="white" onClick={this.passInfo} />
          <Button name="X" />

          <Button name="4" color="white" onClick={this.passInfo} />
          <Button name="5" color="white" onClick={this.passInfo} />
          <Button name="6" color="white" onClick={this.passInfo} />
          <Button name="-" onClick={this.passInfo} />

          <Button name="1" color="white" onClick={this.passInfo} />
          <Button name="2" color="white" onClick={this.passInfo} />
          <Button name="3" color="white" onClick={this.passInfo} />
          <Button name="+" />

          <Button name="0" color="white" wide onClick={this.passInfo} />
          <Button name="." color="white" onClick={this.passInfo} />
          <Button name="=" onClick={this.passInfo} />

    );
  }
}

ButtonPanel.propTypes = {
  handleClick: PropTypes.func.isRequired,
};

export default ButtonPanel;

------------------------------------------------------------------------------------------------

import React from 'react';
import PropTypes from 'prop-types';

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.namePass = this.namePass.bind(this);
  }

  namePass(e) {
    const { name } = e.target;
    const { handleClick } = this.props;
    handleClick(name);
  }

  render() {
    const { name, color, wide } = this.props;
    const classes = color === 'white' && wide ? 'white wide' : color;
    return (

        {name}

    );
  }
}

Button.propTypes = {
  name: PropTypes.string.isRequired,
  color: PropTypes.string,
  wide: PropTypes.bool,
  handleClick: PropTypes.func.isRequired,
};
Button.defaultProps = {
  color: 'orange',
  wide: false,
};

export default Button;

(please excuse the hard-coding, I'm trying to get everything working before refactoring).

At the moment though, I'm getting the following errors:

1) "Warning: Failed prop type: The prop handleClick is marked as required in ButtonPanel, but its value is undefined in ButtonPanel"

2) "Warning: Failed prop type: The prop handleClick is marked as required in Button, but its value is undefined in Button"

Any assistance in solving this would be greatly appreciated.

Body:
Change handleClick in proptypes to onClick OR rename onClick to handleClick.

The warning is coming from Proptypes. It is expecting handleClick prop for both custom components but you are using onClick instead.

I would go with the latter as onClick is normally a default prop for many elements.

ButtonPanel.propTypes = {
  onClick: PropTypes.func.isRequired,
};

Button.propTypes = {
  onClick: PropTypes.func.isRequired,
  ...
};

OR

<ButtonPanel handleClick={this.handleClick} />
<Button handleClick={this.handleClick} ..... />


问:
Clustered hibernate cache with ehcache: nonstrict vs. strict read write
What is the real difference between nonstrict-read-write and read-write? I can read ehcache and Hibernate docs, but as far as I can see they only say that "read-write is better if you do updates". I find it unsatisfactory.

I may have an issue with long-lived cached collection configured like this:

```<code><cache name="trx.domain.Parent.children" maxElementsInMemory="5000"
    eternal="false" overflowToDisk="false" timeToIdleSeconds="1200"
    timeToLiveSeconds="1800">
    <cacheEventListenerFactory
        class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
        properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true" />
</code>```

```<code><set name="children" lazy="false" inverse="true">
    <cache usage="nonstrict-read-write"/>
    <key column="callout_id" />
    <one-to-many class="Child" />
</set>
</code>```

What exactly happens when the collection is updated, on the node where the update occurs and others? What is the difference between nonstrict-read-write and read-write here? Is it possible that a node will use its stale 10-minute version from cache?

Note the lengthy timeouts and asynchronous replication.

答:
Read-write: if two transactions tries to modify data, then these transactions are isolated at the "read committed" level (or repeatable read, if database is set to that) - usually that's enough, typically we don't need "serializable" isolation level.

Nonstrict read-write: cache is not locked at all, so if two transactions modify data we never know what we get, we don't have guarantee that cache state = database state.

This is safe only if it is very unlikely that data would be modified simultaneously by two transactions. We need to set appropriate cache timeout too.

For more details and a very good explanation look here: hibernate cache strategy

ContentLicense: CC BY-SA 2.5

Body:
What is the real difference between nonstrict-read-write and read-write? I can read ehcache and Hibernate docs, but as far as I can see they only say that "read-write is better if you do updates". I find it unsatisfactory.

I may have an issue with long-lived cached collection configured like this:

<cache name="trx.domain.Parent.children" maxElementsInMemory="5000"
    eternal="false" overflowToDisk="false" timeToIdleSeconds="1200"
    timeToLiveSeconds="1800">
    <cacheEventListenerFactory
        class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
        properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true" />

<set name="children" lazy="false" inverse="true">
    <cache usage="nonstrict-read-write"/>
    <key column="callout_id" />
    <one-to-many class="Child" />
</set>

What exactly happens when the collection is updated, on the node where the update occurs and others? What is the difference between nonstrict-read-write and read-write here? Is it possible that a node will use its stale 10-minute version from cache?

Note the lengthy timeouts and asynchronous replication.


问:
Getting non-zero data and positions from 2D array in Python
I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

```<code>import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))
</code>```

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

答:
```<code>print(list(zip(*np.nonzero(groupMatrix),groupMatrix[groupMatrix!=0])))
</code>```

This is certainly not the most efficient solution (it replicates the search for nonzero elements), but it works just fine.

Body:
I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

Body:
print(list(zip(*np.nonzero(groupMatrix),groupMatrix[groupMatrix!=0])))

This is certainly not the most efficient solution (it replicates the search for nonzero elements), but it works just fine.


问:
Split array into different size chunks (4, 3, 3, 3, 4, 3, 3, 3, etc)
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

```<code>[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]
</code>```

I have tried with this code I have customized:

```<code>const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);
</code>```

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

```<code>[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]
</code>```

答:
Mod operator to check if it should be 4 or 3. Use two arrays just to make it easier (can be done with one)

const groupIt = arr => arr.reduce(({
  group,
  out
}, v, i) => {
  var max = out.length % 4 === 0 ? 4 : 3
  group.push(v)
  if (group.length === max || i === arr.length - 1) {
    out.push(group)
    group = []
  }
  return {
    group,
    out
  }
}, {
  group: [],
  out: []
}).out

console.log(groupIt([1, 2, 3, 4, 5, 6, 7, 8]))

var test = (new Array(30)).fill(0).map((x,i) => i + 1)
console.log(groupIt(test))```
</div>
</div>
</p>

<p>with just one:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const groupIt = arr => arr.reduce((out, v, i) => {
  var max = (out.length - 1) % 4 === 0 ? 4 : 3
  out[out.length - 1].push(v)
  if (out[out.length - 1].length === max) {
    out.push([])
  }
  return out
}, [[]])

console.log(groupIt([1, 2, 3, 4, 5, 6, 7, 8]))

var test = (new Array(30)).fill(0).map((x, i) => i + 1)
console.log(groupIt(test))</code>```

Body:
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]

I have tried with this code I have customized:

const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]

Body:
Mod operator to check if it should be 4 or 3. Use two arrays just to make it easier (can be done with one)

const groupIt = arr => arr.reduce(({
  group,
  out
}, v, i) => {
  var max = out.length % 4 === 0 ? 4 : 3
  group.push(v)
  if (group.length === max || i === arr.length - 1) {
    out.push(group)
    group = []
  }
  return {
    group,
    out
  }
}, {
  group: [],
  out: []
}).out

console.log(groupIt([1, 2, 3, 4, 5, 6, 7, 8]))

var test = (new Array(30)).fill(0).map((x,i) => i + 1)
console.log(groupIt(test))

with just one:

const groupIt = arr => arr.reduce((out, v, i) => {
  var max = (out.length - 1) % 4 === 0 ? 4 : 3
  out[out.length - 1].push(v)
  if (out[out.length - 1].length === max) {
    out.push([])
  }
  return out
}, [[]])

console.log(groupIt([1, 2, 3, 4, 5, 6, 7, 8]))

var test = (new Array(30)).fill(0).map((x, i) => i + 1)
console.log(groupIt(test))


问:
What can I replace here since I can't have a lambda function with implicit variable in C#?
I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

```<code> class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}
</code>```

What do you suggest I should do here, to implement this functionality. Thank you for your time.

答:
As other answers have correctly noted:

You can't use var with a lambda in C# because the type is ambiguous. You have to state the delegate type explicitly.

Your use of ref indicates that you have misunderstood how outer variable capture works in both C++ and C#. You don't need to make these ref, and the outer variables will be captured automatically.

However none of the answers given so far have told you the better solution to this problem, which is to not use lambdas at all!  Just use a local function.

```<code>public GameLogic()
{
    ... other code here ...
    string GetTile(int x, int y)
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            return sLevel[y * nLevelWidth + x];
        else
            return "";
    }
</code>```

No lambdas required.

Note that this solution requires C# 7.0 or higher.

(An even better solution would be to put all this code into a class; make a custom data type that does this work for you. But you asked specifically about how to port this code directly, not how to refactor it.)

Body:
I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

 class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}

What do you suggest I should do here, to implement this functionality. Thank you for your time.

Body:
As other answers have correctly noted:

You can't use var with a lambda in C# because the type is ambiguous. You have to state the delegate type explicitly.

Your use of ref indicates that you have misunderstood how outer variable capture works in both C++ and C#. You don't need to make these ref, and the outer variables will be captured automatically.

However none of the answers given so far have told you the better solution to this problem, which is to not use lambdas at all!  Just use a local function.

public GameLogic()
{
    ... other code here ...
    string GetTile(int x, int y)
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            return sLevel[y * nLevelWidth + x];
        else
            return "";
    }

No lambdas required.

Note that this solution requires C# 7.0 or higher.

(An even better solution would be to put all this code into a class; make a custom data type that does this work for you. But you asked specifically about how to port this code directly, not how to refactor it.)


问:
Handlebars not rendering unless data is reassigned to another variable
My Handlebars render() function returns an empty string unless the data from my AJAX response is assigned to a new variable. I can work around this, but I am curious if I have done something wrong which caused it.

The offending code in question:

// Get the list of rooms from the server
$.ajax({
    url: "/rooms",
    method: "GET",
    statusCode: {
        200: (res) => {
            // Must reassign res to another variable in order to render
            const rooms = res;
            $("#room-list").html(render({rooms}));
        },
    },
});
```

<p>It should also be noted that <code>res === rooms</code> returns <code>true</code>.</p>

<p>Where I am getting the template:</p>

<pre class="lang-js prettyprint-override"><code>const template = $("#room-item-template").html();
const render = Handlebars.compile(template);
</code>```

And, finally, the HTML template itself:

<template id="room-item-template">
    \{{#each rooms}}

            <button class="room-btn">

\{{name}}

\{{users.length}} / \{{capacity}}

            </button>

            <button class="room-config-btn">Configure Room</button>

    \{{/each}}
</template>
```

答:
How were you passing res to the render function?
It should have been be as follows.

```<code>$("#room-list").html(render({ rooms: res }))
</code>```

Body:
My Handlebars render() function returns an empty string unless the data from my AJAX response is assigned to a new variable. I can work around this, but I am curious if I have done something wrong which caused it.

The offending code in question:

// Get the list of rooms from the server
$.ajax({
    url: "/rooms",
    method: "GET",
    statusCode: {
        200: (res) => {
            // Must reassign res to another variable in order to render
            const rooms = res;
            $("#room-list").html(render({rooms}));
        },
    },
});

It should also be noted that res === rooms returns true.

Where I am getting the template:

const template = $("#room-item-template").html();
const render = Handlebars.compile(template);

And, finally, the HTML template itself:

<template id="room-item-template">
    \{{#each rooms}}

            <button class="room-btn">

\{{name}}

\{{users.length}} / \{{capacity}}

            </button>

            <button class="room-config-btn">Configure Room</button>

    \{{/each}}
</template>

Body:
How were you passing res to the render function?
It should have been be as follows.

$("#room-list").html(render({ rooms: res }))


问:
Deprecation 6720 - Experimental feature for requested-permissions in capsule-info.bxb
I updated my Bixby capsule-info.bxb to add the requested-permissions element but studio is complaining with this error:

```<code>Experimental feature, not available for external use. [deprecation 6720]
</code>```

The hyperlink below the error message results in an HTTP 404 Not Found page (https://bixbydevelopers.com/dev/docs/dev-guide/release-notes/deprecations.6720)

I made this change as requested in a Stage 2 Deprecation Warning email.

答: This issue has been resolved. Please see this Help Center article for more information.</p>

Body:
I updated my Bixby capsule-info.bxb to add the requested-permissions element but studio is complaining with this error:

Experimental feature, not available for external use. [deprecation 6720]

The hyperlink below the error message results in an HTTP 404 Not Found page (https://bixbydevelopers.com/dev/docs/dev-guide/release-notes/deprecations.6720)

I made this change as requested in a Stage 2 Deprecation Warning email.


问:
Array.map() doesn't render React component
I am having a problem where i'm trying to render pass an array's data to a card component but it doesn't appear on the page, the card component renders normally on its own:

```<code>import React, { Component } from 'react'
import { Container, Grid, Card, Segment, Header } from 'semantic-ui-react';
import ArticleCard from './ArticleCard';

export default class NewsGrid extends Component {
    render() {
        const {News} = this.props
        console.log(News)

        return (
            <div>
                <Container style={{marginTop: '7%'}}>
                <Grid stackable divided >
                    <Grid.Column style={{width: '66.66%'}}>
                        <Card.Group>
                            {
                                News.map(({id, ...otherArticleProps}) => (
                                    <ArticleCard key={id} {...otherArticleProps} />
                                ))
                            }
                        </Card.Group>
                    </Grid.Column>

                </Grid>
            </Container>
            </div>
        )
    }
}
</code>```

console.log() shows that the data is actually there

and i'm passing the array as props from the parent page component, the data is delivered through the flamelink API in useEffect as shown bellow:

```<code>import React, { useEffect, useState } from 'react';
import NewsGrid from '../components/NewsGrid';
import BusinessContainer from '../components/BusinessContainer';
import PolitiqueContainer from './../components/PolitiqueContainer';
import app from '../Firebase';
import { withRouter } from 'react-router-dom';

const Homepage = () => {
    const [News] = useState([])
    const [Business] = useState([])
    const [Politique] = useState([])
    const [Opinion] = useState([])
    const [Blog] = useState([])

    useEffect(() => {
        app.content.get({schemaKey: 'articles',
                        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
                        orderBy:{field: 'date',
                        order: 'desc'},
                         })
        .then(articles => {
            for(var propName in articles) {
                const propValue = articles[propName]

                switch(propValue.category) {
                    default :
                        break;
                    case 'News':
                        News.push(propValue)
                        break;
                    case 'Business':
                        Business.push(propValue)
                        break;
                    case 'Politique':
                        Politique.push(propValue)
                        break;
                    case 'Opinion':
                        Opinion.push(propValue)
                        break;
                    case 'Blog':
                        Blog.push(propValue)
                        break;

                }
            }
        })
    })

    return (
        <div >
            <NewsGrid  News={News} Opinion={Opinion} Blog={Blog} />
            <BusinessContainer  content={Business} />
            <PolitiqueContainer  content={Politique} />

        </div>
    );
};

export default withRouter(Homepage);
</code>```

I am using firebase as a backend combined with Flamelink for the CMS.
Thanks in advance.

答:
```<code>    import React, { useEffect, useState } from 'react';
    import NewsGrid from '../components/NewsGrid';
    import BusinessContainer from '../components/BusinessContainer';
    import PolitiqueContainer from './../components/PolitiqueContainer';
    import app from '../Firebase';
    import { withRouter } from 'react-router-dom';

    const Homepage = () => {
      const [news, setNews] = useState([]);
      const [business, setBusiness] = useState([]);
      const [politique, setPolitique] = useState([]);

  const [opinion, setOpinion] = useState([]);
  const [blog, setBlog] = useState([]);

  useEffect(() => {
    app.content
      .get({
        schemaKey: 'articles',
        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
        orderBy: { field: 'date', order: 'desc' },
      })
      .then(articles => {
        for (let propName in articles) {
          const propValue = articles[propName];

          switch (propValue.category) {
            case 'News':
              setNews(propValue);
              break;
            case 'Business':
              setBusiness(propValue);
              break;
            case 'Politique':
              setPolitique(propValue);
              break;
            case 'Opinion':
              setOpinion(propValue);
              break;
            case 'Blog':
              setBlog(propValue);
              break;
            default:
                break;
          }
        }
      });
  }, []);

  return (
    <div>
      <NewsGrid News={news} Opinion={opinion} Blog={blog} />
      <BusinessContainer content={business} />
      <PolitiqueContainer content={politique} />
    </div>
  );
};

export default withRouter(Homepage);
</code>```

I would suggest using camel case variables:

```<code>const [stateVariable, setStateVariable] = useState();
</code>```

(https://reactjs.org/docs/hooks-state.html) and to add the [] to the useEffect array of dependencies. This will ensure that the useEffect will trigger only a single time. Hope that this helps.

Body:
I am having a problem where i'm trying to render pass an array's data to a card component but it doesn't appear on the page, the card component renders normally on its own:

import React, { Component } from 'react'
import { Container, Grid, Card, Segment, Header } from 'semantic-ui-react';
import ArticleCard from './ArticleCard';

export default class NewsGrid extends Component {
    render() {
        const {News} = this.props
        console.log(News)

        return (

                <Container style={{marginTop: '7%'}}>
                <Grid stackable divided >
                    <Grid.Column style={{width: '66.66%'}}>
                        <Card.Group>
                            {
                                News.map(({id, ...otherArticleProps}) => (
                                    <ArticleCard key={id} {...otherArticleProps} />
                                ))
                            }
                        </Card.Group>
                    </Grid.Column>

                </Grid>
            </Container>

        )
    }
}

console.log() shows that the data is actually there

and i'm passing the array as props from the parent page component, the data is delivered through the flamelink API in useEffect as shown bellow:

import React, { useEffect, useState } from 'react';
import NewsGrid from '../components/NewsGrid';
import BusinessContainer from '../components/BusinessContainer';
import PolitiqueContainer from './../components/PolitiqueContainer';
import app from '../Firebase';
import { withRouter } from 'react-router-dom';

const Homepage = () => {
    const [News] = useState([])
    const [Business] = useState([])
    const [Politique] = useState([])
    const [Opinion] = useState([])
    const [Blog] = useState([])

    useEffect(() => {
        app.content.get({schemaKey: 'articles',
                        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
                        orderBy:{field: 'date',
                        order: 'desc'},
                         })
        .then(articles => {
            for(var propName in articles) {
                const propValue = articles[propName]

                switch(propValue.category) {
                    default :
                        break;
                    case 'News':
                        News.push(propValue)
                        break;
                    case 'Business':
                        Business.push(propValue)
                        break;
                    case 'Politique':
                        Politique.push(propValue)
                        break;
                    case 'Opinion':
                        Opinion.push(propValue)
                        break;
                    case 'Blog':
                        Blog.push(propValue)
                        break;

                }
            }
        })
    })

    return (

            <NewsGrid  News={News} Opinion={Opinion} Blog={Blog} />
            <BusinessContainer  content={Business} />
            <PolitiqueContainer  content={Politique} />

    );
};

export default withRouter(Homepage);

I am using firebase as a backend combined with Flamelink for the CMS.
Thanks in advance.

Body:
    import React, { useEffect, useState } from 'react';
    import NewsGrid from '../components/NewsGrid';
    import BusinessContainer from '../components/BusinessContainer';
    import PolitiqueContainer from './../components/PolitiqueContainer';
    import app from '../Firebase';
    import { withRouter } from 'react-router-dom';

    const Homepage = () => {
      const [news, setNews] = useState([]);
      const [business, setBusiness] = useState([]);
      const [politique, setPolitique] = useState([]);

  const [opinion, setOpinion] = useState([]);
  const [blog, setBlog] = useState([]);

  useEffect(() => {
    app.content
      .get({
        schemaKey: 'articles',
        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
        orderBy: { field: 'date', order: 'desc' },
      })
      .then(articles => {
        for (let propName in articles) {
          const propValue = articles[propName];

          switch (propValue.category) {
            case 'News':
              setNews(propValue);
              break;
            case 'Business':
              setBusiness(propValue);
              break;
            case 'Politique':
              setPolitique(propValue);
              break;
            case 'Opinion':
              setOpinion(propValue);
              break;
            case 'Blog':
              setBlog(propValue);
              break;
            default:
                break;
          }
        }
      });
  }, []);

  return (
    <div>
      <NewsGrid News={news} Opinion={opinion} Blog={blog} />
      <BusinessContainer content={business} />
      <PolitiqueContainer content={politique} />
    </div>
  );
};

export default withRouter(Homepage);

I would suggest using camel case variables:

const [stateVariable, setStateVariable] = useState();

(https://reactjs.org/docs/hooks-state.html) and to add the [] to the useEffect array of dependencies. This will ensure that the useEffect will trigger only a single time. Hope that this helps.


问:
Wordpress Gravity Forms Dropbox link not found in $entry object
I'm using WordPress gravity forms and dropbox addon to upload files on dropbox
I am trying to retrieve the dropbox link after form submission using PHP
As docs said i should be able to find the link in the entry object
https://docs.gravityforms.com/gf_field_dropbox/#-entry-value
but I only find the WordPress upload link although when I view my entry the dropbox link is sitting there fine
and here is the code I am using in the functions.php of my current theme

```<code>add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {

    $value = rgar( $entry, '158' ); // id of the field that holds the dropbox link
    $files = json_decode( $value, true );
    foreach ( $files as $file ) {
        print_r($file);
    }
    foreach($entry as $child) { // also trying to print all entry properties but found nothing
        echo $child . "<br>";
    }

    $value1 = GF_Field_Dropbox::get_value_export( $entry, '158' ); // trying export function in the docs but gives the same as first $value
    print_r($value1);

}
</code>```

is there any way I can access the dropbox generated links after form submission?

答:
managed to get the generated dropbox link using this</p>

```<code>add_action( 'gform_dropbox_post_upload', 'get_dropbox_urls', 10, 3 );
function get_dropbox_urls( $feed, $entry, $form ) {

    print_r('started get drobbox');
    foreach( $form['fields'] as &$field )  {

        // NOTE: Replace 3 with your Dropbox field id.
        $field_id = 158;
        print_r($field_id,'the field id', $field);
        if ( $field->id != $field_id ) {
            continue;
        }

        // Get the field value.
        $field_value = $entry[ $field->id ];

        // Exit if field value is empty.
        if ( rgblank( $field_value ) ) {
            return;
        }

        // Decode JSON string.
        $files = json_decode( stripslashes_deep( $field_value ), true );
        print_r($files);

    }

}
</code>```

Body:
I'm using WordPress gravity forms and dropbox addon to upload files on dropbox
I am trying to retrieve the dropbox link after form submission using PHP
As docs said i should be able to find the link in the entry object
https://docs.gravityforms.com/gf_field_dropbox/#-entry-value
but I only find the WordPress upload link although when I view my entry the dropbox link is sitting there fine
and here is the code I am using in the functions.php of my current theme

add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {

    $value = rgar( $entry, '158' ); // id of the field that holds the dropbox link
    $files = json_decode( $value, true );
    foreach ( $files as $file ) {
        print_r($file);
    }
    foreach($entry as $child) { // also trying to print all entry properties but found nothing
        echo $child . "
";
    }

    $value1 = GF_Field_Dropbox::get_value_export( $entry, '158' ); // trying export function in the docs but gives the same as first $value
    print_r($value1);

}

is there any way I can access the dropbox generated links after form submission?

Body:
managed to get the generated dropbox link using this

add_action( 'gform_dropbox_post_upload', 'get_dropbox_urls', 10, 3 );
function get_dropbox_urls( $feed, $entry, $form ) {

    print_r('started get drobbox');
    foreach( $form['fields'] as &$field )  {

        // NOTE: Replace 3 with your Dropbox field id.
        $field_id = 158;
        print_r($field_id,'the field id', $field);
        if ( $field->id != $field_id ) {
            continue;
        }

        // Get the field value.
        $field_value = $entry[ $field->id ];

        // Exit if field value is empty.
        if ( rgblank( $field_value ) ) {
            return;
        }

        // Decode JSON string.
        $files = json_decode( stripslashes_deep( $field_value ), true );
        print_r($files);

    }

}


问:
Hapi Joi - validate concatenated keys
I have a request body like this one:

```<code>bod = {
file: '123654',
extension: 'bbb',
...
}
</code>```

I'm using hapi joi to validate it's fields:

```<code>let valSchema = {};
valSchema.play = Joi.object().keys({
    file: Joi.string().required().message("Invalid name. Please check documentation."),
    extension: Joi.string().empty().required().message("No extension sent. check the docs..."),
});

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

The problem is that one of the validations needs to check if the "$file:$extension" is in an array such as:

```<code>validConcatenations = [
    "1111:aaa","111123:bbb", "12312:aab",
    "21323:zzzs" ... ];
</code>```

I would need to do this:

```<code>if (data.file && settings.fileWithExtensions.indexOf(`${data.file}:${data.extension}`) < 0) {
        return errors.invalidSampleRate;
    }
</code>```

using joi...Is this possible using it?
using with?

答:
It is possible, all you need to do is a custom validation as the example below.

VERSION 16.1.8 or greater

'use strict';

const Joi = require('@hapi/joi');

const customValidation = function (value, helpers) {
    const validConcatenations = [
        "1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
    if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
        throw Error(`Wrong concatenation ${value.file}:${value.extension}`)
    }
    return value;
};

const schema = Joi.object().keys({
    file: Joi.string().required(),
    extension: Joi.string().empty().required(),
}).custom(customValidation);

const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };

console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));
```

<p>Outputs:</p>

```{ value: { file: '123654', extension: 'bbb' },
  error:
   { ValidationError: "value" failed custom validation because Wrong concatenation 123654:bbb
     _original: { file: '123654', extension: 'bbb' },
     details: [ [Object] ] } }
{ value: { file: '1111', extension: 'aaa' } }
```

<p>Looking at the docs it is possible to do the below solution since version <strong>12.1.0</strong></p>

<p><strong>VERSION 12.1.0 or greater</strong></p>

<pre class="lang-js prettyprint-override"><code>'use strict';

const _Joi = require('@hapi/joi');

const custom = {
    base: _Joi.object(),
    name: 'custom',
    language: {
        concatenation: 'is a invalid concatenation',
    },
    rules: [
        {
            name: 'concatenation',
            validate(params, value, state, options) {
                const validConcatenations = [
                    "1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
                if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
                    return this.createError('custom.concatenation', {v: value}, state, options);
                }
                return value;
            }
        }
    ]
};

const Joi = _Joi.extend(custom);

const schema = Joi.custom().keys({
    file: Joi.string().required(),
    extension: Joi.string().empty().required(),
}).concatenation();

const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };

console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));
</code>```

Outputs:

```<code>{ error:
   { ValidationError: "value" is a invalid concatenation
    at Object.exports.process (/tmp/test/node_modules/@hapi/joi/lib/errors.js:202:19)
    at type._validateWithOptions (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:762:31)
    at type.validate (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:796:21)
    at Object.<anonymous> (/tmp/test/index.js:36:20)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
     isJoi: true,
     name: 'ValidationError',
     details: [ [Object] ],
     _object: { file: '123654', extension: 'bbb' },
     annotate: [Function] },
  value: { file: '123654', extension: 'bbb' },
  then: [Function: then],
  catch: [Function: catch] }
{ error: null,
  value: { file: '1111', extension: 'aaa' },
  then: [Function: then],
  catch: [Function: catch] }
</code>```

Title: Hapi Joi - validate concatenated keys

Body:
I have a request body like this one:

bod = {
file: '123654',
extension: 'bbb',
...
}

I'm using hapi joi to validate it's fields:

let valSchema = {};
valSchema.play = Joi.object().keys({
    file: Joi.string().required().message("Invalid name. Please check documentation."),
    extension: Joi.string().empty().required().message("No extension sent. check the docs..."),
});

module.exports.valSchema = valSchema;

The problem is that one of the validations needs to check if the "$file:$extension" is in an array such as:

validConcatenations = [
    "1111:aaa","111123:bbb", "12312:aab",
    "21323:zzzs" ... ];

I would need to do this:

if (data.file && settings.fileWithExtensions.indexOf(`${data.file}:${data.extension}`) < 0) {
        return errors.invalidSampleRate;
    }

using joi...Is this possible using it?
using with?

Body:
It is possible, all you need to do is a custom validation as the example below.

VERSION 16.1.8 or greater

'use strict';

const Joi = require('@hapi/joi');

const customValidation = function (value, helpers) {
    const validConcatenations = [
        "1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
    if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
        throw Error(`Wrong concatenation ${value.file}:${value.extension}`)
    }
    return value;
};

const schema = Joi.object().keys({
    file: Joi.string().required(),
    extension: Joi.string().empty().required(),
}).custom(customValidation);

const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };

console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));

Outputs:

{ value: { file: '123654', extension: 'bbb' },
  error:
   { ValidationError: "value" failed custom validation because Wrong concatenation 123654:bbb
     _original: { file: '123654', extension: 'bbb' },
     details: [ [Object] ] } }
{ value: { file: '1111', extension: 'aaa' } }

Looking at the docs it is possible to do the below solution since version 12.1.0

VERSION 12.1.0 or greater

'use strict';

const _Joi = require('@hapi/joi');

const custom = {
    base: _Joi.object(),
    name: 'custom',
    language: {
        concatenation: 'is a invalid concatenation',
    },
    rules: [
        {
            name: 'concatenation',
            validate(params, value, state, options) {
                const validConcatenations = [
                    "1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
                if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
                    return this.createError('custom.concatenation', {v: value}, state, options);
                }
                return value;
            }
        }
    ]
};

const Joi = _Joi.extend(custom);

const schema = Joi.custom().keys({
    file: Joi.string().required(),
    extension: Joi.string().empty().required(),
}).concatenation();

const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };

console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));

Outputs:

{ error:
   { ValidationError: "value" is a invalid concatenation
    at Object.exports.process (/tmp/test/node_modules/@hapi/joi/lib/errors.js:202:19)
    at type._validateWithOptions (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:762:31)
    at type.validate (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:796:21)
    at Object.<anonymous> (/tmp/test/index.js:36:20)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
     isJoi: true,
     name: 'ValidationError',
     details: [ [Object] ],
     _object: { file: '123654', extension: 'bbb' },
     annotate: [Function] },
  value: { file: '123654', extension: 'bbb' },
  then: [Function: then],
  catch: [Function: catch] }
{ error: null,
  value: { file: '1111', extension: 'aaa' },
  then: [Function: then],
  catch: [Function: catch] }


问:
How to Specify an IP Address for TcpClient to use
During development, we usually use localhost as the hostname, like the following

```<code> Dim serverListener As New TcpClient("localhost", 8585)
</code>```

I want the user to be able to enter their IP address via a TextBox instead, like

```<code>Dim serverListener As New TcpClient(textbox1.text, 8585)
</code>```

However, this is not working for me. Any ideas? Thanks!

答:
The form of the TcpClient constructor that accepts a string and an int parameter expects a hostname and a port, not an IP address.

You might want to use the TcpClient constructor that takes an IPEndPoint parameter instread. There is more information on the IPEndPoint class on MSDN, but in short it represents an IP address and a port number.

Body:
During development, we usually use localhost as the hostname, like the following

 Dim serverListener As New TcpClient("localhost", 8585)

I want the user to be able to enter their IP address via a TextBox instead, like

Dim serverListener As New TcpClient(textbox1.text, 8585)

However, this is not working for me. Any ideas? Thanks!