问:
Can't build mod_wsgi on Windows 10 - "Cannot open include file: 'ws2tcpip.h'" - Have VS 2019 Build tools
I have apache 2.4 installed (64 bit), python 3.7 (64 bit) (installed from Anaconda, if that matters) and VS 2019 C++ build tools, with the SDK and everything else required to build this checked. I still cannot build mod_wsgi with pip install. How can I get this to work on Windows 10?

I have tried uninstalling and reinstalling, python, visual studio & visual studio build tools, and apache. I have tried all the various visual studio command prompts. I have checked stack overflow, github, and other sites. There were others with similar issues but the solution of installing build tools did not work for me because a.) I already had it, b.) I reinstalled everything and it still didn't work.

pip install mod_wsgi

Resulting error message:

```<code>Collecting mod_wsgi
  Using cached https://files.pythonhosted.org/packages/26/03/a3ed5abc2e66c82c40b0735c2f819c898d136879b00be4f5537126b6a4a4/mod_wsgi-4.6.7.tar.gz
Building wheels for collected packages: mod-wsgi
  Building wheel for mod-wsgi (setup.py) ... error
  ERROR: Complete output from command 'C:\Users\VC046230\AppData\Local\Continuum\anaconda3\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\VC046230\\AppData\\Local\\Temp\\pip-install-12r9v42f\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\VC046230\AppData\Local\Temp\pip-wheel-1q_bver8' --python-tag cp37:
  ERROR: C:\Users\VC046230\AppData\Local\Continuum\anaconda3\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url'
    warnings.warn(msg)
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.7
  creating build\lib.win-amd64-3.7\mod_wsgi
  copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi
  creating build\lib.win-amd64-3.7\mod_wsgi\server
  copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server
  copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server
  copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server
  creating build\lib.win-amd64-3.7\mod_wsgi\server\management
  copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management
  creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands
  copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands
  copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands
  creating build\lib.win-amd64-3.7\mod_wsgi\docs
  copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\docs
  creating build\lib.win-amd64-3.7\mod_wsgi\images
  copying images\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\images
  copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.7\mod_wsgi\images
  running build_ext
  building 'mod_wsgi.server.mod_wsgi' extension
  creating build\temp.win-amd64-3.7
  creating build\temp.win-amd64-3.7\Release
  creating build\temp.win-amd64-3.7\Release\src
  creating build\temp.win-amd64-3.7\Release\src\server
  C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\Apache24/include -IC:\Users\VC046230\AppData\Local\Continuum\anaconda3\include -IC:\Users\VC046230\AppData\Local\Continuum\anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\include" /Tcsrc/server\mod_wsgi.c /Fobuild\temp.win-amd64-3.7\Release\src/server\mod_wsgi.obj
  mod_wsgi.c
  C:\Users\VC046230\AppData\Local\Temp\pip-install-12r9v42f\mod-wsgi\src\server\wsgi_apache.h(39): fatal error C1083: Cannot open include file: 'ws2tcpip.h': No such file or directory
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.23.28105\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
  ----------------------------------------
  ERROR: Failed building wheel for mod-wsgi
</code>```

答:
I just solved the same problem. My config is Windows 10, Python 3.8.1, Apache2.4.39-Win64-VC15-OpenSSL1.1.1b, mod-wsgi 4.7.1.

1) I installed using Build Tools

Visual Studio Build Tools Main Components

SDK for Windows 10 (10.0.18362.0) since I'm using Windows 10

MSVC 140 - C++ VS 2015 (v.14.00)

2) Then I added C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin to PATH

3) Then I got the next error:

```<code>'apr_perms_set.h': No such file or directory'.
</code>```

I downloaded the file and put it into $APACHE_DIR\include

4) Then I got third error:

```<code>fatal error LNK1158: cannot run ‘rc.exe’.
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158
</code>```

I took following files rc.exe rcdll.dll from C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86 and paste them into C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin

5) Congratulations!

Body:
I have apache 2.4 installed (64 bit), python 3.7 (64 bit) (installed from Anaconda, if that matters) and VS 2019 C++ build tools, with the SDK and everything else required to build this checked. I still cannot build mod_wsgi with pip install. How can I get this to work on Windows 10?

I have tried uninstalling and reinstalling, python, visual studio & visual studio build tools, and apache. I have tried all the various visual studio command prompts. I have checked stack overflow, github, and other sites. There were others with similar issues but the solution of installing build tools did not work for me because a.) I already had it, b.) I reinstalled everything and it still didn't work.

pip install mod_wsgi

Resulting error message:

Collecting mod_wsgi
  Using cached https://files.pythonhosted.org/packages/26/03/a3ed5abc2e66c82c40b0735c2f819c898d136879b00be4f5537126b6a4a4/mod_wsgi-4.6.7.tar.gz
Building wheels for collected packages: mod-wsgi
  Building wheel for mod-wsgi (setup.py) ... error
  ERROR: Complete output from command 'C:\Users\VC046230\AppData\Local\Continuum\anaconda3\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\VC046230\\AppData\\Local\\Temp\\pip-install-12r9v42f\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\VC046230\AppData\Local\Temp\pip-wheel-1q_bver8' --python-tag cp37:
  ERROR: C:\Users\VC046230\AppData\Local\Continuum\anaconda3\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url'
    warnings.warn(msg)
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.7
  creating build\lib.win-amd64-3.7\mod_wsgi
  copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi
  creating build\lib.win-amd64-3.7\mod_wsgi\server
  copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server
  copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server
  copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server
  creating build\lib.win-amd64-3.7\mod_wsgi\server\management
  copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management
  creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands
  copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands
  copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands
  creating build\lib.win-amd64-3.7\mod_wsgi\docs
  copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\docs
  creating build\lib.win-amd64-3.7\mod_wsgi\images
  copying images\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\images
  copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.7\mod_wsgi\images
  running build_ext
  building 'mod_wsgi.server.mod_wsgi' extension
  creating build\temp.win-amd64-3.7
  creating build\temp.win-amd64-3.7\Release
  creating build\temp.win-amd64-3.7\Release\src
  creating build\temp.win-amd64-3.7\Release\src\server
  C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\Apache24/include -IC:\Users\VC046230\AppData\Local\Continuum\anaconda3\include -IC:\Users\VC046230\AppData\Local\Continuum\anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\include" /Tcsrc/server\mod_wsgi.c /Fobuild\temp.win-amd64-3.7\Release\src/server\mod_wsgi.obj
  mod_wsgi.c
  C:\Users\VC046230\AppData\Local\Temp\pip-install-12r9v42f\mod-wsgi\src\server\wsgi_apache.h(39): fatal error C1083: Cannot open include file: 'ws2tcpip.h': No such file or directory
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.23.28105\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
  ----------------------------------------
  ERROR: Failed building wheel for mod-wsgi

Body:
I just solved the same problem. My config is Windows 10, Python 3.8.1, Apache2.4.39-Win64-VC15-OpenSSL1.1.1b, mod-wsgi 4.7.1.

1) I installed using Build Tools

Visual Studio Build Tools Main Components

SDK for Windows 10 (10.0.18362.0) since I'm using Windows 10

MSVC 140 - C++ VS 2015 (v.14.00)

2) Then I added C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin to PATH

3) Then I got the next error:

'apr_perms_set.h': No such file or directory'.

I downloaded the file and put it into $APACHE_DIR\include

4) Then I got third error:

fatal error LNK1158: cannot run ‘rc.exe’.
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158

I took following files rc.exe rcdll.dll from C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86 and paste them into C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin

5) Congratulations!


来源: stackexchange

问:
How can I deduce the AWS Account ID from available BasicAWSCredentials?
Can't seem to find this anywhere in the docs; if I am authenticated with BasicAWSCredentials, e.g. AccessKeyId and SecretKey, is it possible to get the AWS Account ID?  </p>

答:
Using AWS Java SDK v2:

public String getAccountId(AwsCredentialsProvider awsAuth, Region awsRegion) {
    StsClient stsClient = getClient(awsAuth, awsRegion);

    GetCallerIdentityRequest request = GetCallerIdentityRequest
        .builder()
        .build();

    GetCallerIdentityResponse response = stsClient.getCallerIdentity(request);
    return response.account();
}
```

<pre class="lang-java prettyprint-override"><code>public StsClient getClient(AwsCredentialsProvider awsAuth, Region awsRegion) {
        return StsClient
                .builder()
                .credentialsProvider(awsAuth)
                .region(awsRegion)
                .build();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using AWS Java SDK v2:

public String getAccountId(AwsCredentialsProvider awsAuth, Region awsRegion) {
    StsClient stsClient = getClient(awsAuth, awsRegion);

    GetCallerIdentityRequest request = GetCallerIdentityRequest
        .builder()
        .build();

    GetCallerIdentityResponse response = stsClient.getCallerIdentity(request);
    return response.account();
}

public StsClient getClient(AwsCredentialsProvider awsAuth, Region awsRegion) {
        return StsClient
                .builder()
                .credentialsProvider(awsAuth)
                .region(awsRegion)
                .build();
}

ContentLicense: CC BY-SA 4.0


问:
google adwords API authorize request
I'm developing an integration between existing CPA system and Google AdWords.
Conversions are stored in the system, and the goal is to periodically, as a background task, parse conversions and send them to user's Google Ad account.

Here's what I figured so far:

I need a google application to which users will grant permission to push data to their ad account.

I need Oauth2 credentials to authorize my application AND users credentials to authorize the API request.

The process of creating and storing gclid is out of concern right now.

I use php client library https://github.com/googleads/googleads-php-lib, which has adsapi_php.ini configuration file. In this file, there are developer token, manager's account client ID, and OAuth2 credentials (cliendId, clientSecret, refreshToken).

However, when user gives access to my application via consent screen, I create OAuth2 object as follows:

```<code> $oAuth2Credential = new OAuth2([
        'authorizationUri'   => 'https://accounts.google.com/o/oauth2/v2/auth',
        'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
        'redirectUri'        => '<myEndpoint>',
        'clientId'           => '<myClientId>',
        'clientSecret'       => '<myClientSecret>',
        'scope'              => 'https://www.googleapis.com/auth/adwords'
    ]);
</code>```

If I understand correctly, I absolutely need to have web application OAuth credentials in order to have a callback to save user's access and refresh tokens, to use them later in my background task.

1) Does this credentials and the ones in adsapi_ini.php file has to be the same?

I've tried to generate a refresh token for my web type credentials to use in conf file, but it did not work. Right now I'm able to get a valid response when I have credentials for application type 'other' in the configuration file, and 'web' application credentials in Oauth2 object for getting user credentials, but I'm not sure this is correct way to do it.

2) How to authorize API request to push data to certain user's account?

Here's sample code:

```<code> $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->withClientCustomerId('<client-customer-id>')
        ->build();
</code>```

As I understand, session object is essential to build any further queries, including uploding conversions.

->fromFile() uses mentined configuration file to get my token and Auth data - basically authorize my application.

$oAuth2Credential is the OAuth2 object containing specific user's authorization data. The problem is that in documentation, this object is created by builder and uses the same method fromFile(), and I don't understand what data it must contain.

I store access_token and refresh_token in my database, and right now I'm building OAuth object as follows:

```<code>$oAuth2Credential = new OAuth2([
        'authorizationUri'   => 'https://accounts.google.com/o/oauth2/v2/auth',
        'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
        'redirectUri'        => '<myEndpoint>',
        'clientId'           => '<myClientId>',
        'clientSecret'       => '<myClientSecret>',
        'scope'              => 'https://www.googleapis.com/auth/adwords',
        'access_token'       => '<user_access_token>'
    ]);
</code>```

So basically just adding access_token to parameters that I'm using for getting this token from user. It works, but doesn't look like correct way to do this.

3) How to manage user's token expiration?

Documentation says that client library automatically handles refreshing tokens, but I don't understand how it will work in my case. Do I need to pass access_token with refresh_token in OAuth object when making API request and then it will refresh automatically, or do I need separate worker to periodically refresh user tokens to keep them valid?

答:
Here's a link that describes the flow of having the client authorise your app.
https://pete-bowen.com/google-ads-api/adwords-api-authorize-multiple-users

Once you've stored the client id, secret and refresh token (somewhere safe) you can use the OAuth2TokenBuilder class which has methods that allow you to provide a clientId, secret and refresh tokens rather than read them from the config file.

Title: google adwords API authorize request

Body:
I'm developing an integration between existing CPA system and Google AdWords.
Conversions are stored in the system, and the goal is to periodically, as a background task, parse conversions and send them to user's Google Ad account.

Here's what I figured so far:

I need a google application to which users will grant permission to push data to their ad account.

I need Oauth2 credentials to authorize my application AND users credentials to authorize the API request.

The process of creating and storing gclid is out of concern right now.

I use php client library https://github.com/googleads/googleads-php-lib, which has adsapi_php.ini configuration file. In this file, there are developer token, manager's account client ID, and OAuth2 credentials (cliendId, clientSecret, refreshToken).

However, when user gives access to my application via consent screen, I create OAuth2 object as follows:

 $oAuth2Credential = new OAuth2([
        'authorizationUri'   => 'https://accounts.google.com/o/oauth2/v2/auth',
        'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
        'redirectUri'        => '<myEndpoint>',
        'clientId'           => '<myClientId>',
        'clientSecret'       => '<myClientSecret>',
        'scope'              => 'https://www.googleapis.com/auth/adwords'
    ]);

If I understand correctly, I absolutely need to have web application OAuth credentials in order to have a callback to save user's access and refresh tokens, to use them later in my background task.

1) Does this credentials and the ones in adsapi_ini.php file has to be the same?

I've tried to generate a refresh token for my web type credentials to use in conf file, but it did not work. Right now I'm able to get a valid response when I have credentials for application type 'other' in the configuration file, and 'web' application credentials in Oauth2 object for getting user credentials, but I'm not sure this is correct way to do it.

2) How to authorize API request to push data to certain user's account?

Here's sample code:

 $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->withClientCustomerId('<client-customer-id>')
        ->build();

As I understand, session object is essential to build any further queries, including uploding conversions.

->fromFile() uses mentined configuration file to get my token and Auth data - basically authorize my application.

$oAuth2Credential is the OAuth2 object containing specific user's authorization data. The problem is that in documentation, this object is created by builder and uses the same method fromFile(), and I don't understand what data it must contain.

I store access_token and refresh_token in my database, and right now I'm building OAuth object as follows:

$oAuth2Credential = new OAuth2([
        'authorizationUri'   => 'https://accounts.google.com/o/oauth2/v2/auth',
        'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
        'redirectUri'        => '<myEndpoint>',
        'clientId'           => '<myClientId>',
        'clientSecret'       => '<myClientSecret>',
        'scope'              => 'https://www.googleapis.com/auth/adwords',
        'access_token'       => '<user_access_token>'
    ]);

So basically just adding access_token to parameters that I'm using for getting this token from user. It works, but doesn't look like correct way to do this.

3) How to manage user's token expiration?

Documentation says that client library automatically handles refreshing tokens, but I don't understand how it will work in my case. Do I need to pass access_token with refresh_token in OAuth object when making API request and then it will refresh automatically, or do I need separate worker to periodically refresh user tokens to keep them valid?


问:
Why does a CSS transition not work well with another animation based on jQuery's animate method?
I have a button that I wish to move when it is clicked, and while moving it should also flip. So there are two animations that take place at the same time, and have the same duration. I also have a CSS transition set up for all the properties of the button. It seems to me that only the CSS scale transform works when I use both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works well.

// find elements
var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

 // the bug: the following animation is not visible
  button.animate({
    "top": "-100px" // I tried without "px" too
  }, 0.15 * 1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: relative;
  transition: all 0.15s;
}</code>```

Hello World

  <button>Click me</button>

```

The JSFiddle is here.

Thank you.

答:
When you declare your button style as transition: all 0.15s; that is affecting the top property too. Therefore, in your flow:

The top animation does happen a few ms after the css manipulation

Every step of the top animation is subject to a transition

Due to the first, there's already a racing condition that may cause the top animation to go unnnoticed, but due to the second, there's also an easing over every step of jQuery's animation.

If not provided, $.fn.animate easing function defaults to swing which is defined as:

```<code> function( p ) {
    return 0.5 - Math.cos( p * Math.PI ) / 2;
 }
</code>```

Where p is between 0 and 1.

In this case, you're asking jQuery to change top from 0 to -100 in 150ms. Usually the animation interval is around 13ms, but let's say it's exactly 15ms so we have 10 animation steps. Due to the swing easing, the first step amounts for:

```<code> 100 * (0.5 -  Math.cos( (0.1 * Math.PI ) / 2) = 2.45
</code>```

In other words, due to transition: all 0.15s and leaving the race condition apart, clicking the button would scale it horizontally to 0 and move it 2.45px upwards in 0.15s.

If, instead, you only transition the transform property, and leave the top transition to jQuery, you could see both of them happening in parallel.

In the following snippet I slowed things down to take 1s, added console statements on each step and included the regular button, another one that only transitions transform and a third one that transitions transform and top which doesn't use jQuery animations.

// find elements
var button = $("button.animate");

// handle click
button.on("click", function() {
  console.clear();

  $(this).css(
    "transform", (index, value) => {
      console.log(`top: transform was ${value}`);
      return "scaleX(0)";
    }
  );

  console.log('before $.fn.animate');
  $(this).animate({
    "top": "-100px"
  }, 1000, 'swing', () => {
    console.log('finish animation');
    window.setTimeout(() => {
      console.log('restore initial state')
      $(this).css({
        transform: "unset",
        top: 0
      });
    }, 2000);
  });

});

// handle click
$("button.no_animate").on("click", function() {
  console.clear();

  $(this).css({
    "transform": "scaleX(0)",
    "top": "-100px"
  });

  window.setTimeout(() => {
    console.log('restore everything');
    $(this).css({
      transform: "unset",
      top: 0
    });
  }, 2000);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

p {
  color: white;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  position: relative;
}

button.animate.all {
  transition: all 1s;
}

button.animate.transform {
  transition: transform 1s;
}

button.no_animate {
  top: 0;
  transition: top 1s, transform 1s;
}</code>```

Hello World

  <button class="animate all">I Transition all</button>
  <button class="animate transform">I Transition "transform" </button>
  <button class="no_animate transform">I don't use animate </button>

```

Body:
I have a button that I wish to move when it is clicked, and while moving it should also flip. So there are two animations that take place at the same time, and have the same duration. I also have a CSS transition set up for all the properties of the button. It seems to me that only the CSS scale transform works when I use both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works well.

// find elements
var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

 // the bug: the following animation is not visible
  button.animate({
    "top": "-100px" // I tried without "px" too
  }, 0.15 * 1000);
});

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: relative;
  transition: all 0.15s;
}

Hello World

  <button>Click me</button>

The JSFiddle is here.

Thank you.

Body:
When you declare your button style as transition: all 0.15s; that is affecting the top property too. Therefore, in your flow:

The top animation does happen a few ms after the css manipulation

Every step of the top animation is subject to a transition

Due to the first, there's already a racing condition that may cause the top animation to go unnnoticed, but due to the second, there's also an easing over every step of jQuery's animation.

If not provided, $.fn.animate easing function defaults to swing which is defined as:

 function( p ) {
    return 0.5 - Math.cos( p * Math.PI ) / 2;
 }

Where p is between 0 and 1.

In this case, you're asking jQuery to change top from 0 to -100 in 150ms. Usually the animation interval is around 13ms, but let's say it's exactly 15ms so we have 10 animation steps. Due to the swing easing, the first step amounts for:

 100 * (0.5 -  Math.cos( (0.1 * Math.PI ) / 2) = 2.45

In other words, due to transition: all 0.15s and leaving the race condition apart, clicking the button would scale it horizontally to 0 and move it 2.45px upwards in 0.15s.

If, instead, you only transition the transform property, and leave the top transition to jQuery, you could see both of them happening in parallel.

In the following snippet I slowed things down to take 1s, added console statements on each step and included the regular button, another one that only transitions transform and a third one that transitions transform and top which doesn't use jQuery animations.

// find elements
var button = $("button.animate");

// handle click
button.on("click", function() {
  console.clear();

  $(this).css(
    "transform", (index, value) => {
      console.log(`top: transform was ${value}`);
      return "scaleX(0)";
    }
  );

  console.log('before $.fn.animate');
  $(this).animate({
    "top": "-100px"
  }, 1000, 'swing', () => {
    console.log('finish animation');
    window.setTimeout(() => {
      console.log('restore initial state')
      $(this).css({
        transform: "unset",
        top: 0
      });
    }, 2000);
  });

});

// handle click
$("button.no_animate").on("click", function() {
  console.clear();

  $(this).css({
    "transform": "scaleX(0)",
    "top": "-100px"
  });

  window.setTimeout(() => {
    console.log('restore everything');
    $(this).css({
      transform: "unset",
      top: 0
    });
  }, 2000);

});

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

p {
  color: white;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  position: relative;
}

button.animate.all {
  transition: all 1s;
}

button.animate.transform {
  transition: transform 1s;
}

button.no_animate {
  top: 0;
  transition: top 1s, transform 1s;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p id="check">Hello World</p>
  <button class="animate all">I Transition all</button>
  <button class="animate transform">I Transition "transform" </button>
  <button class="no_animate transform">I don't use animate </button>
</div>


问:
Modifying var type of data set in Spark using its own method
The following is a minimal example of the problem I am facing. I have an array that I want to modify in-place as it has about a million elements. the following code works except for the very last statement.

```<code> import spark.implicits._

 case class Frame(x: Double, var y: Array[Double]) {
    def total(): Double = {
        return y.sum
    }
    def modifier(): Unit = {
        for (i <- 0 until y.length) {
            y(i) += 10
        }
        return
    }
 }

 val df = Seq(
               (1.0, Array(0, 2, 1)),
               (8.0, Array(1, 2, 3)),
               (9.0, Array(11, 21, 23))
             ).toDF("x", "y")

 val ds = df.as[Frame]
 ds.show

 ds.map(_.total()).show     // works
 ds.map(_.modifier()).show  // does not work
</code>```

The error is as follows:

```<code>scala> ds.map(_.modifier()).show
<console>:50: error: Unable to find encoder for type Unit. An implicit Encoder[Unit] is needed to store Unit instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
       ds.map(_.modifier()).show
</code>```

I cannot see the origin of the problem. I would be grateful for any help in fixing the bug.

答:
Actually, this has nothing to do with 'var' or 'val', its about mutable data structures. The problem is that modifier returns Unit (e.g. nothing), so you cannot map on this results. You can run it using :

```<code>case class Frame(x: Double, var y: Array[Double]) {
def total(): Double = {
  return y.sum
}
def modifier(): Frame = {
  for (i <- 0 until y.length) {
    y(i) += 10
  }
  return this
}
</code>```

}

But I does not make much sense in my opinion, you should avoid mutable state. In addition, I would keep case classes simple (i.e. without logic) in spark, use them as data containers only. If you must increase every element by then, you can do it also like this:

```<code>case class Frame(x: Double, val y: Array[Double])

ds.map(fr => fr.copy(y = fr.y.map(_+10.0))).show
</code>```

Body:
The following is a minimal example of the problem I am facing. I have an array that I want to modify in-place as it has about a million elements. the following code works except for the very last statement.

 import spark.implicits._

 case class Frame(x: Double, var y: Array[Double]) {
    def total(): Double = {
        return y.sum
    }
    def modifier(): Unit = {
        for (i <- 0 until y.length) {
            y(i) += 10
        }
        return
    }
 }

 val df = Seq(
               (1.0, Array(0, 2, 1)),
               (8.0, Array(1, 2, 3)),
               (9.0, Array(11, 21, 23))
             ).toDF("x", "y")

 val ds = df.as[Frame]
 ds.show

 ds.map(_.total()).show     // works
 ds.map(_.modifier()).show  // does not work

The error is as follows:

scala> ds.map(_.modifier()).show
<console>:50: error: Unable to find encoder for type Unit. An implicit Encoder[Unit] is needed to store Unit instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
       ds.map(_.modifier()).show

I cannot see the origin of the problem. I would be grateful for any help in fixing the bug.

Body:
Actually, this has nothing to do with 'var' or 'val', its about mutable data structures. The problem is that modifier returns Unit (e.g. nothing), so you cannot map on this results. You can run it using :

case class Frame(x: Double, var y: Array[Double]) {
def total(): Double = {
  return y.sum
}
def modifier(): Frame = {
  for (i <- 0 until y.length) {
    y(i) += 10
  }
  return this
}

}

But I does not make much sense in my opinion, you should avoid mutable state. In addition, I would keep case classes simple (i.e. without logic) in spark, use them as data containers only. If you must increase every element by then, you can do it also like this:

case class Frame(x: Double, val y: Array[Double])

ds.map(fr => fr.copy(y = fr.y.map(_+10.0))).show


问:
Updating array with React hooks
I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?</p>

```<code>const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}
</code>```

答:
Try this one</p>

```<code>  const updatedTrick = () => {
    modifyTrick(oldTrick => {
      let newTrick = [...oldTrick];
      newTrick[0] = 1;
      return newTrick;
    })
  }
</code>```

Title: Updating array with React hooks

Body:
I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}

Body:
Try this one

  const updatedTrick = () => {
    modifyTrick(oldTrick => {
      let newTrick = [...oldTrick];
      newTrick[0] = 1;
      return newTrick;
    })
  }


问:
How to find/remove unused dependencies in Gradle
I wanted to find unused dependencies in my project. Is there a feature for this in Gradle, like in Maven?</p>

答:
I just learned about this one: https://plugins.gradle.org/plugin/com.autonomousapps.dependency-analysis

Github

From the looks it is under active development, but I haven't tested it yet.

Edit:
Actually it is pretty awesome, it provides lots of advises (e.g. whether to use api vs implementation)


问:
memory leak - application exited with signal 9 in iphone application
I have an application which is utilizing a lot of memory by using UIImageView, creating graphics context, calling web service, drawing using quartz2d, blending images, playing video, recording and so on. But now the application is exiting after some time with a memory warning.
Is there any way to clear the ram usage like clear cache or something like that.</p>

答:
First of all delete build folder from your directory,then clean all targets,then go to menu Build
then Build and Analyze and solve the potential leaks.

After doing this you should run your application through instruments and see where memory leak occures
and then try to solve it.


问:
Spring IoC: identifier per request
I've created this bean in order to get a Supplier<String>:

```<code>@Bean
public Supplier<String> auditIdSupplier() {
    return () -> String.join(
        "-",
        "KEY",
        UUID.randomUUID().toString()
    );
}
</code>```

As you can see, it's intented to only generate an straightforward identifier string.

Each time, it's called, a new identifier is supplied.

I'd like to change this behavior, in order to get the same generated identifier inside request scope. I mean, first time a request is reached, a new indentifier is generated. From then on, next calls no this Supplier has to return the first generated indentifier inside request scope.

Any ideas?

答:
As it was written in commentary, maybe something like below will work:</p>

```<code>@Bean
@RequestScope
public Supplier<String> auditIdSupplier() {
    String val = String.join("-","KEY",UUID.randomUUID().toString());
    return () -> val;
}
</code>```

Title: Spring IoC: identifier per request

Body:
I've created this bean in order to get a Supplier<String>:

@Bean
public Supplier<String> auditIdSupplier() {
    return () -> String.join(
        "-",
        "KEY",
        UUID.randomUUID().toString()
    );
}

As you can see, it's intented to only generate an straightforward identifier string.

Each time, it's called, a new identifier is supplied.

I'd like to change this behavior, in order to get the same generated identifier inside request scope. I mean, first time a request is reached, a new indentifier is generated. From then on, next calls no this Supplier has to return the first generated indentifier inside request scope.

Any ideas?

Body:
As it was written in commentary, maybe something like below will work:

@Bean
@RequestScope
public Supplier<String> auditIdSupplier() {
    String val = String.join("-","KEY",UUID.randomUUID().toString());
    return () -> val;
}


问:
Celery autodiscover_tasks not working for all Django 1.7 apps
I have a Django 1.7 project with Celery 3.1. All the apps in my Django project work with the new AppConfig. The problem is that not all the tasks are found with autodiscover_tasks:

```<code>app.autodiscover_tasks(settings.INSTALLED_APPS)
</code>```

If i use autodiscover_tasks like this it wil work:

```<code>app.autodiscover_tasks(settings.INSTALLED_APPS + ('apps.core','apps.sales'))
</code>```

The tasks defined in websites are found but the tasks in core and sales are not. All have the same layout with apps.py and tasks.py.

The project folder structure is:

```<code>apps
  core
  apps.py
  tasks.py
dashboard
  apps.py
sales
  apps.py
  tasks.py
websites
  apps.py
  tasks.py
</code>```

The class definitions are as follows:

```<code>class WebsitesConfig(AppConfig):
    name = 'apps.websites'
    verbose_name = 'Websites'

class SalesConfig(AppConfig):
    name = 'apps.sales'
    verbose_name = 'Sales'
</code>```

答:
My problem was the wrong path to the celery.py in the celery command.
the command should be something  like this:

celery worker -A <project_name.celery_app_module> -l info
```

<p>where celery <code>celery_app_module</code> is like this:</p>

```from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# Set default Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<project_name>.settings')

app = Celery('<project_name>', include=['<app_name>.tasks'])
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

```

Body:
I have a Django 1.7 project with Celery 3.1. All the apps in my Django project work with the new AppConfig. The problem is that not all the tasks are found with autodiscover_tasks:

app.autodiscover_tasks(settings.INSTALLED_APPS)

If i use autodiscover_tasks like this it wil work:

app.autodiscover_tasks(settings.INSTALLED_APPS + ('apps.core','apps.sales'))

The tasks defined in websites are found but the tasks in core and sales are not. All have the same layout with apps.py and tasks.py.

The project folder structure is:

apps
  core
  apps.py
  tasks.py
dashboard
  apps.py
sales
  apps.py
  tasks.py
websites
  apps.py
  tasks.py

The class definitions are as follows:

class WebsitesConfig(AppConfig):
    name = 'apps.websites'
    verbose_name = 'Websites'

class SalesConfig(AppConfig):
    name = 'apps.sales'
    verbose_name = 'Sales'

Body:
My problem was the wrong path to the celery.py in the celery command.
the command should be something  like this:

celery worker -A <project_name.celery_app_module> -l info

where celery celery_app_module is like this:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# Set default Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<project_name>.settings')

app = Celery('<project_name>', include=['<app_name>.tasks'])
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


问:
Moving Icon Towards Right in Drawer Navigator Toolbar
I am editing Material UI's drawer navigator example code. I added a notification icon and a checkout icon with the Admin Panel typography within the toolbar.

The checkout icon is towards the right end but for some reason the notification icon is just stuck in the middle. How could I fix this?

Drawer.tsx:

```<code>const drawerWidth = 240;

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      display: 'flex',
    },
    appBar: {
      width: `calc(100% - ${drawerWidth}px)`,
      marginLeft: drawerWidth,
    },
    drawer: {
      width: drawerWidth,
      flexShrink: 0,
    },
    drawerPaper: {
      width: drawerWidth,
    },

    panelheaderRight:{
        marginRight: 0,
        right: 0,
    },
    toolbar: theme.mixins.toolbar,
    content: {
      flexGrow: 1,
      backgroundColor: theme.palette.background.default,
      padding: theme.spacing(3),
    },
  }),
);

export default function PermanentDrawerLeft() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <CssBaseline />
      <AppBar position="fixed" className={classes.appBar}>
        <Toolbar className="toolbar-class">
          <Typography variant="h6" noWrap>
            Admin Panel
          </Typography>
          <NotificationsIcon className='panelheaderRight'/>
          <ExitToAppIcon className='panelheaderRight'/>
        </Toolbar>
      </AppBar>
      <Drawer
        className={classes.drawer}
        variant="permanent"
        classes={{
          paper: classes.drawerPaper,
        }}
        anchor="left"
      >
        <div className='toolbar'/>
        <Divider />
        <List>
        {[{ text: 'Home', url: '/panel', icon: <HomeIcon/>}].map((item, index) => (
            <Link to={item.url} style={{ textDecoration: 'none' }}>
            <ListItem button key={item.text}>
              <ListItemIcon>{item.icon}</ListItemIcon>
              <ListItemText primary={item.text} />
            </ListItem>
            </Link>
          ))}
        </List>
        <Divider />
      </Drawer>
    </div>
  );
}
</code>```

I have also added this css code separately but it doesn't work.
Drawer.css:

```<code>.panelheaderRight{
    margin-right: 0;
    float: right;
    right: 0;
}
.toolbar-class{
    display:flex;
    justify-content:space-between;
    width: 100%;
    }
</code>```

答:
That happens because you need an extra wrapper; watch this:

.toolbar-class {
  display: flex;
  align-items:center;
  justify-content: space-between;
  background-color: #ddd;
  padding: 0 1rem;
}

.toolbar-after {
  display: flex;
  align-items: center;
}

.item:not(:last-child) {
  margin-right: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toolbar-class">
  <div>Admin panel</div>
  <div class="toolbar-after">
    <p class="item">bell</p>
    <p class="item">exit</p>
  </div>
</div></code>```

If you don't want an extra wrapper you could use css grid

.toolbar-class {
  display: grid;
  grid-template-columns: 1fr auto auto;
  align-items:center;
  background-color: #ddd;
  padding: 0 1rem;
}

.item:not(:last-child) {
  margin-right: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toolbar-class">
  <div>Admin panel</div>
    <p class="item">bell</p>
    <p class="item">exit</p>
</div></code>```

Body:
I am editing Material UI's drawer navigator example code. I added a notification icon and a checkout icon with the Admin Panel typography within the toolbar.

The checkout icon is towards the right end but for some reason the notification icon is just stuck in the middle. How could I fix this?

Drawer.tsx:

const drawerWidth = 240;

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      display: 'flex',
    },
    appBar: {
      width: `calc(100% - ${drawerWidth}px)`,
      marginLeft: drawerWidth,
    },
    drawer: {
      width: drawerWidth,
      flexShrink: 0,
    },
    drawerPaper: {
      width: drawerWidth,
    },

    panelheaderRight:{
        marginRight: 0,
        right: 0,
    },
    toolbar: theme.mixins.toolbar,
    content: {
      flexGrow: 1,
      backgroundColor: theme.palette.background.default,
      padding: theme.spacing(3),
    },
  }),
);

export default function PermanentDrawerLeft() {
  const classes = useStyles();

  return (

      <CssBaseline />
      <AppBar position="fixed" className={classes.appBar}>
        <Toolbar className="toolbar-class">
          <Typography variant="h6" noWrap>
            Admin Panel
          </Typography>
          <NotificationsIcon className='panelheaderRight'/>
          <ExitToAppIcon className='panelheaderRight'/>
        </Toolbar>
      </AppBar>
      <Drawer
        className={classes.drawer}
        variant="permanent"
        classes={{
          paper: classes.drawerPaper,
        }}
        anchor="left"
      >

        <Divider />
        <List>
        {[{ text: 'Home', url: '/panel', icon: <HomeIcon/>}].map((item, index) => (
            <Link to={item.url} style={{ textDecoration: 'none' }}>
            <ListItem button key={item.text}>
              <ListItemIcon>{item.icon}</ListItemIcon>
              <ListItemText primary={item.text} />
            </ListItem>
            </Link>
          ))}
        </List>
        <Divider />
      </Drawer>

  );
}

I have also added this css code separately but it doesn't work.
Drawer.css:

.panelheaderRight{
    margin-right: 0;
    float: right;
    right: 0;
}
.toolbar-class{
    display:flex;
    justify-content:space-between;
    width: 100%;
    }

Body:
That happens because you need an extra wrapper; watch this:

.toolbar-class {
  display: flex;
  align-items:center;
  justify-content: space-between;
  background-color: #ddd;
  padding: 0 1rem;
}

.toolbar-after {
  display: flex;
  align-items: center;
}

.item:not(:last-child) {
  margin-right: 15px;
}

<div class="toolbar-class">
  <div>Admin panel</div>
  <div class="toolbar-after">
    <p class="item">bell</p>
    <p class="item">exit</p>
  </div>
</div>

If you don't want an extra wrapper you could use css grid

.toolbar-class {
  display: grid;
  grid-template-columns: 1fr auto auto;
  align-items:center;
  background-color: #ddd;
  padding: 0 1rem;
}

.item:not(:last-child) {
  margin-right: 15px;
}

<div class="toolbar-class">
  <div>Admin panel</div>
    <p class="item">bell</p>
    <p class="item">exit</p>
</div>


答:
You need to configure a request scoped bean

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

    @Bean
    @RequestScope
    public String myRequestScopedIdentifyer(NativeWebRequest httpRequest) {
        // You don't need request as parameter here, but you can inject it this way if you need request context

        return String.join(
          "-",
          "KEY",
          UUID.randomUUID().toString());
    }
</code>```

And then inject it where appropriate with either field injection

```<code>@Component
public class MyClass {

    @Autowired
    @Qualifier("myRequestScopedIdentifyer")
    private String identifier
</code>```

or object factory

```<code>@Component
public class MyClass {

    public MyClass(@Qualifier("myRequestScopedIdentifyer") ObjectFactory<String> identifyerProvider) {
        this.identifyerProvider= identifyerProvider;
    }

    private final ObjectFactory<String> identifyerProvider;

    public void someMethod() {
        String requestScopedId = identifyerProvider.getObject();
    }
</code>```

Title: Spring IoC: identifier per request

Body:
You need to configure a request scoped bean

@Configuration
public class MyConfig {

    @Bean
    @RequestScope
    public String myRequestScopedIdentifyer(NativeWebRequest httpRequest) {
        // You don't need request as parameter here, but you can inject it this way if you need request context

        return String.join(
          "-",
          "KEY",
          UUID.randomUUID().toString());
    }

And then inject it where appropriate with either field injection

@Component
public class MyClass {

    @Autowired
    @Qualifier("myRequestScopedIdentifyer")
    private String identifier

or object factory

@Component
public class MyClass {

    public MyClass(@Qualifier("myRequestScopedIdentifyer") ObjectFactory<String> identifyerProvider) {
        this.identifyerProvider= identifyerProvider;
    }

    private final ObjectFactory<String> identifyerProvider;

    public void someMethod() {
        String requestScopedId = identifyerProvider.getObject();
    }


问:
Typescript classes: Is explicit 'public' modifier a best-practice?
In TS, the default access level for a class member is public unless anything else is specified. Even so, is it considered a best-practice to use the public modifier anyway? If nothing else to make the code more obvious?

答:
As other answers have stated, this is a matter of preference (I prefer the leaner version).

If you use parameter properties though, the explicit public access modifier is compulsory in order to create and initialize an instance member from the given parameter.

```<code>class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(public name: string, ink: boolean) { }
}

const o = new Octopus("Lui", true)
o.name // works
o.ink // error
</code>```

Body:
As other answers have stated, this is a matter of preference (I prefer the leaner version).

If you use parameter properties though, the explicit public access modifier is compulsory in order to create and initialize an instance member from the given parameter.

class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(public name: string, ink: boolean) { }
}

const o = new Octopus("Lui", true)
o.name // works
o.ink // error


问:
How to convert string to bool and evaluate the condition?
I have to convert a string to bool and evaluate the string condition.
For example:

```<code>string condition = "8 > 9 || !8";
</code>```

then the condition has to evaluate and return true;

if string condition = "!8"; then condition has to return true.

Suggest me how to evaluate the condition.

答:
Generally, if you want to evaluate C# code during runtime, you can use
the .NET Compiler Platform (Roslyn) via the Microsoft.CodeAnalysis.CSharp.Scripting
Nuget package.

BTW, I found this right here in stack overflow: How can I evaluate a C# expression dynamically?

here's a solution to your specific requirement, assuming the only exception to valid C# expressions is treating !8 as boolean true (specifically "!8" preceded or followed followed by any other character is forbidden).

```<code>private async Task<bool> ProcessExpression(string expression)
    {
        var processedExpression = expression.Replace("!8", "true");
        return await CSharpScript.EvaluateAsync<bool>(processedExpression);
    }
</code>```

And here's some test code for the above:

```<code>Task.Run(async () =>
        {
            var expresion = "8 > 9";
            var result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 < 9";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "!8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 > 9 || !8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 > 9 && !8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");
        });
</code>```

The output we get is:

8 > 9 : False
8 < 9 : True
!8 : True
8 > 9 || !8 : True
8 > 9 && !8 : False

please note that this solution has a performance penalty and if this is a concert than you should look for other options such as writing a dedicated parser or look for 3rd party Nuget packages.

Body:
I have to convert a string to bool and evaluate the string condition.
For example:

string condition = "8 > 9 || !8";

then the condition has to evaluate and return true;

if string condition = "!8"; then condition has to return true.

Suggest me how to evaluate the condition.

Body:
Generally, if you want to evaluate C# code during runtime, you can use
the .NET Compiler Platform (Roslyn) via the Microsoft.CodeAnalysis.CSharp.Scripting
Nuget package.

BTW, I found this right here in stack overflow: How can I evaluate a C# expression dynamically?

here's a solution to your specific requirement, assuming the only exception to valid C# expressions is treating !8 as boolean true (specifically "!8" preceded or followed followed by any other character is forbidden).

private async Task<bool> ProcessExpression(string expression)
    {
        var processedExpression = expression.Replace("!8", "true");
        return await CSharpScript.EvaluateAsync<bool>(processedExpression);
    }

And here's some test code for the above:

Task.Run(async () =>
        {
            var expresion = "8 > 9";
            var result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 < 9";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "!8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 > 9 || !8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 > 9 && !8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");
        });

The output we get is:

8 > 9 : False
8 < 9 : True
!8 : True
8 > 9 || !8 : True
8 > 9 && !8 : False

please note that this solution has a performance penalty and if this is a concert than you should look for other options such as writing a dedicated parser or look for 3rd party Nuget packages.


问:
Reverse value from one view to another by using protocol in Swift
Now I'm learing the swift programming and I'm stuck on the protocol grammar.

There's a simple function I want to implement: There are two ViewControllers I've created in one Main.Storyboard, The first ViewController has a label and a button to go to the second ViewController. The second one has a textField and a button to go back to the first ViewController.

I entered some words in the textField and click go-back button to dismiss the view, but I can't see the label changed on the first view.

Here's what I've coded for the delegate view:

```<code>import UIKit

protocol SecondViewDelegate {
    func getText(text: String)
}

class SecondViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    var text: String?
    var delegate: SecondViewDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    @IBAction func backButton(_ sender: UIButton) {
//        print(text!)
        delegate?.getText(text: text!)
        dismiss(animated: true, completion: nil)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
//        print("textFieldDidEndEditing has been called")
        text = textField.text
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        return true
    }
}
</code>```

I've print the text when I pressed the backButton and I'm sure the text printed on console is which what I entered in the textField.

And here's the code for another view which showed the text:

```<code>class ViewController: UIViewController, SecondViewDelegate {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondVC = SecondViewController()
        secondVC.delegate = self
    }

    @IBAction func clickButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToSecond", sender: self)
    }

    func getText(text: String) {
        self.textLabel.text = text
    }

}
</code>```

When I returned to the view, the label didn't change. And I added a breakpoint in the function getText and run the app, the app didn't crash.

I don't know which part I've done wrong. Can anyone point out the problem to help me? Thanks!

答:
Please add this method to your code for pass delegate.

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToSecond" {
        if let vc = segue.destination as? SecondViewController {
            vc.delegate = self
        }
    }
}
</code>```

And remove this lines of code.

```<code>let secondVC = SecondViewController()
secondVC.delegate = self
</code>```

Body:
Now I'm learing the swift programming and I'm stuck on the protocol grammar.

There's a simple function I want to implement: There are two ViewControllers I've created in one Main.Storyboard, The first ViewController has a label and a button to go to the second ViewController. The second one has a textField and a button to go back to the first ViewController.

I entered some words in the textField and click go-back button to dismiss the view, but I can't see the label changed on the first view.

Here's what I've coded for the delegate view:

import UIKit

protocol SecondViewDelegate {
    func getText(text: String)
}

class SecondViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    var text: String?
    var delegate: SecondViewDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    @IBAction func backButton(_ sender: UIButton) {
//        print(text!)
        delegate?.getText(text: text!)
        dismiss(animated: true, completion: nil)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
//        print("textFieldDidEndEditing has been called")
        text = textField.text
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        return true
    }
}

I've print the text when I pressed the backButton and I'm sure the text printed on console is which what I entered in the textField.

And here's the code for another view which showed the text:

class ViewController: UIViewController, SecondViewDelegate {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondVC = SecondViewController()
        secondVC.delegate = self
    }

    @IBAction func clickButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToSecond", sender: self)
    }

    func getText(text: String) {
        self.textLabel.text = text
    }

}

When I returned to the view, the label didn't change. And I added a breakpoint in the function getText and run the app, the app didn't crash.

I don't know which part I've done wrong. Can anyone point out the problem to help me? Thanks!

Body:
Please add this method to your code for pass delegate.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToSecond" {
        if let vc = segue.destination as? SecondViewController {
            vc.delegate = self
        }
    }
}

And remove this lines of code.

let secondVC = SecondViewController()
secondVC.delegate = self


答:
This is my version:</p>

```<code>@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class AuditIdPerRequest {
   private String key;

   @PostConstruct
   public void calculateKey() {
      this.key = String.join(
        "-",
        "KEY",
        UUID.randomUUID().toString()
    );
   }

   public String getAuditId() {
      return this.key;
   }
}

</code>```

Title: Spring IoC: identifier per request

Body:
This is my version:

@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class AuditIdPerRequest {
   private String key;

   @PostConstruct
   public void calculateKey() {
      this.key = String.join(
        "-",
        "KEY",
        UUID.randomUUID().toString()
    );
   }

   public String getAuditId() {
      return this.key;
   }
}


问:
Make a bash script available without using ssh
I have a simple bash script (myscript.sh).

```<code>mysqldump -u busql mydb mytable1 mytable2 mytable3 | mysql -u busql mydb2 && rsync --progress --stats -av --chown=mydomain.de:psacln /var/www/vhosts/mydomain.com/httpdocs/pictures/master/product/1/* /var/www/vhosts/mydomain.de/httpdocs/pictures/master/product/1/
</code>```

So basically the script dumps 3 tables from db1 and insert them into db2, copy all pictures from mydomain.com to mydomain.de and change the user for all copied pictures from mydomain.com to mydomain.de.

Now I want to make this script (one-click) available for my colleagues without giving them ssh access to our server.

First thing I was thinking of, was to make this script through html/php available. But the problem here is that the script needs to be run as root in order to change the user/owner for the copied files. I would like run the script from/with mydomain.com user but open minded. And it seems like there is no safe solution to run this script from a php page as root.

Could I maybie give mydomain.com user the rights to change file-owners or what would you suggest to make this script available without ssh access?!

There are also other scripts with other file-owners coming in the future, that need to be easy available for my colleagues. So I thinking what could be here the best solution ...

答:
chown is really a root only operation.  The usual way to change ownership is to allow the target user (mydomain.de) read access to the files and then copy the files as that user.  This doesn't require any root access to execute.

You can give access for one specific user to run one specific script as another named user using sudo by editing /etc/sudoers.

For example, for two users "bob" and "frank", bob can run "/home/bob/special_script.sh" as frank as long as frank has access to the script and this line is added to /etc/sudoers:

```<code>bob ALL=(frank) NOPASSWD: /home/bob/special_script.sh
</code>```

bob would run:

```<code>sudo -u frank /home/bob/special_script.sh
</code>```

I recommend that instead of rsync with --chown you create a script containing the rsync command and give sudo access to run it as mydomain.de, giving mydomain.de access to read  /var/www/vhosts/mydomain.com/httpdocs/pictures/master/product/1/

Body:
I have a simple bash script (myscript.sh).

mysqldump -u busql mydb mytable1 mytable2 mytable3 | mysql -u busql mydb2 && rsync --progress --stats -av --chown=mydomain.de:psacln /var/www/vhosts/mydomain.com/httpdocs/pictures/master/product/1/* /var/www/vhosts/mydomain.de/httpdocs/pictures/master/product/1/

So basically the script dumps 3 tables from db1 and insert them into db2, copy all pictures from mydomain.com to mydomain.de and change the user for all copied pictures from mydomain.com to mydomain.de.

Now I want to make this script (one-click) available for my colleagues without giving them ssh access to our server.

First thing I was thinking of, was to make this script through html/php available. But the problem here is that the script needs to be run as root in order to change the user/owner for the copied files. I would like run the script from/with mydomain.com user but open minded. And it seems like there is no safe solution to run this script from a php page as root.

Could I maybie give mydomain.com user the rights to change file-owners or what would you suggest to make this script available without ssh access?!

There are also other scripts with other file-owners coming in the future, that need to be easy available for my colleagues. So I thinking what could be here the best solution ...

Body:
chown is really a root only operation.  The usual way to change ownership is to allow the target user (mydomain.de) read access to the files and then copy the files as that user.  This doesn't require any root access to execute.

You can give access for one specific user to run one specific script as another named user using sudo by editing /etc/sudoers.

For example, for two users "bob" and "frank", bob can run "/home/bob/special_script.sh" as frank as long as frank has access to the script and this line is added to /etc/sudoers:

bob ALL=(frank) NOPASSWD: /home/bob/special_script.sh

bob would run:

sudo -u frank /home/bob/special_script.sh

I recommend that instead of rsync with --chown you create a script containing the rsync command and give sudo access to run it as mydomain.de, giving mydomain.de access to read  /var/www/vhosts/mydomain.com/httpdocs/pictures/master/product/1/


问:
Group Rows to in Oracle SQL to achieve unique ID
I have the following rows in a SQL Table

```<code>Col1    Col2  Col3  Col4
CABA    B08    3    0000000000017
BA      A06    4    0000000000018
CABA    B08    3    0000000000018
CABA    B06  1.5    0000000000019
BA      A07    5    0000000000021
CABA    B04   0.5   0000000000021
</code>```

As a result, I would like to group common Col4 and create IDs ColD like the following

```<code>Col1    Col2  Col3  Col4            Col5
CABA    B08    3    0000000000017   ARB08
BA      A06    4    0000000000018   ARA06B08
CABA    B08    3    0000000000018   ARA06B08
CABA    B06  1.5    0000000000019   ARB06
BA      A07    5    0000000000021   ARA07B04
CABA    B04   0.5   0000000000021   ARA07B04
</code>```

Is there a way we can achieve this using Oracle SQL

答:
You can use listagg() as a window function:

```<code>select
    t.*,
    'AR' || listagg(col2, '')
        within group(order by col2)
        over(partition by col4) col5
from mytable t
</code>```

Demo on DB Fiddle:

```
COL1 | COL2 | COL3 | COL4 | COL5
:--- | :--- | ---: | ---: | :-------
CABA | B08  |    3 |   17 | ARB08
BA   | A06  |    4 |   18 | ARA06B08
CABA | B08  |    3 |   18 | ARA06B08
CABA | B06  |  1.5 |   19 | ARB06
BA   | A07  |    5 |   21 | ARA07B04
CABA | B04  |   .5 |   21 | ARA07B04
```

Body:
I have the following rows in a SQL Table

Col1    Col2  Col3  Col4
CABA    B08    3    0000000000017
BA      A06    4    0000000000018
CABA    B08    3    0000000000018
CABA    B06  1.5    0000000000019
BA      A07    5    0000000000021
CABA    B04   0.5   0000000000021

As a result, I would like to group common Col4 and create IDs ColD like the following

Col1    Col2  Col3  Col4            Col5
CABA    B08    3    0000000000017   ARB08
BA      A06    4    0000000000018   ARA06B08
CABA    B08    3    0000000000018   ARA06B08
CABA    B06  1.5    0000000000019   ARB06
BA      A07    5    0000000000021   ARA07B04
CABA    B04   0.5   0000000000021   ARA07B04

Is there a way we can achieve this using Oracle SQL

Body:
You can use listagg() as a window function:

select
    t.*,
    'AR' || listagg(col2, '')
        within group(order by col2)
        over(partition by col4) col5
from mytable t

Demo on DB Fiddle:

COL1 | COL2 | COL3 | COL4 | COL5
:--- | :--- | ---: | ---: | :-------
CABA | B08  |    3 |   17 | ARB08
BA   | A06  |    4 |   18 | ARA06B08
CABA | B08  |    3 |   18 | ARA06B08
CABA | B06  |  1.5 |   19 | ARB06
BA   | A07  |    5 |   21 | ARA07B04
CABA | B04  |   .5 |   21 | ARA07B04


问:
Xcode Exit codes and signals
I've looked around and never found a comprehensive list of exit codes for Xcode especially working with iOS. This question: Debuging to simulator crashes with "exited with status 5" unless I have breakpoint simply says I need to restart xcode to solve a common problem labeled 'exit code 5'. There are many other similar questions out there. The solutions often work, however I don't understand how they work. Next time I come across once of these exit code's I'd like to know what they mean so I can have a better idea of how to prevent it from happening again.

What are the common Xcode signals and exit codes?

答:
signal 0 an 1 are pretty standard, others are defined in context and by users, on osx 10.6:

man signal gives:

```<code> 2     SIGINT       terminate process    interrupt program
 3     SIGQUIT      create core image    quit program
 4     SIGILL       create core image    illegal instruction
 5     SIGTRAP      create core image    trace trap
 6     SIGABRT      create core image    abort program (formerly SIGIOT)
 7     SIGEMT       create core image    emulate instruction executed
 8     SIGFPE       create core image    floating-point exception
 9     SIGKILL      terminate process    kill program
 10    SIGBUS       create core image    bus error
 11    SIGSEGV      create core image    segmentation violation
 12    SIGSYS       create core image    non-existent system call invoked
 13    SIGPIPE      terminate process    write on a pipe with no reader
 14    SIGALRM      terminate process    real-time timer expired
 15    SIGTERM      terminate process    software termination signal
 16    SIGURG       discard signal       urgent condition present on
                                         socket
 17    SIGSTOP      stop process         stop (cannot be caught or
                                         ignored)
 18    SIGTSTP      stop process         stop signal generated from
                                         keyboard
 19    SIGCONT      discard signal       continue after stop
 20    SIGCHLD      discard signal       child status has changed
 21    SIGTTIN      stop process         background read attempted from
                                         control terminal
 22    SIGTTOU      stop process         background write attempted to
                                         control terminal
 23    SIGIO        discard signal       I/O is possible on a descriptor
                                         (see fcntl(2))
 24    SIGXCPU      terminate process    cpu time limit exceeded (see
                                         setrlimit(2))
 25    SIGXFSZ      terminate process    file size limit exceeded (see
                                         setrlimit(2))
 26    SIGVTALRM    terminate process    virtual time alarm (see
                                         setitimer(2))
 27    SIGPROF      terminate process    profiling timer alarm (see
                                         setitimer(2))
 28    SIGWINCH     discard signal       Window size change
 29    SIGINFO      discard signal       status request from keyboard
 30    SIGUSR1      terminate process    User defined signal 1
 31    SIGUSR2      terminate process    User defined signal 2
</code>```

Title: Xcode Exit codes and signals

Body:
signal 0 an 1 are pretty standard, others are defined in context and by users, on osx 10.6:

man signal gives:

 2     SIGINT       terminate process    interrupt program
 3     SIGQUIT      create core image    quit program
 4     SIGILL       create core image    illegal instruction
 5     SIGTRAP      create core image    trace trap
 6     SIGABRT      create core image    abort program (formerly SIGIOT)
 7     SIGEMT       create core image    emulate instruction executed
 8     SIGFPE       create core image    floating-point exception
 9     SIGKILL      terminate process    kill program
 10    SIGBUS       create core image    bus error
 11    SIGSEGV      create core image    segmentation violation
 12    SIGSYS       create core image    non-existent system call invoked
 13    SIGPIPE      terminate process    write on a pipe with no reader
 14    SIGALRM      terminate process    real-time timer expired
 15    SIGTERM      terminate process    software termination signal
 16    SIGURG       discard signal       urgent condition present on
                                         socket
 17    SIGSTOP      stop process         stop (cannot be caught or
                                         ignored)
 18    SIGTSTP      stop process         stop signal generated from
                                         keyboard
 19    SIGCONT      discard signal       continue after stop
 20    SIGCHLD      discard signal       child status has changed
 21    SIGTTIN      stop process         background read attempted from
                                         control terminal
 22    SIGTTOU      stop process         background write attempted to
                                         control terminal
 23    SIGIO        discard signal       I/O is possible on a descriptor
                                         (see fcntl(2))
 24    SIGXCPU      terminate process    cpu time limit exceeded (see
                                         setrlimit(2))
 25    SIGXFSZ      terminate process    file size limit exceeded (see
                                         setrlimit(2))
 26    SIGVTALRM    terminate process    virtual time alarm (see
                                         setitimer(2))
 27    SIGPROF      terminate process    profiling timer alarm (see
                                         setitimer(2))
 28    SIGWINCH     discard signal       Window size change
 29    SIGINFO      discard signal       status request from keyboard
 30    SIGUSR1      terminate process    User defined signal 1
 31    SIGUSR2      terminate process    User defined signal 2


问:
How to Get Child Product Ids from a Configurable product
I am trying to fetch all child product Ids from configurable product Ids.

```<code>$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product');

        $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
        $currentStore = $storeManager->getStore();
        $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $productURL = $mediaUrl.'catalog/product';
        $collection = $this->_productCollectionFactory->create();
        $productCollection = $collection->addAttributeToSelect('*')->addAttributeToFilter('type_id','configurable');
        $vendor_product = array();

        $productData = $product->getData();
        foreach($productCollection as $prodObj){
            $productData = array();
            $product = $product->load($prodObj->getId());

                     $productTypeInstance = $product->getTypeInstance();
            $usedProducts = $productTypeInstance->getUsedProducts($product);

 foreach ($usedProducts  as $child) {
$productData['childrenIds'][] = $child->getId();
}
</code>```

I get Ids of my first configurable product in all the cases

答:
To get child product Ids from a configurable product, you can use below code:

```<code> public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    public function execute()
    {
        $_productId=57786;
        $_product=$this->productRepository->getById($_productId);
        $childIs=$_product->getExtensionAttributes()->getConfigurableProductLinks();

        print_r($childIs);
    }
</code>```

Output looks like:

```<code>Array
(
    [31981] => 31981
    [31982] => 31982
    [31983] => 31983
)
</code>```

Hope it will help you.

Body:
I am trying to fetch all child product Ids from configurable product Ids.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product');

        $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
        $currentStore = $storeManager->getStore();
        $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $productURL = $mediaUrl.'catalog/product';
        $collection = $this->_productCollectionFactory->create();
        $productCollection = $collection->addAttributeToSelect('*')->addAttributeToFilter('type_id','configurable');
        $vendor_product = array();

        $productData = $product->getData();
        foreach($productCollection as $prodObj){
            $productData = array();
            $product = $product->load($prodObj->getId());

                     $productTypeInstance = $product->getTypeInstance();
            $usedProducts = $productTypeInstance->getUsedProducts($product);

 foreach ($usedProducts  as $child) {
$productData['childrenIds'][] = $child->getId();
}

I get Ids of my first configurable product in all the cases

Body:
To get child product Ids from a configurable product, you can use below code:

 public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    public function execute()
    {
        $_productId=57786;
        $_product=$this->productRepository->getById($_productId);
        $childIs=$_product->getExtensionAttributes()->getConfigurableProductLinks();

        print_r($childIs);
    }

Output looks like:

Array
(
    [31981] => 31981
    [31982] => 31982
    [31983] => 31983
)

Hope it will help you.


问:
Devise methods in helper file?
I have a helper module ModelHelper. I want to use user_signed_in? method inside that helper module. But it shows error. How can I call this method inside helper file.</p>

答:
Method user_signed_in? defined in the Devise::Controllers::Helpers::ClassModule module. Long story short it just checks if scope authenticated in warden. So you can try to check it without Devise helpers

def #{mapping}_signed_in?
  !!current_#{mapping}
end

def current_#{mapping}
  @current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
end
```

Title: Devise methods in helper file?


问:
dc.js - Chart not rendering (single row bar chart - horizontal row), with the exception of legend, axes and tick marks/values (which do render)
Scenario

I want to see my dc.js horizontal row stacked bar chart (single row chart), but no chart appears, except for legend with names, axes with tick marks which do appear.

Screenshot

Data set below in code snippet

Question

How do I render the ensure chart rendering successfully using dc.js / d3.js?

Code Snippet

```<code>$scope.avgCycleTime = function(){

    var data = [
                    {"Project":"Expedition","Stage": "Created", "Days":12},
                    {"Project":"Expedition","Stage": "Active", "Days":14},
                    {"Project":"Expedition","Stage": "Closure", "Days":2}
    ];
    var ndx = crossfilter(data);

    data.forEach(function(x) {
      x.Days = 0;
    });

    var ndx = crossfilter(data)

    var xdim = ndx.dimension(function (d) {return d.Days;});

    function root_function(dim,stack_names) {
        return dim.group().reduce(
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function() {
        return {};
      });}

    var stages = ['Created', 'Active', 'Closure'];
    var ygroup = root_function(xdim,stages)

    function sel_stack(i) {
    return function(d) {
      return d.value[i];
    };}

    cycleChart = new dc.barChart("#risk-cycle-chart");

    var chart = document.getElementById('risk-cycle-chart');

    heightStatusChart =  200;
    widthStatusChart = Math.floor(parseFloat(window.getComputedStyle(chart, null).width))
     - 2*parseInt(window.getComputedStyle(chart, null).getPropertyValue('padding-top'));

    cycleChart
      .x(d3.scaleLinear().domain([0,7,14,21,28]))
      .dimension(xdim)
      .group(ygroup, data[0].Project, sel_stack(data[0].Project))
      .xUnits(dc.units.ordinal)
      .margins({left:75, top: 0, right: 0, bottom: 20})
      .width(widthStatusChart)
      .height(heightStatusChart)
      .legend(dc.legend());

    for(var i = 1; i<stages.length; ++i)
      cycleChart.stack(ygroup, stages[i], sel_stack(stages[i]));
</code>```

}

答:
Sigh, I guess dc.js and crossfilter have a steep learning curve. There isn't any "interesting" problem here, just a bunch of minor glitches:

dc.barChart is not a constructor. Use either new dc.BarChart(...) or dc.barChart(...)

You are zeroing out d.Days, which is the field your dimension uses, so there will only be one bin.

Your x scale should match your xUnits, so d3.scaleOrdinal not d3.scaleLinear.

You have changed your data from having separate fields for Created, Active, Closure to one field named Stage. With this format of data, your reducers could look like

```<code>function root_function(dim, stack_field, stack_names) {
  return dim.group().reduce(
    function(p, v) {
      p[v[stack_field]] = p[v[stack_field]] + 1; // 2
      return p;},
    function(p, v) {
      p[v[stack_field]] = p[v[stack_field]] - 1; // 3
      return p;},
    function() {
      return Object.fromEntries(stack_names.map(sn => [sn,0])); // 1
    });}
</code>```

Initialize each bin with a field for each of the stack_names with value 0

When adding a row to a bin, determine which field it affects using stack_field; increment that field

When removing a row from a bin, decrement the same way

You are requesting an x domain of [0,7,14,21,28] but none of your Days fall exactly on those values. If you want to round down, you could do

```<code>var xdim = ndx.dimension(function (d) {return Math.floor(d.Days/7)*7;});
</code>```

.group(ygroup, data[0].Project, sel_stack(data[0].Project)) doesn't make sense since you are stacking by Stage, not by Project; this should be .group(ygroup, stages[0], sel_stack(stages[0]))

With the above changes, we get a chart with one stack in each of the first three bins:

Demo fiddle.

Body:
Scenario

I want to see my dc.js horizontal row stacked bar chart (single row chart), but no chart appears, except for legend with names, axes with tick marks which do appear.

Screenshot

Data set below in code snippet

Question

How do I render the ensure chart rendering successfully using dc.js / d3.js?

Code Snippet

$scope.avgCycleTime = function(){

    var data = [
                    {"Project":"Expedition","Stage": "Created", "Days":12},
                    {"Project":"Expedition","Stage": "Active", "Days":14},
                    {"Project":"Expedition","Stage": "Closure", "Days":2}
    ];
    var ndx = crossfilter(data);

    data.forEach(function(x) {
      x.Days = 0;
    });

    var ndx = crossfilter(data)

    var xdim = ndx.dimension(function (d) {return d.Days;});

    function root_function(dim,stack_names) {
        return dim.group().reduce(
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function() {
        return {};
      });}

    var stages = ['Created', 'Active', 'Closure'];
    var ygroup = root_function(xdim,stages)

    function sel_stack(i) {
    return function(d) {
      return d.value[i];
    };}

    cycleChart = new dc.barChart("#risk-cycle-chart");

    var chart = document.getElementById('risk-cycle-chart');

    heightStatusChart =  200;
    widthStatusChart = Math.floor(parseFloat(window.getComputedStyle(chart, null).width))
     - 2*parseInt(window.getComputedStyle(chart, null).getPropertyValue('padding-top'));

    cycleChart
      .x(d3.scaleLinear().domain([0,7,14,21,28]))
      .dimension(xdim)
      .group(ygroup, data[0].Project, sel_stack(data[0].Project))
      .xUnits(dc.units.ordinal)
      .margins({left:75, top: 0, right: 0, bottom: 20})
      .width(widthStatusChart)
      .height(heightStatusChart)
      .legend(dc.legend());

    for(var i = 1; i<stages.length; ++i)
      cycleChart.stack(ygroup, stages[i], sel_stack(stages[i]));

}

Body:
Sigh, I guess dc.js and crossfilter have a steep learning curve. There isn't any "interesting" problem here, just a bunch of minor glitches:

dc.barChart is not a constructor. Use either new dc.BarChart(...) or dc.barChart(...)

You are zeroing out d.Days, which is the field your dimension uses, so there will only be one bin.

Your x scale should match your xUnits, so d3.scaleOrdinal not d3.scaleLinear.

You have changed your data from having separate fields for Created, Active, Closure to one field named Stage. With this format of data, your reducers could look like

function root_function(dim, stack_field, stack_names) {
  return dim.group().reduce(
    function(p, v) {
      p[v[stack_field]] = p[v[stack_field]] + 1; // 2
      return p;},
    function(p, v) {
      p[v[stack_field]] = p[v[stack_field]] - 1; // 3
      return p;},
    function() {
      return Object.fromEntries(stack_names.map(sn => [sn,0])); // 1
    });}

Initialize each bin with a field for each of the stack_names with value 0

When adding a row to a bin, determine which field it affects using stack_field; increment that field

When removing a row from a bin, decrement the same way

You are requesting an x domain of [0,7,14,21,28] but none of your Days fall exactly on those values. If you want to round down, you could do

var xdim = ndx.dimension(function (d) {return Math.floor(d.Days/7)*7;});

.group(ygroup, data[0].Project, sel_stack(data[0].Project)) doesn't make sense since you are stacking by Stage, not by Project; this should be .group(ygroup, stages[0], sel_stack(stages[0]))

With the above changes, we get a chart with one stack in each of the first three bins:

Demo fiddle.


问:
Detecting audio silence in WAV files using C#
I'm tasked with building a .NET client app to detect silence in a WAV files.

Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this?

答:
Here a nice variant to detect threshold alternatings:

```<code>static class AudioFileReaderExt
{

    private static bool IsSilence(float amplitude, sbyte threshold)
    {
        double dB = 20 * Math.Log10(Math.Abs(amplitude));
        return dB < threshold;
    }

    private static bool IsBeep(float amplitude, sbyte threshold)
    {
        double dB = 20 * Math.Log10(Math.Abs(amplitude));
        return dB > threshold;
    }

    public static double GetBeepDuration(this AudioFileReader reader,
                                              double StartPosition, sbyte silenceThreshold = -40)
    {
        int counter = 0;
        bool eof = false;
        int initial = (int)(StartPosition * reader.WaveFormat.Channels * reader.WaveFormat.SampleRate / 1000);
        if (initial > reader.Length) return -1;
        reader.Position = initial;
        var buffer = new float[reader.WaveFormat.SampleRate * 4];
        while (!eof)
        {
            int samplesRead = reader.Read(buffer, 0, buffer.Length);
            if (samplesRead == 0)
                eof = true;

            for (int n = initial; n < samplesRead; n++)
            {
                if (IsBeep(buffer[n], silenceThreshold))
                {
                    counter++;
                }
                else
                {
                    eof=true; break;
                }
            }
        }

        double silenceSamples = (double)counter / reader.WaveFormat.Channels;
        double silenceDuration = (silenceSamples / reader.WaveFormat.SampleRate) * 1000;

        return TimeSpan.FromMilliseconds(silenceDuration).TotalMilliseconds;
    }

    public static double GetSilenceDuration(this AudioFileReader reader,
                                              double StartPosition, sbyte silenceThreshold = -40)
    {
        int counter = 0;
        bool eof = false;
        int initial = (int)(StartPosition * reader.WaveFormat.Channels * reader.WaveFormat.SampleRate / 1000);
        if (initial > reader.Length) return -1;
        reader.Position = initial;
        var buffer = new float[reader.WaveFormat.SampleRate * 4];
        while (!eof)
        {
            int samplesRead = reader.Read(buffer, 0, buffer.Length);
            if (samplesRead == 0)
                eof=true;

            for (int n = initial; n < samplesRead; n++)
            {
                if (IsSilence(buffer[n], silenceThreshold))
                {
                    counter++;
                }
                else
                {
                    eof=true; break;
                }
            }
        }

        double silenceSamples = (double)counter / reader.WaveFormat.Channels;
        double silenceDuration = (silenceSamples / reader.WaveFormat.SampleRate) * 1000;

        return TimeSpan.FromMilliseconds(silenceDuration).TotalMilliseconds;
    }

}
</code>```

Main usage:

```<code>using (AudioFileReader reader = new AudioFileReader("test.wav"))
        {
            double duratioff = 1;
            double duration = 1;
            double position = 1;
            while (duratioff >-1 && duration >-1)
            {
                duration = reader.GetBeepDuration(position);
                Console.WriteLine(duration);
                position = position + duration;
                duratioff = reader.GetSilenceDuration(position);
                Console.WriteLine(-duratioff);
                position = position + duratioff;
            }
        }
</code>```

OwnerDisplayName: Judah Himango

ContentLicense: CC BY-SA 2.5

Body:
Here a nice variant to detect threshold alternatings:

static class AudioFileReaderExt
{

    private static bool IsSilence(float amplitude, sbyte threshold)
    {
        double dB = 20 * Math.Log10(Math.Abs(amplitude));
        return dB < threshold;
    }

    private static bool IsBeep(float amplitude, sbyte threshold)
    {
        double dB = 20 * Math.Log10(Math.Abs(amplitude));
        return dB > threshold;
    }

    public static double GetBeepDuration(this AudioFileReader reader,
                                              double StartPosition, sbyte silenceThreshold = -40)
    {
        int counter = 0;
        bool eof = false;
        int initial = (int)(StartPosition * reader.WaveFormat.Channels * reader.WaveFormat.SampleRate / 1000);
        if (initial > reader.Length) return -1;
        reader.Position = initial;
        var buffer = new float[reader.WaveFormat.SampleRate * 4];
        while (!eof)
        {
            int samplesRead = reader.Read(buffer, 0, buffer.Length);
            if (samplesRead == 0)
                eof = true;

            for (int n = initial; n < samplesRead; n++)
            {
                if (IsBeep(buffer[n], silenceThreshold))
                {
                    counter++;
                }
                else
                {
                    eof=true; break;
                }
            }
        }

        double silenceSamples = (double)counter / reader.WaveFormat.Channels;
        double silenceDuration = (silenceSamples / reader.WaveFormat.SampleRate) * 1000;

        return TimeSpan.FromMilliseconds(silenceDuration).TotalMilliseconds;
    }

    public static double GetSilenceDuration(this AudioFileReader reader,
                                              double StartPosition, sbyte silenceThreshold = -40)
    {
        int counter = 0;
        bool eof = false;
        int initial = (int)(StartPosition * reader.WaveFormat.Channels * reader.WaveFormat.SampleRate / 1000);
        if (initial > reader.Length) return -1;
        reader.Position = initial;
        var buffer = new float[reader.WaveFormat.SampleRate * 4];
        while (!eof)
        {
            int samplesRead = reader.Read(buffer, 0, buffer.Length);
            if (samplesRead == 0)
                eof=true;

            for (int n = initial; n < samplesRead; n++)
            {
                if (IsSilence(buffer[n], silenceThreshold))
                {
                    counter++;
                }
                else
                {
                    eof=true; break;
                }
            }
        }

        double silenceSamples = (double)counter / reader.WaveFormat.Channels;
        double silenceDuration = (silenceSamples / reader.WaveFormat.SampleRate) * 1000;

        return TimeSpan.FromMilliseconds(silenceDuration).TotalMilliseconds;
    }

}

Main usage:

using (AudioFileReader reader = new AudioFileReader("test.wav"))
        {
            double duratioff = 1;
            double duration = 1;
            double position = 1;
            while (duratioff >-1 && duration >-1)
            {
                duration = reader.GetBeepDuration(position);
                Console.WriteLine(duration);
                position = position + duration;
                duratioff = reader.GetSilenceDuration(position);
                Console.WriteLine(-duratioff);
                position = position + duratioff;
            }
        }


问:
crypto-js wrong des-ecb decoding
I need to decrypt base64 string using base64 key with ECB mode and Iso10126 padding using DES.

In theory it is simple:

const decryptedKeyDes = CryptoJS.DES.decrypt(
      encryptedData, // QAKH7qnKxZTIta...
      ResponseParser.secretKey, // MfKhm... length=32
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Iso10126
      }
    );
```

<p>I get <code>sigBytes:162</code>response and after converting it to base64 (because then I need to ungzip) I get <code>
byteLength:243</code> which is wrong, it should be <code>byteLength:395</code> (I am just compering it with my correct Java code).</p>

<p>I have no idea what is wrong here.</p>

<p>I also tried to do it using node.js's <code>crypto</code> but I also get wrong and different result. I can't find how to set <code>padding</code> in <code>crypto</code> and I can get only <code>utf8</code>, <code>binary</code> or <code>ascii</code></p>

<pre class="lang-js prettyprint-override"><code>function encodeDesECB(textToEncode, keyString) {
      var key = new Buffer(
        "some key with 32 length".substring(0, 8),
        "utf8"
      );
      var cipher = crypto.createDecipheriv("des-ecb", key, null);
      cipher.setAutoPadding(false);
      var c = cipher.update(textToEncode, "base64", "utf8");

      c += cipher.final("utf8");
      return c;
    }
</code>```

The java code is:

import javax.crypto.Cipher
import static javax.crypto.Cipher.DECRYPT_MODE

//CIPHER_ALGORITHM_MODE_PADDING = 'DESede/ECB/ISO10126Padding'

Cipher decryptingCipher = Cipher.getInstance(CIPHER_ALGORITHM_MODE_PADDING)
      decryptingCipher.init(DECRYPT_MODE, secretKeySpec)
      decryptingCipher.doFinal(data)
```

where secretKeySpec is object with algorithm: DESede and key, which is bit[] equal to mine.

I have no idea what is wrong in my code.

Does CryptoJs works wrong, or maybe I forgot about something in my decoding.

Do you have any clues what can be wrong?

答:
Thanks to @Topaco I finally solved it.

The key has to be WordArray: CryptoJS.enc.Base64.parse('some key with 32 length')

The message has to be base64 string: QAKH7qnKxZTIta...;

Then you need to parse the response like this: tripleDesResult.toString(CryptoJS.enc.Base64)

Thanks again!

Title: crypto-js wrong des-ecb decoding

Body:
I need to decrypt base64 string using base64 key with ECB mode and Iso10126 padding using DES.

In theory it is simple:

const decryptedKeyDes = CryptoJS.DES.decrypt(
      encryptedData, // QAKH7qnKxZTIta...
      ResponseParser.secretKey, // MfKhm... length=32
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Iso10126
      }
    );

I get sigBytes:162response and after converting it to base64 (because then I need to ungzip) I get
byteLength:243 which is wrong, it should be byteLength:395 (I am just compering it with my correct Java code).

I have no idea what is wrong here.

I also tried to do it using node.js's crypto but I also get wrong and different result. I can't find how to set padding in crypto and I can get only utf8, binary or ascii

function encodeDesECB(textToEncode, keyString) {
      var key = new Buffer(
        "some key with 32 length".substring(0, 8),
        "utf8"
      );
      var cipher = crypto.createDecipheriv("des-ecb", key, null);
      cipher.setAutoPadding(false);
      var c = cipher.update(textToEncode, "base64", "utf8");

      c += cipher.final("utf8");
      return c;
    }

The java code is:

import javax.crypto.Cipher
import static javax.crypto.Cipher.DECRYPT_MODE

//CIPHER_ALGORITHM_MODE_PADDING = 'DESede/ECB/ISO10126Padding'

Cipher decryptingCipher = Cipher.getInstance(CIPHER_ALGORITHM_MODE_PADDING)
      decryptingCipher.init(DECRYPT_MODE, secretKeySpec)
      decryptingCipher.doFinal(data)

where secretKeySpec is object with algorithm: DESede and key, which is bit[] equal to mine.

I have no idea what is wrong in my code.

Does CryptoJs works wrong, or maybe I forgot about something in my decoding.

Do you have any clues what can be wrong?


问:
Updating array with React hooks
I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?</p>

```<code>const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}
</code>```

答:
You can also do it like this:</p>

```<code>const updateTrick = () => {
    modifyTrick(oldTrick => {
      oldTrick[0] = 1;
      return oldTrick;
    });
};
</code>```

Title: Updating array with React hooks

Body:
I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}

Body:
You can also do it like this:

const updateTrick = () => {
    modifyTrick(oldTrick => {
      oldTrick[0] = 1;
      return oldTrick;
    });
};