问:
Sprite Kit game design for chess game
I am new to Swift and iOS, I am planning to design a chess game (chinese chess) in iOS using Sprite Kit. I've been brainstorming the design strategies.
I have a question regarding creating the chess board and how the pieces move.

Unlike chess, each piece move to an intersection point, I am seeing people who make chess game board by creating each tile as a separate UIview, since the chinese chess board is harder to draw I was planning to just use the board image as one node, and each pieces simply move on top of the board. left right up down by calculating the distance of each square. ( for example, dividing the board width by 8 since there are 8 equal squares a row) Is this a good strategy or is there a better  way of implementing. I find this way not the most efficient since if the device changes, the board and pieces size would stay the same?

I would appreciate it if anyone can give me some advice.

答:
I did precisely this sort of thing for a port of the classic game "Chase!". In my case the background graphic was not static, as the board layout could be changed by the user if desired.

Basically all I did was use the UIView bounds and found the smallest dimension, which is the narrow direction of the screen. I then scaled the grid to that size and placed it in the middle of the UIView.

Since the number of tiles in your case is fixed, it is easy to calculate a grid location for a given screen location and vice versa.

So to answer you more directly, "yes, that is the way to do it".

Title: Sprite Kit game design for chess game


来源: stackexchange

问:
scrapinghub starting job too slow
I am new in scraping and I am running different jobs on scrapinghub. I run them via their API. The problem is that starting the spider and initializing it takes too much time like 30 seconds. When I run it locally, it takes up to 5 seconds to finish the spider. But in scrapinghub it takes 2:30 minutes. I understand that closing a spider after all requests are finished takes a little bit more time, but this is not a problem. Anyway, my problem is that from the moment I call the API to start the job (I see that it appear in running jobs instantly, but takes too long to make the first request) and the moment the first request is done, I have to wait too much. Any idea how I can make it to last as shortly as locally? Thanks!

I already tried to put AUTOTHROTTLE_ENABLED = false as I saw in some other question on stackoverflow.

答:
According to scrapy cloud docs:

Scrapy Cloud jobs run in containers. These containers can be of different sizes defined by Scrapy Cloud units.

A Scrapy Cloud provides: 1 GB of RAM, 2.5GB of disk space,1x CPU and 1 concurrent crawl slot.

Resources available to the job are proportional to the number of units allocated.

It means that allocating more Scrapy Cloud units can solve your problem.

ContentLicense: CC BY-SA 4.0

Title: scrapinghub starting job too slow


问:
Detect whether Google User has logged in before
I'm currently implementing the possibility for the user to login with Google.

How can I detect whether this exact Google User has previously logged in to fetch data from the database. So far, when a user has already logged in the past, logging in with Google overwrites the entry in the database.

Is there a way to check whether the auth id has already been setup before?

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()

    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self

    Database.database().isPersistenceEnabled = true

    ...

    return true
}

// MARK: - Google SignIn
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error {
        print("Failed logging into Google: ", error)
        return
    }

    print("Successfully logged into Google.")

    guard let authentication = user.authentication else { return }
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)

    Auth.auth().signIn(with: credential) { (acc, error) in
        if let error = error {
            print("Failed to create User with Google: ", error)
            return
        }

        self.upDataToDatabase(from: user)

        print("Successfully created user with Google.")
    }
}

func upDataToDatabase(from user: GIDGoogleUser) {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let databaseRefUser = Database.database().reference().child("users/\(uid)")

    let userObject = [
        "name": String(user.profile.name),
        "email": String(user.profile.email),
        ] as [String: Any]

    databaseRefUser.setValue(userObject) { (error, ref) in
        if error != nil {
            print("Error creating Database connection: ", error as Any)
            return
        } else {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "homeView") as! HomeViewController
            self.window?.rootViewController = controller
            self.window?.makeKeyAndVisible()
        }
    }
}

@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any])
    -> Bool {
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                                 annotation: [:])
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: sourceApplication,
                                             annotation: annotation)
}
</code>```

答:
Firebase userId always remains same for a user until deleted.

```<code> guard let uid = Auth.auth().currentUser?.uid else { return }
 let databaseRefUser = Database.database().reference().child("users/\(uid)")
</code>```

Check if databaseRefUser already exists than don't update the DB else setValue for the same.

Body:
I'm currently implementing the possibility for the user to login with Google.

How can I detect whether this exact Google User has previously logged in to fetch data from the database. So far, when a user has already logged in the past, logging in with Google overwrites the entry in the database.

Is there a way to check whether the auth id has already been setup before?

class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()

    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self

    Database.database().isPersistenceEnabled = true

    ...

    return true
}

// MARK: - Google SignIn
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error {
        print("Failed logging into Google: ", error)
        return
    }

    print("Successfully logged into Google.")

    guard let authentication = user.authentication else { return }
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)

    Auth.auth().signIn(with: credential) { (acc, error) in
        if let error = error {
            print("Failed to create User with Google: ", error)
            return
        }

        self.upDataToDatabase(from: user)

        print("Successfully created user with Google.")
    }
}

func upDataToDatabase(from user: GIDGoogleUser) {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let databaseRefUser = Database.database().reference().child("users/\(uid)")

    let userObject = [
        "name": String(user.profile.name),
        "email": String(user.profile.email),
        ] as [String: Any]

    databaseRefUser.setValue(userObject) { (error, ref) in
        if error != nil {
            print("Error creating Database connection: ", error as Any)
            return
        } else {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "homeView") as! HomeViewController
            self.window?.rootViewController = controller
            self.window?.makeKeyAndVisible()
        }
    }
}

@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any])
    -> Bool {
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                                 annotation: [:])
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: sourceApplication,
                                             annotation: annotation)
}

Body:
Firebase userId always remains same for a user until deleted.

 guard let uid = Auth.auth().currentUser?.uid else { return }
 let databaseRefUser = Database.database().reference().child("users/\(uid)")

Check if databaseRefUser already exists than don't update the DB else setValue for the same.


问:
In Jolt how to modified the keys of out put json and copy values from input
In Nifi I want to copy all input values to output which has modified keys compared to input.

Input:

```<code>{
    "test": {
    "name":"John",
    "salary":"2500.145263"
    }
}
</code>```

Output:

```<code>{
    "company": {
    "fn":"JOHN",
    "sl":"2500.14"
    }
}
</code>```

Here I want to make the name uppercase and salary rounded off to two decimal places.

答:
According to this, there is not (yet) a pure rounding function in JOLT. However there is a divideAndRound function, try the following spec (it worked for me in the online tester with your input):

```<code>[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "test": {
        "salary": "=divideAndRound(2,@(1,salary),1)"
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "test": {
        "salary": "=toString(@(1,salary))"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "test": {
        "name": "company.fn",
        "salary": "company.salary"
      }
    }
    }
]
</code>```

The first part of the chain just divides the number by 1 and then rounds to 2 places, the second part of the chain spec is just to turn your salary field back into a string; when you use divideAndRound it will turn it into a numeric field. If you'd prefer the numeric field, you can leave out the second spec in the chain.

Body:
In Nifi I want to copy all input values to output which has modified keys compared to input.

Input:

{
    "test": {
    "name":"John",
    "salary":"2500.145263"
    }
}

Output:

{
    "company": {
    "fn":"JOHN",
    "sl":"2500.14"
    }
}

Here I want to make the name uppercase and salary rounded off to two decimal places.

Body:
According to this, there is not (yet) a pure rounding function in JOLT. However there is a divideAndRound function, try the following spec (it worked for me in the online tester with your input):

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "test": {
        "salary": "=divideAndRound(2,@(1,salary),1)"
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "test": {
        "salary": "=toString(@(1,salary))"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "test": {
        "name": "company.fn",
        "salary": "company.salary"
      }
    }
    }
]

The first part of the chain just divides the number by 1 and then rounds to 2 places, the second part of the chain spec is just to turn your salary field back into a string; when you use divideAndRound it will turn it into a numeric field. If you'd prefer the numeric field, you can leave out the second spec in the chain.


问:
Serving Django's static and media files from S3
I'm having a weird problem and I have no idea what's causing it. Here's my current config (using Heroku):

```<code>MEDIA_URL = '/media/'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, '../static'),
)

#Determine if local or deployed.
if 'DATABASE_URL' in os.environ:
    STATICFILES_STORAGE     = 'storages.backends.s3boto.S3BotoStorage'
    AWS_ACCESS_KEY_ID       = 'A...A'
    AWS_SECRET_ACCESS_KEY   = '...R'
    DEFAULT_FILE_STORAGE    = 'storages.backends.s3boto.S3BotoStorage'

    # PRODUCTION OR STAGING
    if 'PROD' in os.environ:
        AWS_STORAGE_BUCKET_NAME = 's3.project.com'
        STATIC_URL = "https://s3.amazonaws.com/project/"
    else:
        AWS_STORAGE_BUCKET_NAME = 'project-staging'
        STATIC_URL = "https://s3.amazonaws.com/project-staging/"
else:
    STATIC_ROOT = ''
</code>```

The thing is, static files are working fine, the links look like this: https://s3.amazonaws.com/project-staging/img/homepage_left.png.

First problem (Admin half broken):

The admin is half working. CSS files are served fine: https://project-staging.s3.amazonaws.com/admin/js/core.js?Signature=asdasdasd%3D&Expires=1352430664&AWSAccessKeyId=asdasdasA but the all the images are broken:

https://project-staging.s3.amazonaws.com/admin?Signature=%2asdasdad%3D&Expires=1352430664&AWSAccessKeyId=asdasdaimg/icon_calendar.gif

I don't know why the Signature and AWSAccesskey are there :(. If I remove them (by hand) the URL works fine!

Second problem (uploaded media via ImageField/FileField):

I'm using {{MEDIA_URL}}{{object.flyer}}, it translates to /media/media/flyers/poster_1.png, how do I point it out to s3? It should be like this: https://project-staging.s3.amazonaws.com/media/flyers/poster_1.png

答:
Adding the answers:

First problem:
Make sure your bucket is set to public and set AWS_QUERYSTRING_AUTH in your settings to False, that way your file will be served without the signature part

```<code>AWS_QUERYSTRING_AUTH = False
</code>```

Second problem:
Make sure you add "url" at the end {{..url}}

```<code>{{MEDIA_URL}}{{object.flyer.url}}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having a weird problem and I have no idea what's causing it. Here's my current config (using Heroku):

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, '../static'),
)

#Determine if local or deployed.
if 'DATABASE_URL' in os.environ:
    STATICFILES_STORAGE     = 'storages.backends.s3boto.S3BotoStorage'
    AWS_ACCESS_KEY_ID       = 'A...A'
    AWS_SECRET_ACCESS_KEY   = '...R'
    DEFAULT_FILE_STORAGE    = 'storages.backends.s3boto.S3BotoStorage'

    # PRODUCTION OR STAGING
    if 'PROD' in os.environ:
        AWS_STORAGE_BUCKET_NAME = 's3.project.com'
        STATIC_URL = "https://s3.amazonaws.com/project/"
    else:
        AWS_STORAGE_BUCKET_NAME = 'project-staging'
        STATIC_URL = "https://s3.amazonaws.com/project-staging/"
else:
    STATIC_ROOT = ''

The thing is, static files are working fine, the links look like this: https://s3.amazonaws.com/project-staging/img/homepage_left.png.

First problem (Admin half broken):

The admin is half working. CSS files are served fine: https://project-staging.s3.amazonaws.com/admin/js/core.js?Signature=asdasdasd%3D&Expires=1352430664&AWSAccessKeyId=asdasdasA but the all the images are broken:

https://project-staging.s3.amazonaws.com/admin?Signature=%2asdasdad%3D&Expires=1352430664&AWSAccessKeyId=asdasdaimg/icon_calendar.gif

I don't know why the Signature and AWSAccesskey are there :(. If I remove them (by hand) the URL works fine!

Second problem (uploaded media via ImageField/FileField):

I'm using {{MEDIA_URL}}{{object.flyer}}, it translates to /media/media/flyers/poster_1.png, how do I point it out to s3? It should be like this: https://project-staging.s3.amazonaws.com/media/flyers/poster_1.png

Body:
Adding the answers:

First problem:
Make sure your bucket is set to public and set AWS_QUERYSTRING_AUTH in your settings to False, that way your file will be served without the signature part

AWS_QUERYSTRING_AUTH = False

Second problem:
Make sure you add "url" at the end {{..url}}

{{MEDIA_URL}}{{object.flyer.url}}


问:
Map yarn build output to stage an artifact
I'm trying to use an Azure DevOps yarn YAML task to build my site. That step completes. But where does the built code go?

```<code>##[section]Starting: Yarn
    Task         : Yarn task
Description  : Executes Yarn
Version      : 2.8.1001
Author       : Geek Learning
Help         : [More Information](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Yarn) (Version 2.8.1001).

Dear Angular and Ember CLI users, please check our [known issues](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Known-Issues)
==============================================================================
SYSTEMVSSCONNECTION exists true
SYSTEMVSSCONNECTION exists true
    [command]C:\windows\system32\cmd.exe /D /S /C "C:\npm\prefix\yarn.cmd --production build"
yarn install v1.15.2
    [1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@1.2.7: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.7" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
    warning " > bootstrap@4.3.1" has unmet peer dependency "popper.js@^1.14.7".
    [4/4] Building fresh packages...
Done in 119.26s.
##[section]Finishing: Yarn

##[section]Starting: Stage Files
    ==============================================================================
    Task         : Copy Files
Description  : Copy files from source folder to target folder using match patterns (The match patterns will only match file paths, not folder paths)
Version      : 2.117.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=708389)

##[error]Unhandled: Not found SourceFolder: D:\a\1\a\s\build\
##[section]Finishing: Stage Files
</code>```

Here is my YAML

```<code>task: Yarn@2
inputs:
    ProjectDirectory: './'
Arguments: 'build'
ProductionMode: true

    - task: CopyFiles@2
displayName: 'Stage Files'
inputs:
    SourceFolder: 'D:\_work\1\s\build'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/dist'
CleanTargetFolder: true
OverWrite: true
</code>```

I have been playing around with the SourceFolder and having no luck.

Adding a "dir" command seems to show that I am in the root folder for my project, but I do not see a build folder

答:
I think the issue was that "yarn build" appeared to be working, but it was only installing yarn.

I added a second command to "yarn build" after "yarn --production".

```<code>- task: Yarn@2
inputs:
    ProjectDirectory: './'
ProductionMode: true

    - task: Yarn@2
inputs:
    ProjectDirectory: './'
Arguments: 'build'

    - script: "dir .."
displayName: 'Run dir'

    - task: CopyFiles@2
displayName: 'Stage Files'
inputs:
    SourceFolder: './build'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/dist'
CleanTargetFolder: true
OverWrite: true
</code>```

Body:
I'm trying to use an Azure DevOps yarn YAML task to build my site. That step completes. But where does the built code go?

##[section]Starting: Yarn
    Task         : Yarn task
Description  : Executes Yarn
Version      : 2.8.1001
Author       : Geek Learning
Help         : [More Information](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Yarn) (Version 2.8.1001).

Dear Angular and Ember CLI users, please check our [known issues](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Known-Issues)
==============================================================================
SYSTEMVSSCONNECTION exists true
SYSTEMVSSCONNECTION exists true
    [command]C:\windows\system32\cmd.exe /D /S /C "C:\npm\prefix\yarn.cmd --production build"
yarn install v1.15.2
    [1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@1.2.7: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.7" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
    warning " > bootstrap@4.3.1" has unmet peer dependency "popper.js@^1.14.7".
    [4/4] Building fresh packages...
Done in 119.26s.
##[section]Finishing: Yarn

##[section]Starting: Stage Files
    ==============================================================================
    Task         : Copy Files
Description  : Copy files from source folder to target folder using match patterns (The match patterns will only match file paths, not folder paths)
Version      : 2.117.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=708389)

##[error]Unhandled: Not found SourceFolder: D:\a\1\a\s\build\
##[section]Finishing: Stage Files

Here is my YAML

task: Yarn@2
inputs:
    ProjectDirectory: './'
Arguments: 'build'
ProductionMode: true

    - task: CopyFiles@2
displayName: 'Stage Files'
inputs:
    SourceFolder: 'D:\_work\1\s\build'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/dist'
CleanTargetFolder: true
OverWrite: true

I have been playing around with the SourceFolder and having no luck.

Adding a "dir" command seems to show that I am in the root folder for my project, but I do not see a build folder

Body:
I think the issue was that "yarn build" appeared to be working, but it was only installing yarn.

I added a second command to "yarn build" after "yarn --production".

- task: Yarn@2
inputs:
    ProjectDirectory: './'
ProductionMode: true

    - task: Yarn@2
inputs:
    ProjectDirectory: './'
Arguments: 'build'

    - script: "dir .."
displayName: 'Run dir'

    - task: CopyFiles@2
displayName: 'Stage Files'
inputs:
    SourceFolder: './build'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/dist'
CleanTargetFolder: true
OverWrite: true


问:
Is it possible for an app to not work properly in different devices even though they run the same OS version?
I am building an app that includes a Speech To Text activity. I have tested it in a Xiaomi Pocophone F1 and a Samsung Galaxy A50, both running android 9 Pie. The F1 runs the app great, the A50 runs the app partly, but when attempting to use the Speech To Text option it just crashes. Is it that the device does not support that feature? i can't believe that... Anyway, i need a way to prohibit the user from attempting to use that feature on a Galaxy A50, so the app will politely say that it cannot happen instead of crashing.</p>

答:
Yes. Most Android operating systems provided by cell phone carriers are custom. They take the Google version of the OS and pile in all sorts of add-on apps and services (bloatware) that can impact other systems. This can cause minor differences between devices with the same OS.

Couple that with hardware differences that also impact how a device performs and handles input, and you can easily get circumstances where one device will not behave the same as another even though running the same OS version.

For you specific problem, you can see if the speech to text is available:

```<code>// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(
  new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
  speakButton.setOnClickListener(this);
} else {
  speakButton.setEnabled(false);
  speakButton.setText("Recognizer not present");
}
</code>```

Code pulled from another stack overflow question: How to detect if speech to text is available on android?

Body:
Yes. Most Android operating systems provided by cell phone carriers are custom. They take the Google version of the OS and pile in all sorts of add-on apps and services (bloatware) that can impact other systems. This can cause minor differences between devices with the same OS.

Couple that with hardware differences that also impact how a device performs and handles input, and you can easily get circumstances where one device will not behave the same as another even though running the same OS version.

For you specific problem, you can see if the speech to text is available:

// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(
  new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
  speakButton.setOnClickListener(this);
} else {
  speakButton.setEnabled(false);
  speakButton.setText("Recognizer not present");
}

Code pulled from another stack overflow question: How to detect if speech to text is available on android?


问:
Blanket hreflang or lang attribute for single language website
My marketing team is on me to fix Site Audit errors reported by Semrush and Ahrefs.

The error is: "218 pages have no hreflang and lang attributes"

This is a single language site - all in US English.  I realize I can go into 218 pages and change  to .  However, my full site is more than 2000 pages so I think the 218 count is just that site audit stopped there.

I'd like to just put a default in the page header for all pages.  I see the syntax for hreflang alternate, but I don't think it's right for a single language site.

Is there a way for me to add a blanket default that makes semrush site audit know that all my pages are lang="en" ?

答:
If you have a common header and all that pages are part of the same domain, you can use

<link rel="alternate" hreflang="x-default" href="https://www.yourURL.com<?php echo $_SERVER["REQUEST_URI"]; ?>" />
 in the head and the "x-default" handles the language for you.
Here is a url that explains better the usage of 'x-default':
https://webmasters.googleblog.com/2013/04/x-default-hreflang-for-international-pages.html

I hope it helps.


问:
What's wrong in this loop?
I checked and i don't found errors:

```<code>$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

for($i = 1; $i <=$_SESSION['variable']; $i++){
  $listo[$i] = $preparado1[$i] . $segundo[1];
}

for($i = ($_SESSION['variable'] + 1) ; $i <= ($_SESSION['variable'] * 2); $i++){
  for($n = 1; $n <=$_SESSION['variable']; $n++){
    $listo[$i] = $preparado1[$n] . $segundo[2];
  }
}

for($i = 1;$i <=$_SESSION['variable'] * $_SESSION['extension']; $i++ ){
  echo   $final[$i] . "</br>";
}
</code>```

I  recibe this:

```<code>MiguelBeltran
CarlosBeltran
CarlosSanz
CarlosSanz
</code>```

But I should recibe this:

```<code>MiguelBeltran
CarlosBeltran
MiguelSanz
CarlosSanz
</code>```

Thanks!!

答:
```<code>$preparado[1] = "Miguel";
$preparado[1] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";
</code>```

You assigned $preparado[1] twice.

Title: What's wrong in this loop?

Body:
I checked and i don't found errors:

$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

for($i = 1; $i <=$_SESSION['variable']; $i++){
  $listo[$i] = $preparado1[$i] . $segundo[1];
}

for($i = ($_SESSION['variable'] + 1) ; $i <= ($_SESSION['variable'] * 2); $i++){
  for($n = 1; $n <=$_SESSION['variable']; $n++){
    $listo[$i] = $preparado1[$n] . $segundo[2];
  }
}

for($i = 1;$i <=$_SESSION['variable'] * $_SESSION['extension']; $i++ ){
  echo   $final[$i] . "
";
}

I  recibe this:

MiguelBeltran
CarlosBeltran
CarlosSanz
CarlosSanz

But I should recibe this:

MiguelBeltran
CarlosBeltran
MiguelSanz
CarlosSanz

Thanks!!

Body:
$preparado[1] = "Miguel";
$preparado[1] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

You assigned $preparado[1] twice.


问:
Flask UWSGI ModuleNotFound
I have a Flask application that I'm trying to configure for a production environment. So far, during testing python app.py inside of a virtualenv works fine.

However, I'm beginning to configure the application to begin using UWSGI. When I attempt to start the Flask app using

$ uwsgi -s /tmp/myapplication.sock --manage-script-name --mount /myapplication=app:app
 --virtualenv /path/to/my/venv

I get a

ModuleNotFoundError: No module named 'flask_httpauth'

I was wondering if anyone has experience w/ that authentication module and if they have any advice on what I should do. I'm unsure of why the development server starts without an issue, but the uwsgi server (that I pass the same virtualenv that's used for the dev server) runs into import issues

答:
I was able to resolve this issue by setting the home path to my virtualenv directory (.venv in my case):

```<code># uwsgi.ini
home = /Users/floatingrock/Desktop/projects/google_v2/.venv/
</code>```

If you're wondering, I got the full path using pwd.

Title: Flask UWSGI ModuleNotFound

Body:
I was able to resolve this issue by setting the home path to my virtualenv directory (.venv in my case):

# uwsgi.ini
home = /Users/floatingrock/Desktop/projects/google_v2/.venv/

If you're wondering, I got the full path using pwd.


问:
Parsing Returned JSON
I am trying to print some of the values from the API call to the console, but I am receiving an error I am unfamiliar with:

System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'

I think that I might be incorrectly accessing the values returned to by the API, but I am not 100% sure whats wrong

I've looked at a few other posts about this same issue and tried to implement the fixes suggested, but none of them were able to solve my problem. I think mine is unique as my JSON object is different from others I have seen.

```<code>namespace CarQueryAPI
{
    class CarResult
    {
        public string model_name { get; set; }
    }
}

namespace CarQueryAPI
{
    class Program
    {
        public static void Main(string[] args)
    {
        apiCall();
        Console.ReadKey();
    }

    public static void apiCall()
    {
        //client to invoke the car query api
        WebClient client = new WebClient();

        Task<String> carQueryTask = null;// Task<string> that queries carQuery

        // url for API (no key required)
        string url = "https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&make=toyota&model=camry&year=2005";

        try
        {
           //request info from the api
            carQueryTask = client.DownloadStringTaskAsync(url);

            string result = carQueryTask.Result.Remove(0, 2);
            result = result.Remove(result.Length - 4, 4);

            dynamic json = JsonConvert.DeserializeObject(result);

            string model_name = json.model_name;

            Console.WriteLine(model_name);
        }

        catch (WebException)
        {
            // check whether Task failed
            if (carQueryTask.Status == TaskStatus.Faulted)
            {
                Console.WriteLine("Call Failed");
            }
        }
    }
}
</code>```

}

i need the result to e just the model_name of the car being returned from the call so that I can see how to capture the others as well.

The following is some of the JSON object being returned:

```<code>?({"Trims":[{"model_id":"38988","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 GLi Automatic","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2360","model_engine_cyl":null,"model_engine_type":null,"model_engine_valves_per_cyl":"4","model_engine_power_ps":"152","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"4000","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":null,"model_top_speed_kph":"197","model_0_to_100_kph":"10.6","model_drive":"Front","model_transmission_type":"Automatic","model_seats":"5","model_doors":"4","model_weight_kg":"920","model_length_mm":null,"model_width_mm":null,"model_height_mm":null,"model_wheelbase_mm":"2730","model_lkm_hwy":null,"model_lkm_mixed":null,"model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"},{"model_id":"38999","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 WT-i","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2362","model_engine_cyl":"4","model_engine_type":"in-line","model_engine_valves_per_cyl":"4","model_engine_power_ps":"153","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"3800","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":"Gasoline - Premium","model_top_speed_kph":"210","model_0_to_100_kph":"9.4","model_drive":"Front","model_transmission_type":null,"model_seats":"5","model_doors":"4","model_weight_kg":"1465","model_length_mm":"4820","model_width_mm":"1800","model_height_mm":"1510","model_wheelbase_mm":"2680","model_lkm_hwy":null,"model_lkm_mixed":"8.7","model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"}
</code>```

...etc

EDIT:

Changed some of the code as you all suggested, but now I am receiving this error:

Unexpected end when deserializing object. Path 'Trims[18]', line 1, position 19143

答:
I was able to get what I was looking for from the following changes, I had removed to much from the JSON initially and I was parsing it incorrectly. Thank you to everyone who answered or commented so much! You all helped me a lot!

``
    class Program
    {
        public static void Main(string[] args)
        {
            apiCall();
            Console.ReadKey();
        }

```<code>    public static void apiCall()
    {
        //client to invoke the car query api
        WebClient client = new WebClient();

        Task<String> carQueryTask = null;// Task<string> that queries carQuery

        // url for API (no key required)
        string url = "https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&make=toyota&model=camry&year=2005";

        try
        {
            //request info from the api
            carQueryTask = client.DownloadStringTaskAsync(url);

            string result = carQueryTask.Result.Remove(0, 2);
            result = result.Remove(result.Length - 2, 2);

            dynamic json = JsonConvert.DeserializeObject(result);

            var model_name = json.Trims[0].model_name;

            Console.WriteLine(model_name);

        }

        catch (WebException)
        {
            // check whether Task failed
            if (carQueryTask.Status == TaskStatus.Faulted)
            {
                Console.WriteLine("Call Failed");
            }
        }
    }
}
</code>```

}

``

Title: Parsing Returned JSON

Body:
I am trying to print some of the values from the API call to the console, but I am receiving an error I am unfamiliar with:

System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'

I think that I might be incorrectly accessing the values returned to by the API, but I am not 100% sure whats wrong

I've looked at a few other posts about this same issue and tried to implement the fixes suggested, but none of them were able to solve my problem. I think mine is unique as my JSON object is different from others I have seen.

namespace CarQueryAPI
{
    class CarResult
    {
        public string model_name { get; set; }
    }
}

namespace CarQueryAPI
{
    class Program
    {
        public static void Main(string[] args)
    {
        apiCall();
        Console.ReadKey();
    }

    public static void apiCall()
    {
        //client to invoke the car query api
        WebClient client = new WebClient();

        Task<String> carQueryTask = null;// Task<string> that queries carQuery

        // url for API (no key required)
        string url = "https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&make=toyota&model=camry&year=2005";

        try
        {
           //request info from the api
            carQueryTask = client.DownloadStringTaskAsync(url);

            string result = carQueryTask.Result.Remove(0, 2);
            result = result.Remove(result.Length - 4, 4);

            dynamic json = JsonConvert.DeserializeObject(result);

            string model_name = json.model_name;

            Console.WriteLine(model_name);
        }

        catch (WebException)
        {
            // check whether Task failed
            if (carQueryTask.Status == TaskStatus.Faulted)
            {
                Console.WriteLine("Call Failed");
            }
        }
    }
}

}

i need the result to e just the model_name of the car being returned from the call so that I can see how to capture the others as well.

The following is some of the JSON object being returned:

?({"Trims":[{"model_id":"38988","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 GLi Automatic","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2360","model_engine_cyl":null,"model_engine_type":null,"model_engine_valves_per_cyl":"4","model_engine_power_ps":"152","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"4000","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":null,"model_top_speed_kph":"197","model_0_to_100_kph":"10.6","model_drive":"Front","model_transmission_type":"Automatic","model_seats":"5","model_doors":"4","model_weight_kg":"920","model_length_mm":null,"model_width_mm":null,"model_height_mm":null,"model_wheelbase_mm":"2730","model_lkm_hwy":null,"model_lkm_mixed":null,"model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"},{"model_id":"38999","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 WT-i","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2362","model_engine_cyl":"4","model_engine_type":"in-line","model_engine_valves_per_cyl":"4","model_engine_power_ps":"153","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"3800","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":"Gasoline - Premium","model_top_speed_kph":"210","model_0_to_100_kph":"9.4","model_drive":"Front","model_transmission_type":null,"model_seats":"5","model_doors":"4","model_weight_kg":"1465","model_length_mm":"4820","model_width_mm":"1800","model_height_mm":"1510","model_wheelbase_mm":"2680","model_lkm_hwy":null,"model_lkm_mixed":"8.7","model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"}

...etc

EDIT:

Changed some of the code as you all suggested, but now I am receiving this error:

Unexpected end when deserializing object. Path 'Trims[18]', line 1, position 19143

Body:
I was able to get what I was looking for from the following changes, I had removed to much from the JSON initially and I was parsing it incorrectly. Thank you to everyone who answered or commented so much! You all helped me a lot!

``
    class Program
    {
        public static void Main(string[] args)
        {
            apiCall();
            Console.ReadKey();
        }

    public static void apiCall()
    {
        //client to invoke the car query api
        WebClient client = new WebClient();

        Task<String> carQueryTask = null;// Task<string> that queries carQuery

        // url for API (no key required)
        string url = "https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&make=toyota&model=camry&year=2005";

        try
        {
            //request info from the api
            carQueryTask = client.DownloadStringTaskAsync(url);

            string result = carQueryTask.Result.Remove(0, 2);
            result = result.Remove(result.Length - 2, 2);

            dynamic json = JsonConvert.DeserializeObject(result);

            var model_name = json.Trims[0].model_name;

            Console.WriteLine(model_name);

        }

        catch (WebException)
        {
            // check whether Task failed
            if (carQueryTask.Status == TaskStatus.Faulted)
            {
                Console.WriteLine("Call Failed");
            }
        }
    }
}

}

``


问:
Yahoo Finance API like chart
I want to create a chart very similar to yahoo Finance interactive chart in a .NET application. The interactive chart on Yahoo finance is not included in their developer API. Has anyone tried to leverage their API to create a similar chart? Although the chart is very much like the one used on Yahoo, the data used for my analysis is not Stock data. So, I will not be able to call the Yahoo Url by feeding any query params.

Any suggestions?

答:
If your looking at a web based chart, the flot graphs for jQuery are a good option IMHO. They look pretty schnazzy, are interactive and are very simple to get working.

http://plugins.jquery.com/project/flot

Title: Yahoo Finance API like chart

OwnerDisplayName: Mainstay

ContentLicense: CC BY-SA 2.5


问:
Group a Ruby Array of Dates by Month and Year into a Hash
Let's say I had a Ruby Array of Dates like:

```<code>2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
</code>```

What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:

```<code>{
    2011 => {
        1   => [2011-01-20, 2011-01-23],
        2   => [2011-02-01, 2011-02-15],
        3  => [2011-03-21],
    }
}
</code>```

I can do this by iterating over everything and extracting years, months and so on, then comining them.

Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?

答:
This gets you pretty close, you just need to change the numerical month number into a textual month name:</p>

```<code>dates = %w(
2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
)

grouped = dates.inject({}) do |ret, date|
  y,m,d = date.split('-')
  ret[y] ||= {}
  # Change 'm' into month name here
  ret[y][m] ||= []
  ret[y][m] << date
  ret
end

puts grouped.inspect
</code>```

Body:
Let's say I had a Ruby Array of Dates like:

2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21

What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:

{
    2011 => {
        1   => [2011-01-20, 2011-01-23],
        2   => [2011-02-01, 2011-02-15],
        3  => [2011-03-21],
    }
}

I can do this by iterating over everything and extracting years, months and so on, then comining them.

Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?

Body:
This gets you pretty close, you just need to change the numerical month number into a textual month name:

dates = %w(
2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
)

grouped = dates.inject({}) do |ret, date|
  y,m,d = date.split('-')
  ret[y] ||= {}
  # Change 'm' into month name here
  ret[y][m] ||= []
  ret[y][m] << date
  ret
end

puts grouped.inspect


问:
AutoFixure Fixture.Build().With() with different values
Consider a class

```<code>class A
{
    public class NestedA
    {
        public string StrWithInt { get; set; }

        public string Str1 { get; set; }

        public string Str2 { get; set; }
    }

    public List<NestedA> Items { get; set; }
}
</code>```

I am using AutoFixture framework for generating instances of class A with random contents.

The NestedA's class property StrWithInt is a string type but its value has to be a number, int value. So I am using a With() method to customize generation.

My code looks like below:

```<code>Random r = new Random();
Fixture fixture = new Fixture();
fixture.Customize<A.NestedA>(ob =>
    ob.With(p => p.StrWithInt, r.Next().ToString())
);
var sut = fixture.Build<A>().Create();

foreach (var it in sut.Items)
{
   Console.WriteLine($"StrWithInt: {it.StrWithInt}");
}
Console.ReadLine();
</code>```

I get a such result.

StrWithInt: 340189285

  StrWithInt: 340189285

  StrWithInt: 340189285

All values are same. But I am expected to see different values of this property.
How Can I reach it?

答:
The With(...) method has many overloads among which you can find the  following:

```<code>IPostprocessComposer<T> With<TProperty>(
      Expression<Func<T, TProperty>> propertyPicker,
      Func<TProperty> valueFactory);
</code>```

So you can use this one via passing factory of random numbers and after this result always will be different:

```<code>fixture.Customize<A.NestedA>(ob =>
    ob.With(p => p.StrWithInt, () => r.Next().ToString())
);
</code>```

In your case you choose the static one which always assign the same value to the specified property.

Body:
Consider a class

class A
{
    public class NestedA
    {
        public string StrWithInt { get; set; }

        public string Str1 { get; set; }

        public string Str2 { get; set; }
    }

    public List<NestedA> Items { get; set; }
}

I am using AutoFixture framework for generating instances of class A with random contents.

The NestedA's class property StrWithInt is a string type but its value has to be a number, int value. So I am using a With() method to customize generation.

My code looks like below:

Random r = new Random();
Fixture fixture = new Fixture();
fixture.Customize(ob =>
    ob.With(p => p.StrWithInt, r.Next().ToString())
);
var sut = fixture.Build().Create();

foreach (var it in sut.Items)
{
   Console.WriteLine($"StrWithInt: {it.StrWithInt}");
}
Console.ReadLine();

I get a such result.

StrWithInt: 340189285

  StrWithInt: 340189285

  StrWithInt: 340189285

All values are same. But I am expected to see different values of this property.
How Can I reach it?

Body:
The With(...) method has many overloads among which you can find the  following:

IPostprocessComposer<T> With<TProperty>(
      Expression<Func<T, TProperty>> propertyPicker,
      Func<TProperty> valueFactory);

So you can use this one via passing factory of random numbers and after this result always will be different:

fixture.Customize<A.NestedA>(ob =>
    ob.With(p => p.StrWithInt, () => r.Next().ToString())
);

In your case you choose the static one which always assign the same value to the specified property.


问:
Highchart not showing on mobile
I have a issue with my charts working in highcharts.

All my charts are displaying correctly on desktop , in Chrome/FF/IE/Safari

But when i'm on mobile, any of them are showing.
I have nothing on my log so I would like to know how can i fix them,

There is the link for the charts :
http://www.chahinecapital.com/fonds/

You can go on the sub heading Digital Star Europe , and click the button for ACTIFS as exemple.

There is also my loadEurope.js , where i initialize the charts

```<code>   jQuery(document).ready(function($) {
    Highcharts.setOptions({
    lang: {
        months: [
            'Janvier', 'Février', 'Mars', 'Avril',
            'Mai', 'Juin', 'Juillet', 'Août',
            'Septembre', 'Octobre', 'Novembre', 'Décembre'
        ],
        weekdays: [
            'Dimanche', 'Lundi', 'Mardi', 'Mercredi',
            'Jeudi', 'Vendredi', 'Samedi'
        ],
        shortMonths: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil',
                      'Aout', 'Sept', 'Oct', 'Nov', 'Déc'
        ]
    }
});

$.get('http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/volatilityFR.csv', function(data) {
    $('#EuropeVolatility').highcharts({

          yAxis: [{

                labels: {
                    format: '{value} %',

                },
                title: {
                    text: ' ',
                }

            }],
        data: {
          csv: data,
        },
        series: [{
            color: '#682666',
          }, {
            color: '#ed8322',
          },{
            color: '#B7ADA5',
             }],
        xAxis: {
            tickPixelInterval: 50,
        },
        title:{
            text:null
        }
      });
    });

$("#EuropeAllocPaysBtn").click(function() {
$.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/countryFR.csv", function(csv) {
    $('#EuropeAllocPays').highcharts({
        chart: {
            type: 'pie',
            options3d: {
                enabled: true,
                alpha: 45,
                beta: 0
            }
        },
        plotOptions: {
             pie: {
                 allowPointSelect: true,
                 cursor: 'pointer',
                 depth: 35,
                 dataLabels: {
                     enabled: false
                 },
                 showInLegend: true
             }
         },
        data: {
            csv: csv
        },
        title:{
            text:null
        }
    });
});
});

$("#EuropeAllocSecteursBtn").click(function() {
    $.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/secteursFR.csv", function(csv) {
        $('#EuropeAllocSecteurs').highcharts({
             chart: {

                 type: 'pie',
                 options3d: {
                     enabled: true,
                     alpha: 45,
                     beta: 0
                 }
             },
             plotOptions: {
                 pie: {
                     allowPointSelect: true,
                     cursor: 'pointer',
                     depth: 35,
                     dataLabels: {
                         enabled: false
                        },
                     showInLegend: true
                    }
             },
            data: {
                csv: csv
            },
            title:{
                text:null
            }
        });
    });
    });

$("#EuropeActifsBtn").click(function() {
    $.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/assetsFR.csv", function(csv) {
        $('#EuropeActifs').highcharts({

             yAxis: [{
                    gridLineWidth: 0,
                    labels: {
                        format: '{value:,.0f}',

                    },
                    title: {
                        text: 'Nombre de parts',
                    },
                    opposite: true
                },
                {
                    labels: {
                        format: '{value}',
                        formatter: function(){
                            return this.value/100000 + "M";
                          }

                    },
                    title: {
                        text: 'Actifs en \u20AC ',

                    }

                }],

            data: {
                csv: csv
            },
            series: [{
                yAxis:1,
                color: '#682666',
              }, {
                yAxis:0,
                color: '#ed8322',
              }],
              title:{
                    text:null
                }
        });
    });
});

$("#EuropePerformancesPeriodeBtn").click(function() {
    $.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/performancesFR.csv", function(csv) {
        $('#EuropePerformancesPeriode').highcharts({
            yAxis: [{
                labels: {
                    format: '{value} %',

                },
                title: {
                    text: ' ',
                }

            }],
            xAxis:{
                tickInterval:1,
            },
            chart: {
                type: 'column'
            },

            data: {
                csv: csv
            },
            series: [{
                color: '#682666',
              }, {
                color: '#ed8322',
              },{
                color: '#B7ADA5',
                 }],
                 title:{
                        text:null
                    }
        });
    });
 });
});
</code>```

Thanks a lot for your help

Jordan

答:
I went through this exact same problem with another library, so I will put an answer here, maybe it will help someone.

Just to be clear, my problem was with AM4CHARTS library.

All charts working fine in Desktop, even when I was setting chrome and firefox to mobile mode, but not showing in Mobile.

The issue in my case was, for some reason, the browser cache.

I did clean the cache for the last 24 hours at chrome in android, and the charts went back.

Hope this helps anyone who might step into this.

Title: Highchart not showing on mobile

Body:
I have a issue with my charts working in highcharts.

All my charts are displaying correctly on desktop , in Chrome/FF/IE/Safari

But when i'm on mobile, any of them are showing.
I have nothing on my log so I would like to know how can i fix them,

There is the link for the charts :
http://www.chahinecapital.com/fonds/

You can go on the sub heading Digital Star Europe , and click the button for ACTIFS as exemple.

There is also my loadEurope.js , where i initialize the charts

   jQuery(document).ready(function($) {
    Highcharts.setOptions({
    lang: {
        months: [
            'Janvier', 'Février', 'Mars', 'Avril',
            'Mai', 'Juin', 'Juillet', 'Août',
            'Septembre', 'Octobre', 'Novembre', 'Décembre'
        ],
        weekdays: [
            'Dimanche', 'Lundi', 'Mardi', 'Mercredi',
            'Jeudi', 'Vendredi', 'Samedi'
        ],
        shortMonths: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil',
                      'Aout', 'Sept', 'Oct', 'Nov', 'Déc'
        ]
    }
});

$.get('http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/volatilityFR.csv', function(data) {
    $('#EuropeVolatility').highcharts({

          yAxis: [{

                labels: {
                    format: '{value} %',

                },
                title: {
                    text: ' ',
                }

            }],
        data: {
          csv: data,
        },
        series: [{
            color: '#682666',
          }, {
            color: '#ed8322',
          },{
            color: '#B7ADA5',
             }],
        xAxis: {
            tickPixelInterval: 50,
        },
        title:{
            text:null
        }
      });
    });

$("#EuropeAllocPaysBtn").click(function() {
$.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/countryFR.csv", function(csv) {
    $('#EuropeAllocPays').highcharts({
        chart: {
            type: 'pie',
            options3d: {
                enabled: true,
                alpha: 45,
                beta: 0
            }
        },
        plotOptions: {
             pie: {
                 allowPointSelect: true,
                 cursor: 'pointer',
                 depth: 35,
                 dataLabels: {
                     enabled: false
                 },
                 showInLegend: true
             }
         },
        data: {
            csv: csv
        },
        title:{
            text:null
        }
    });
});
});

$("#EuropeAllocSecteursBtn").click(function() {
    $.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/secteursFR.csv", function(csv) {
        $('#EuropeAllocSecteurs').highcharts({
             chart: {

                 type: 'pie',
                 options3d: {
                     enabled: true,
                     alpha: 45,
                     beta: 0
                 }
             },
             plotOptions: {
                 pie: {
                     allowPointSelect: true,
                     cursor: 'pointer',
                     depth: 35,
                     dataLabels: {
                         enabled: false
                        },
                     showInLegend: true
                    }
             },
            data: {
                csv: csv
            },
            title:{
                text:null
            }
        });
    });
    });

$("#EuropeActifsBtn").click(function() {
    $.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/assetsFR.csv", function(csv) {
        $('#EuropeActifs').highcharts({

             yAxis: [{
                    gridLineWidth: 0,
                    labels: {
                        format: '{value:,.0f}',

                    },
                    title: {
                        text: 'Nombre de parts',
                    },
                    opposite: true
                },
                {
                    labels: {
                        format: '{value}',
                        formatter: function(){
                            return this.value/100000 + "M";
                          }

                    },
                    title: {
                        text: 'Actifs en \u20AC ',

                    }

                }],

            data: {
                csv: csv
            },
            series: [{
                yAxis:1,
                color: '#682666',
              }, {
                yAxis:0,
                color: '#ed8322',
              }],
              title:{
                    text:null
                }
        });
    });
});

$("#EuropePerformancesPeriodeBtn").click(function() {
    $.get("http://www.chahinecapital.com/wp-content/themes/consulting-child/data/fonds/DigitalStarsEurope/performancesFR.csv", function(csv) {
        $('#EuropePerformancesPeriode').highcharts({
            yAxis: [{
                labels: {
                    format: '{value} %',

                },
                title: {
                    text: ' ',
                }

            }],
            xAxis:{
                tickInterval:1,
            },
            chart: {
                type: 'column'
            },

            data: {
                csv: csv
            },
            series: [{
                color: '#682666',
              }, {
                color: '#ed8322',
              },{
                color: '#B7ADA5',
                 }],
                 title:{
                        text:null
                    }
        });
    });
 });
});

Thanks a lot for your help

Jordan


问:
How to manually add an error bar (95% CI) to a barplot
I drew a cumulative barplot with ggplot2:

```<code>a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))
</code>```

It looks like this:

I want to add an error bar for each column.

So first, I manually calculated each 95% CI :

```<code>binom.test(2,45)$conf.int*100
binom.test(3,10)$conf.int*100
binom.test(5,18)$conf.int*100
binom.test(12,27)$conf.int*100
</code>```

Then, I use the geom_errorbar function:

```<code>a + geom_errorbar(ymin=0.2, ymax=0.4,width = 0.2, size=1)
</code>```

It does draw an error bar, but every error bars is the same:

Right now I am stuck: I was not able to find the solution for setting every error bar manually. I imagined something like this, but it won't work:

```<code>a + geom_errorbar(ymin=c(0.2,0.22,0.23,0.30), ymax=c(0.4,0.43,0.35,0.50))
#random number, I will put CI here
</code>```

Here is the error I get:

```<code>Aesthetics must be either length 1 or the same as the data (100): ymin, ymax
</code>```

Any ideas of what to do to get something like this?
Thanks!

EDIT:
Here is the 10 first rows of my database (datasilice2):

```<code>> dput(head(datasilice2, 10))
structure(list(Duree_exposition_4gpes = c(3, 3, 0, 1, 0, 1, 2,
2, 1, 3), Antinucléaires_sup_ou_egal_200 = c(1, 0, 0, 1, 1, 1,
0, 0, 1, 1)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

As suggested, I created a new dataframe and tried to feed that into the geom_errorbar:

```<code>a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))

newdf <- data.frame(xcol=c(0,1,2,3),ymincol=c(0.2,0.3,0.4,0.5),ymaxcol=c(0.25,0.30,0.45,0.5))
a + geom_errorbar(data=newdf,aes(x=xcol,ymin=ymincol,ymax=ymaxcol))
</code>```

But here is a new error:

```<code>Error in factor(Antinucléaires_sup_ou_egal_200) :
  object 'Antinucléaires_sup_ou_egal_200' not found
</code>```

答:
The following code will add the error bars in a percentage scale.

In the two middle bars the error bars one goes up to 100% and the other starts at 0%, because all data points for each of those groups were 1 or 0, respectively. With actual data this will probably change.

```<code>library(ggplot2)
library(scales)
library(dplyr)

datasilice2 %>%
  group_by(Duree_exposition_4gpes) %>%
  summarise(N = n(),
            Sum = sum(Antinucléaires_sup_ou_egal_200),
            LimInf = binom.test(Sum, N)$conf.int[1],
            LimSup = binom.test(Sum, N)$conf.int[2],
            Sum = Sum/N) %>%
  ggplot(aes(x = Duree_exposition_4gpes, y = Sum,
             fill = factor(Sum))) +
  geom_bar(stat = "identity",
           position = position_dodge(), show.legend = FALSE,
           colour = NA, alpha = 0.4) +
  scale_fill_manual(values = rep("red", 4)) +
  geom_errorbar(aes(ymin = LimInf, ymax = LimSup,
                    width = 0.2)) +
  scale_y_continuous(name = "Yes",
                     limits=c(0, 1),
                     oob = rescale_none,
                     breaks = seq(0, 1, 0.05),
                     labels = percent_format(suffix = "%", accuracy = 1))
</code>```

If you want to have each bar with its own colour you can do

```<code>scale_fill_manual(values = c("red", "yellow", "green", "blue"))
</code>```

As for the summarise function, it executes the following steps:

N = n() - get the number of rows

Sum = sum(Antinucléaires_sup_ou_egal_200) - sum the 1s, the size of the bars

LimInf and LimSup - function binom.test needs the total data size (N) and the number of successes (Sum). This is why the proportion is only computed in the next code line.

Sum = Sum/N - compute the proportion of successes.

Body:
I drew a cumulative barplot with ggplot2:

a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))

It looks like this:

I want to add an error bar for each column.

So first, I manually calculated each 95% CI :

binom.test(2,45)$conf.int*100
binom.test(3,10)$conf.int*100
binom.test(5,18)$conf.int*100
binom.test(12,27)$conf.int*100

Then, I use the geom_errorbar function:

a + geom_errorbar(ymin=0.2, ymax=0.4,width = 0.2, size=1)

It does draw an error bar, but every error bars is the same:

Right now I am stuck: I was not able to find the solution for setting every error bar manually. I imagined something like this, but it won't work:

a + geom_errorbar(ymin=c(0.2,0.22,0.23,0.30), ymax=c(0.4,0.43,0.35,0.50))
#random number, I will put CI here

Here is the error I get:

Aesthetics must be either length 1 or the same as the data (100): ymin, ymax

Any ideas of what to do to get something like this?
Thanks!

EDIT:
Here is the 10 first rows of my database (datasilice2):

> dput(head(datasilice2, 10))
structure(list(Duree_exposition_4gpes = c(3, 3, 0, 1, 0, 1, 2,
2, 1, 3), Antinucléaires_sup_ou_egal_200 = c(1, 0, 0, 1, 1, 1,
0, 0, 1, 1)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))

As suggested, I created a new dataframe and tried to feed that into the geom_errorbar:

a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))

newdf <- data.frame(xcol=c(0,1,2,3),ymincol=c(0.2,0.3,0.4,0.5),ymaxcol=c(0.25,0.30,0.45,0.5))
a + geom_errorbar(data=newdf,aes(x=xcol,ymin=ymincol,ymax=ymaxcol))

But here is a new error:

Error in factor(Antinucléaires_sup_ou_egal_200) :
  object 'Antinucléaires_sup_ou_egal_200' not found

Body:
The following code will add the error bars in a percentage scale.

In the two middle bars the error bars one goes up to 100% and the other starts at 0%, because all data points for each of those groups were 1 or 0, respectively. With actual data this will probably change.

library(ggplot2)
library(scales)
library(dplyr)

datasilice2 %>%
  group_by(Duree_exposition_4gpes) %>%
  summarise(N = n(),
            Sum = sum(Antinucléaires_sup_ou_egal_200),
            LimInf = binom.test(Sum, N)$conf.int[1],
            LimSup = binom.test(Sum, N)$conf.int[2],
            Sum = Sum/N) %>%
  ggplot(aes(x = Duree_exposition_4gpes, y = Sum,
             fill = factor(Sum))) +
  geom_bar(stat = "identity",
           position = position_dodge(), show.legend = FALSE,
           colour = NA, alpha = 0.4) +
  scale_fill_manual(values = rep("red", 4)) +
  geom_errorbar(aes(ymin = LimInf, ymax = LimSup,
                    width = 0.2)) +
  scale_y_continuous(name = "Yes",
                     limits=c(0, 1),
                     oob = rescale_none,
                     breaks = seq(0, 1, 0.05),
                     labels = percent_format(suffix = "%", accuracy = 1))

If you want to have each bar with its own colour you can do

scale_fill_manual(values = c("red", "yellow", "green", "blue"))

As for the summarise function, it executes the following steps:

N = n() - get the number of rows

Sum = sum(Antinucléaires_sup_ou_egal_200) - sum the 1s, the size of the bars

LimInf and LimSup - function binom.test needs the total data size (N) and the number of successes (Sum). This is why the proportion is only computed in the next code line.

Sum = Sum/N - compute the proportion of successes.


问:
MySql.Data.MySqlClient.MySqlException: Duplicate entry
How is it possible to get duplicate entry error from this auto scaffold from .net identity code:

```<code>        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {  UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
</code>```

Produces this stacktrace:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
        An unhandled exception has occurred while executing the request.
  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Duplicate entry '3ab1a765-c575-4a50-ba42-6d282ccb24a6' for key 'PRIMARY' ---> MySql.Data.MySqlClient.MySqlException: Duplicate entry '3ab1a765-c575-4a50-ba42-6d282ccb24a6' for key 'PRIMARY'
     at MySqlConnector.Core.ServerSession.TryAsyncContinuation(Task1 task) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 1252
     at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  --- End of stack trace from previous location where exception was thrown ---
     at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
  --- End of stack trace from previous location where exception was thrown ---
     at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ResultSet.cs:line 43
     --- End of inner exception stack trace ---
     at MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 81
     at MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 307
     at MySql.Data.MySqlClient.MySqlDataReader.CreateAsync(MySqlCommand command, CommandBehavior behavior, ResultSetProtocol resultSetProtocol, IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 292
     at MySqlConnector.Core.TextCommandExecutor.ExecuteReaderAsync(String commandText, MySqlParameterCollection parameterCollection, CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\TextCommandExecutor.cs:line 37
     at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
     --- End of inner exception stack trace ---
     at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple2 parameters, CancellationToken cancellationToken)
     at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList1 entriesToSave, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
     at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9.CreateAsync(TUser user, CancellationToken cancellationToken)
     at Chuchubi.Data.MultiTenant.TenantUserStore.CreateAsync(ApplicationUser user, CancellationToken cancellationToken) in C:\Users\Dropbox\Code\chuchubi-backend\Chuchubi.Data\MultiTenant\TenantUserStore.cs:line 30
     at Microsoft.AspNetCore.Identity.UserManager1.CreateAsync(TUser user)
     at Microsoft.AspNetCore.Identity.UserManager1.CreateAsync(TUser user, String password)
     at Chuchubi.Areas.Identity.Pages.Account.RegisterModel.OnPostAsync(String returnUrl) in C:\Users\Dropbox\Code\chuchubi-backend\Chuchubi\Areas\Identity\Pages\Account\Register.cshtml.cs:line 71
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
     at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
     at SaasKit.Multitenancy.Internal.TenantResolutionMiddleware1.Invoke(HttpContext context, ITenantResolver1 tenantResolver)
     at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]

This was from auto generated code from visual studio.

EDIT:

MySql version details:

```<code>'immediate_server_version', '999999'
'innodb_version', '8.0.16'
'original_server_version', '999999'
'protocol_version', '10'
'slave_type_conversions', ''
'tls_version', 'TLSv1,TLSv1.1,TLSv1.2'
'version', '8.0.16'
'version_comment', 'MySQL Community Server - GPL'
'version_compile_machine', 'x86_64'
'version_compile_os', 'Win64'
'version_compile_zlib', '1.2.11'
</code>```

my csproj:

```<code>    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.4" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
    <PackageReference Include="SaasKit.Multitenancy" Version="1.1.4" />
</code>```

This is done on a empty database, after the error there is no user being inserted in the database!

答:
Ok attempting to replicated this in a clean project i managed to figure it out.
So the application is multi-tenant, each identity user has a one on one relation with a tenant.

Using SaasKit i was caching the database model Tenant into memory, while creating a new user like so:

```<code>IdentityUser.Tenant = cachedTenant;
DbContext.SaveChanges();
</code>```

Entityframework sees the Tenant as a new tenant (not being tracked), therefor causing the duplicate message.

So the duplicate message was actually for the new tenant.

Fix by caching a 'view model' instead of the database model.

Body:
How is it possible to get duplicate entry error from this auto scaffold from .net identity code:

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {  UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by clicking here.");

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

Produces this stacktrace:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
        An unhandled exception has occurred while executing the request.
  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Duplicate entry '3ab1a765-c575-4a50-ba42-6d282ccb24a6' for key 'PRIMARY' ---> MySql.Data.MySqlClient.MySqlException: Duplicate entry '3ab1a765-c575-4a50-ba42-6d282ccb24a6' for key 'PRIMARY'
     at MySqlConnector.Core.ServerSession.TryAsyncContinuation(Task1 task) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 1252
     at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  --- End of stack trace from previous location where exception was thrown ---
     at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
  --- End of stack trace from previous location where exception was thrown ---
     at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ResultSet.cs:line 43
     --- End of inner exception stack trace ---
     at MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 81
     at MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 307
     at MySql.Data.MySqlClient.MySqlDataReader.CreateAsync(MySqlCommand command, CommandBehavior behavior, ResultSetProtocol resultSetProtocol, IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 292
     at MySqlConnector.Core.TextCommandExecutor.ExecuteReaderAsync(String commandText, MySqlParameterCollection parameterCollection, CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\TextCommandExecutor.cs:line 37
     at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
     --- End of inner exception stack trace ---
     at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple2 parameters, CancellationToken cancellationToken)
     at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList1 entriesToSave, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
     at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
     at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9.CreateAsync(TUser user, CancellationToken cancellationToken)
     at Chuchubi.Data.MultiTenant.TenantUserStore.CreateAsync(ApplicationUser user, CancellationToken cancellationToken) in C:\Users\Dropbox\Code\chuchubi-backend\Chuchubi.Data\MultiTenant\TenantUserStore.cs:line 30
     at Microsoft.AspNetCore.Identity.UserManager1.CreateAsync(TUser user)
     at Microsoft.AspNetCore.Identity.UserManager1.CreateAsync(TUser user, String password)
     at Chuchubi.Areas.Identity.Pages.Account.RegisterModel.OnPostAsync(String returnUrl) in C:\Users\Dropbox\Code\chuchubi-backend\Chuchubi\Areas\Identity\Pages\Account\Register.cshtml.cs:line 71
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
     at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
     at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
     at SaasKit.Multitenancy.Internal.TenantResolutionMiddleware1.Invoke(HttpContext context, ITenantResolver1 tenantResolver)
     at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]

This was from auto generated code from visual studio.

EDIT:

MySql version details:

'immediate_server_version', '999999'
'innodb_version', '8.0.16'
'original_server_version', '999999'
'protocol_version', '10'
'slave_type_conversions', ''
'tls_version', 'TLSv1,TLSv1.1,TLSv1.2'
'version', '8.0.16'
'version_comment', 'MySQL Community Server - GPL'
'version_compile_machine', 'x86_64'
'version_compile_os', 'Win64'
'version_compile_zlib', '1.2.11'

my csproj:

    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.4" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
    <PackageReference Include="SaasKit.Multitenancy" Version="1.1.4" />

This is done on a empty database, after the error there is no user being inserted in the database!

Body:
Ok attempting to replicated this in a clean project i managed to figure it out.
So the application is multi-tenant, each identity user has a one on one relation with a tenant.

Using SaasKit i was caching the database model Tenant into memory, while creating a new user like so:

IdentityUser.Tenant = cachedTenant;
DbContext.SaveChanges();

Entityframework sees the Tenant as a new tenant (not being tracked), therefor causing the duplicate message.

So the duplicate message was actually for the new tenant.

Fix by caching a 'view model' instead of the database model.


问:
Push an item to a deeply nested array in MongoDb
Is it possible (preferably using the C# Builders) to add a new item to a deeply nested array I.e. an array within an array within an array.

My data model looks something like :

```<code>public class Company
{
    public string Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Department> Departments { get; set; }
}

public class Department
{
    public string Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Managers> Managers { get; set; }
}

public class Manager
{
    public string Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Employee> Employees { get; set; }
}

public class Employee
{
    public string Id { get; set; }
    public string Name { get; set; }
}
</code>```

Which translates to:

```<code>{
    "Id": 12345,
    "Name": "Company Ltd",
    "Departments": [
        {
            "Id": 1,
            "Name": "Development",
            "Managers" : [
                {
                    "Id" : 5555,
                    "Name" : "The Boss",
                    "Employees": [
                        {
                            "Id" : 123,
                            "Name" : "Developer 1"
                        },
                        {
                            "Id" : 124,
                            "Name" : "Developer 2"
                        }
                    ]
                }
            ]
        }
    ]
}
</code>```

If I wanted to add another employee under a specific manager how would I go about doing that?

答:
In order to push to a nested array, you must make use of the positional operator $ in order to specify a matching outer array element to apply the operation to. For example:

```<code>db.collection.update(
    {"my_array._id": myTargetId},
    {$push: {"my_array.$.my_inner_array": myArrayElem}}
);
</code>```

This breaks down, however, for traversing nested arrays--that is, you can only use the positional operator on the single array, not any nested ones. This is a well-defined problem as noted in the MongoDB documentation.

If you absolutely need to perform these kinds of nested array operations, then you have a couple of options available to you:

The first, and preferred, is to update your document structure and avoid nesting arrays more than one level deep. This will avoid the issue altogether, but will require any existing data to be migrated to the new structure and additional efforts to be made to structure the data in the way you need on the fly on retrieval. Separate client and server representations of your data will end up being required.

The second is to perform a series of less-reliable steps:

 1. Retrieve the original document.

 2. Locate the indexes for each array where your target element is located manually.

 3. Attempt an update on the specific index chain and attempt to match that index chain as well.

 4. Check the result of the update attempt--if it fails, then it's possible that the document was changed while the indexes were being calculated.

For example, if you wanted to update manager with ID 5555 to have the additional employee, you'd perform the following query after retrieving the indexes:

```<code>// Index chain found to be Departments.0 and Managers.0
db.collection.update(
    {
        "Id": 12345,
        "Departments.0.Managers.0.Id": 5555 // Specify index chain 0,0 and ensure that our target still has Id 5555.
    },
    { $push: {
        "Departments.0.Managers.0.Employees": myNewEmployee // Push to index chain 0,0
    }}

);
</code>```

Body:
Is it possible (preferably using the C# Builders) to add a new item to a deeply nested array I.e. an array within an array within an array.

My data model looks something like :

public class Company
{
    public string Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Department> Departments { get; set; }
}

public class Department
{
    public string Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Managers> Managers { get; set; }
}

public class Manager
{
    public string Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Employee> Employees { get; set; }
}

public class Employee
{
    public string Id { get; set; }
    public string Name { get; set; }
}

Which translates to:

{
    "Id": 12345,
    "Name": "Company Ltd",
    "Departments": [
        {
            "Id": 1,
            "Name": "Development",
            "Managers" : [
                {
                    "Id" : 5555,
                    "Name" : "The Boss",
                    "Employees": [
                        {
                            "Id" : 123,
                            "Name" : "Developer 1"
                        },
                        {
                            "Id" : 124,
                            "Name" : "Developer 2"
                        }
                    ]
                }
            ]
        }
    ]
}

If I wanted to add another employee under a specific manager how would I go about doing that?

Body:
In order to push to a nested array, you must make use of the positional operator $ in order to specify a matching outer array element to apply the operation to. For example:

db.collection.update(
    {"my_array._id": myTargetId},
    {$push: {"my_array.$.my_inner_array": myArrayElem}}
);

This breaks down, however, for traversing nested arrays--that is, you can only use the positional operator on the single array, not any nested ones. This is a well-defined problem as noted in the MongoDB documentation.

If you absolutely need to perform these kinds of nested array operations, then you have a couple of options available to you:

The first, and preferred, is to update your document structure and avoid nesting arrays more than one level deep. This will avoid the issue altogether, but will require any existing data to be migrated to the new structure and additional efforts to be made to structure the data in the way you need on the fly on retrieval. Separate client and server representations of your data will end up being required.

The second is to perform a series of less-reliable steps:

 1. Retrieve the original document.

 2. Locate the indexes for each array where your target element is located manually.

 3. Attempt an update on the specific index chain and attempt to match that index chain as well.

 4. Check the result of the update attempt--if it fails, then it's possible that the document was changed while the indexes were being calculated.

For example, if you wanted to update manager with ID 5555 to have the additional employee, you'd perform the following query after retrieving the indexes:

// Index chain found to be Departments.0 and Managers.0
db.collection.update(
    {
        "Id": 12345,
        "Departments.0.Managers.0.Id": 5555 // Specify index chain 0,0 and ensure that our target still has Id 5555.
    },
    { $push: {
        "Departments.0.Managers.0.Employees": myNewEmployee // Push to index chain 0,0
    }}

);


问:
Unity how handle onTouch event?
I add UI object Button and add the C# script with public function.
To button I add component Event Trigger, do events(Pointer Click and Pointer Down) and redirect to my function public void onClick()

On PC code works, but when I upload game to android and touch the object, code not works.

How to do onTouch event?

答:
Touches aren't Clicks

In order to handle touch input you need to check Input.touchCount and then query each touch with Input.GetTouch. Note that each Touch has an an ID that will be unique per finger and consistent across frames.

There are no easy OnClick like methods for touches, as touches can be a lot more complex (tap, long tap, drag, etc), so you will have to check inside Update() and handle the conversion from touch data to mouse analogs yourself.

Title: Unity how handle onTouch event?


问:
Aqueduct framework not generating migrations
I'm trying to generate a migration from a model using the command - "aqueduct db generate".

This is the model "request.dart" under lib > model (where i have the other models as well which were already migrated without any issues) :

import 'package:dbapi/dbapi.dart';

class Request extends ManagedObject<_Request> implements _Request {}

class _Request {

@managedPrimaryKey

int index;

String description;

}

It is however creating an empty migration because its not able to recognize the new model-"Request". Below is the output from "aqueduct db generate"

```<code>-- Aqueduct CLI Version: 2.5.0+1
-- Aqueduct project version: 2.5.0+1
-- Replaying migration files...
Replaying version 1
Replaying version 2
Replaying version 3
 -- The following ManagedObject<T> subclasses were found:
     Question
     UserProfile

* If you were expecting more declarations, ensure the files are visible in the application library file.

  -- Created new migration file (version 4).
</code>```

note: The new model "request.dart" has the same file permissions as the previous models that I could migrate.

Has anyone else run into the same issue? Appreciate the help !

答:
As Joe Conway said, I had to import the ManagedObject subclass into my controller:

```<code>import 'package:my_project/model/my_model.dart';
</code>```

After than running

```<code>aqueduct db generate
</code>```

created the correct migration file. I was eventually going to use the managed object in the controller anyway, but I wasn't there yet and I wanted to generate the migration file first.

Body:
I'm trying to generate a migration from a model using the command - "aqueduct db generate".

This is the model "request.dart" under lib > model (where i have the other models as well which were already migrated without any issues) :

import 'package:dbapi/dbapi.dart';

class Request extends ManagedObject<_Request> implements _Request {}

class _Request {

@managedPrimaryKey

int index;

String description;

}

It is however creating an empty migration because its not able to recognize the new model-"Request". Below is the output from "aqueduct db generate"

-- Aqueduct CLI Version: 2.5.0+1
-- Aqueduct project version: 2.5.0+1
-- Replaying migration files...
Replaying version 1
Replaying version 2
Replaying version 3
 -- The following ManagedObject<T> subclasses were found:
     Question
     UserProfile

* If you were expecting more declarations, ensure the files are visible in the application library file.

  -- Created new migration file (version 4).

note: The new model "request.dart" has the same file permissions as the previous models that I could migrate.

Has anyone else run into the same issue? Appreciate the help !

Body:
As Joe Conway said, I had to import the ManagedObject subclass into my controller:

import 'package:my_project/model/my_model.dart';

After than running

aqueduct db generate

created the correct migration file. I was eventually going to use the managed object in the controller anyway, but I wasn't there yet and I wanted to generate the migration file first.