问:
google invisible reCaptcha server side validation is failing
i have integrated the invisible reCaptcha in my application and the client side response is coming as part of solving the image challenge. i am then calling a angular function to validate user response on server side using below code. where  onloginSubmit(token) is the success call back.

```<code><button id="btnLogin" ng-disabled="loginForm.$invalid"
                                class="g-recaptcha primarybtn margin-left-zero form-control-input"
                                data-sitekey="{{public_key}}"
                                data-callback='onloginSubmit'>{{'label_login' |
                                translate}}</button>

<script>
   function onloginSubmit(token) {
       angular.element(document.getElementById('loginForm')).scope().verifyReCaptcha(token);
   };
 </script>
</code>```

in angular i am calling the verifyReCaptcha as below.

```<code>$scope.public_key = "------ My Site Key -------";
  $scope.private_key = "------ My Secret Key -------";
  $scope.verifyReCaptchaURL = "https://www.google.com/recaptcha/api/siteverify";

$scope.verifyReCaptcha = function(reCaptchaToken){
       var captchaData = {
              secret : $scope.private_key,
              response : reCaptchaToken
      }

      $http({
          headers: {
            'Accept': 'application/json,text/plain',
            'Content-Type': 'application/json;application/x-www-form-urlencoded;charset=utf-8;',
          },
          url: $scope.verifyReCaptchaURL,
          method: 'POST',
          data: captchaData
        }).success(function (data) {
             console.log("success");
             $scope.login();
        }).error(function (data) {
             console.log("error");
             $window.location.reload(true);
        });
  };
</code>```

when i hit the api service https://www.google.com/recaptcha/api/siteverify . i get the below error.

```<code>Failed to load https://www.google.com/recaptcha/api/siteverify: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405.
</code>```

i couldnt find more documentation for the issue.

what is it that i am doing wrong and also if there is any error the recaptcha does not come up and the login button which i am using fails to respond.

n the request i am mentioning the Method as Post, the method is over ridden as Options and the request payload which i am sending is not present. this is what i got in the networks tab

Request URL:https://www.google.com/recaptcha/api/siteverify
Request Method:OPTIONS
Status Code:405
Remote Address:10.120.118.50:8080
Referrer Policy:no-referrer-when-downgrade

答:
Most of the thing you did a great job. One thing is to require in your application is communicate to an external domain so you can include HTTP header content type is include a JSONP format.</p>

```<code> $http({
      headers: {
        'Accept': 'application/json,text/plain',
        'Content-Type': 'application/jsonp;application/x-www-form-urlencoded;charset=utf-8;',
      },
      url: $scope.verifyReCaptchaURL,
      method: 'POST',
      data: captchaData
    }).success(function (data) {
         console.log("success");
         $scope.login();
    }).error(function (data) {
         console.log("error");
         $window.location.reload(true);
    });
</code>```

Body:
i have integrated the invisible reCaptcha in my application and the client side response is coming as part of solving the image challenge. i am then calling a angular function to validate user response on server side using below code. where  onloginSubmit(token) is the success call back.

<button id="btnLogin" ng-disabled="loginForm.$invalid"
                                class="g-recaptcha primarybtn margin-left-zero form-control-input"
                                data-sitekey="{{public_key}}"
                                data-callback='onloginSubmit'>{{'label_login' |
                                translate}}</button>

in angular i am calling the verifyReCaptcha as below.

$scope.public_key = "------ My Site Key -------";
  $scope.private_key = "------ My Secret Key -------";
  $scope.verifyReCaptchaURL = "https://www.google.com/recaptcha/api/siteverify";

$scope.verifyReCaptcha = function(reCaptchaToken){
       var captchaData = {
              secret : $scope.private_key,
              response : reCaptchaToken
      }

      $http({
          headers: {
            'Accept': 'application/json,text/plain',
            'Content-Type': 'application/json;application/x-www-form-urlencoded;charset=utf-8;',
          },
          url: $scope.verifyReCaptchaURL,
          method: 'POST',
          data: captchaData
        }).success(function (data) {
             console.log("success");
             $scope.login();
        }).error(function (data) {
             console.log("error");
             $window.location.reload(true);
        });
  };

when i hit the api service https://www.google.com/recaptcha/api/siteverify . i get the below error.

Failed to load https://www.google.com/recaptcha/api/siteverify: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405.

i couldnt find more documentation for the issue.

what is it that i am doing wrong and also if there is any error the recaptcha does not come up and the login button which i am using fails to respond.

n the request i am mentioning the Method as Post, the method is over ridden as Options and the request payload which i am sending is not present. this is what i got in the networks tab

Request URL:https://www.google.com/recaptcha/api/siteverify
Request Method:OPTIONS
Status Code:405
Remote Address:10.120.118.50:8080
Referrer Policy:no-referrer-when-downgrade

Body:
Most of the thing you did a great job. One thing is to require in your application is communicate to an external domain so you can include HTTP header content type is include a JSONP format.

 $http({
      headers: {
        'Accept': 'application/json,text/plain',
        'Content-Type': 'application/jsonp;application/x-www-form-urlencoded;charset=utf-8;',
      },
      url: $scope.verifyReCaptchaURL,
      method: 'POST',
      data: captchaData
    }).success(function (data) {
         console.log("success");
         $scope.login();
    }).error(function (data) {
         console.log("error");
         $window.location.reload(true);
    });


来源: stackexchange

问:
How do I create arrays within an array in C without a predefined size?
I would like to create arrays within an array in C without a pre-defined number of characters or input in the array.
The following is my code:

```<code>{
    int noOfStudents,noOfItems;
    int *grades;
    int i;
    char a[];
    printf("Please enter number of students\n");
    scanf("%d", &noOfStudents);
    printf("Please enter number of items\n");
    scanf("%d", &noOfItems);

    for (i = 0; i < noOfStudents; i++)
    {
        a[i] = (int *)malloc((sizeof(int))*noOfItems);
    }
</code>```

I've been thrown an error

c(2133): 'a': unknown size

How do I successfully create arrays within an array by means of malloc?

答: You may try the function malloc, which dynamically allocates memory and returns a pointer to it. Then you can cast the pointer to a pointer pointing to an array of a certain type.

ContentLicense: CC BY-SA 3.0

Body:
I would like to create arrays within an array in C without a pre-defined number of characters or input in the array.
The following is my code:

{
    int noOfStudents,noOfItems;
    int *grades;
    int i;
    char a[];
    printf("Please enter number of students\n");
    scanf("%d", &noOfStudents);
    printf("Please enter number of items\n");
    scanf("%d", &noOfItems);

    for (i = 0; i < noOfStudents; i++)
    {
        a[i] = (int *)malloc((sizeof(int))*noOfItems);
    }

I've been thrown an error

c(2133): 'a': unknown size

How do I successfully create arrays within an array by means of malloc?


问:
How to resize Twitter Bootstrap modal dynamically based on the content
I have database content which has different types of data, such as Youtube videos, Vimeo videos, text, Imgur pictures, etc. All of them have different heights and widths. All I have found while searching the Internet is changing the size to only one parameter. It has to be same as the content in the popup.

This is my HTML code. I also use Ajax to call the content.

```<code><div id="modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="ModalLabel"></h3>
    </div>
    <div class="modal-body">

    </div>
</div>
</code>```

答:
I had the same problem with bootstrap 3 and the modal-body div's height not wanting to be greater than 442px.  This was all the css needed to fix it in my case:</p>

```<code>.modal-body {
    overflow-y: auto;
}
</code>```

Body:
I have database content which has different types of data, such as Youtube videos, Vimeo videos, text, Imgur pictures, etc. All of them have different heights and widths. All I have found while searching the Internet is changing the size to only one parameter. It has to be same as the content in the popup.

This is my HTML code. I also use Ajax to call the content.

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Body:
I had the same problem with bootstrap 3 and the modal-body div's height not wanting to be greater than 442px.  This was all the css needed to fix it in my case:

.modal-body {
    overflow-y: auto;
}


问:
dashed lines show in Graphical Layout but not on devices
I am using paint to draw a dashed line in android.

```<code>dashed.setPathEffect(new DashPathEffect(new float[] { 5, 5 }, 0));
</code>```

During development, everything shows up fine in the Graphical Layout view. But when I plugin a real device, the device shows a solid line. At first I thought it was because my devices were all LG. Then I tested on a Samsung S4: same problem. Does anyone know how to fix this discrepancy? It makes no sense that the Graphical Layout is saying one thing and yet no actual device agrees with it. Any advice?

答:
disable hardware acceleration might be not best way, try this from here :</p>

```<code>Path baseline = new Path();
baseline.moveTo(0, 0);
baseline.lineTo(100, 0);
canvas.drawPath(baseline, paint);
</code>```

Body:
I am using paint to draw a dashed line in android.

dashed.setPathEffect(new DashPathEffect(new float[] { 5, 5 }, 0));

During development, everything shows up fine in the Graphical Layout view. But when I plugin a real device, the device shows a solid line. At first I thought it was because my devices were all LG. Then I tested on a Samsung S4: same problem. Does anyone know how to fix this discrepancy? It makes no sense that the Graphical Layout is saying one thing and yet no actual device agrees with it. Any advice?

Body:
disable hardware acceleration might be not best way, try this from here :

Path baseline = new Path();
baseline.moveTo(0, 0);
baseline.lineTo(100, 0);
canvas.drawPath(baseline, paint);


问:
How is set() implemented?
I've seen people say that set objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have?

Every answer here was really enlightening, but I can only accept one, so I'll go with the closest answer to my original question. Thanks all for the info!

答:
To emphasize a little more the difference between set's and dict's, here is an excerpt from the setobject.c comment sections, which clarify's the main difference of set's against dicts.

Use cases for sets differ considerably from dictionaries where looked-up
     keys are more likely to be present.  In contrast, sets are primarily
     about membership testing where the presence of an element is not known in
     advance.  Accordingly, the set implementation needs to optimize for both
     the found and not-found case.

source on github

Title: How is set() implemented?


问:
Manifest package and applicationID can differ from real java packages of the application?
Let's analyze this situation:

Manifest package and application ID on gradle file: com.myweb.mysuperapppackagenamewithaso

Real java packages inside the sourcecode of my app:

```<code>com.mysourcecode.package1
com.mysourcecode.package2
</code>```

with the MainActivity here:

```<code>com.mysourcecode.package1.MainActivity.java
</code>```

Is this possible and safe? Manifest package and applicationID can differ from real java packages of the application?

答:
Below given are the three things which we need to think about,

```<code>   applicationId: BuildConfig.APPLICATION_ID
   packageName: getApplicationContext().getPackageName()
   Java package: BuildConfig.class.getPackage().toString()
</code>```

getPackageName gives the same applicationId which is created at the final moment from the gradle file and it overrides the AndroidManifest package. The final AndroidManifest contains the same applicationId.The getPackageName is the same as the applicationId as the applicationId overrides the packageName in the AndroidManifest at the final moment.

But for the Java code, the package is same as the project structure. The package that is used in your source code to refer to your R class, and to resolve any relative activity, service registrations, continues to be called the package as defined in your manifest. So, the AndroidManifest should have the package same as Java package to resolve relative activity, service.

So, with the same java package, we can create any number of APKs with all unique applicationId.

Example : application flavors

Reference : Android Package Name Vs Application ID

Body:
Let's analyze this situation:

Manifest package and application ID on gradle file: com.myweb.mysuperapppackagenamewithaso

Real java packages inside the sourcecode of my app:

com.mysourcecode.package1
com.mysourcecode.package2

with the MainActivity here:

com.mysourcecode.package1.MainActivity.java

Is this possible and safe? Manifest package and applicationID can differ from real java packages of the application?

Body:
Below given are the three things which we need to think about,

   applicationId: BuildConfig.APPLICATION_ID
   packageName: getApplicationContext().getPackageName()
   Java package: BuildConfig.class.getPackage().toString()

getPackageName gives the same applicationId which is created at the final moment from the gradle file and it overrides the AndroidManifest package. The final AndroidManifest contains the same applicationId.The getPackageName is the same as the applicationId as the applicationId overrides the packageName in the AndroidManifest at the final moment.

But for the Java code, the package is same as the project structure. The package that is used in your source code to refer to your R class, and to resolve any relative activity, service registrations, continues to be called the package as defined in your manifest. So, the AndroidManifest should have the package same as Java package to resolve relative activity, service.

So, with the same java package, we can create any number of APKs with all unique applicationId.

Example : application flavors

Reference : Android Package Name Vs Application ID


问:
Inherit height from parent with box-sizing: border-box
Here is the deal.
I have parent div with css like:

```<code>.parent{box-sizing: border-box; height: 60px; border: 1px solid green;}
</code>```

Child div with css:

```<code>.child{height:inherit;background: red}
</code>```

Here is markup:

.parent {
  box-sizing: border-box;
  height: 60px;
  border: 1px solid green;
}

.child {
  height:inherit;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child"></div>
</div></code>```

https://jsfiddle.net/CheWebDev/fcecuvut/1/

So how to get inherit height from parent? Is it possible with box-sizing: border-box prop.?

答:
Why not using height: 100%. As this is basicly the same as setting height: inherit. Where height: inherit makes it the exact height as its parent, height: 100% will make it based on the parent rules.

So if a padding isset (in your case a border), it will not overflow the padding. But only fills the available height of its parent.

.parent{box-sizing: border-box; height: 60px; border: 10px solid green;}
.child{height:100%;background: red}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div class="parent"><div class="child"></div></div></code>```

Body:
Here is the deal.
I have parent div with css like:

.parent{box-sizing: border-box; height: 60px; border: 1px solid green;}

Child div with css:

.child{height:inherit;background: red}

Here is markup:

.parent {
  box-sizing: border-box;
  height: 60px;
  border: 1px solid green;
}

.child {
  height:inherit;
  background: red;
}

https://jsfiddle.net/CheWebDev/fcecuvut/1/

So how to get inherit height from parent? Is it possible with box-sizing: border-box prop.?

Body:
Why not using height: 100%. As this is basicly the same as setting height: inherit. Where height: inherit makes it the exact height as its parent, height: 100% will make it based on the parent rules.

So if a padding isset (in your case a border), it will not overflow the padding. But only fills the available height of its parent.

.parent{box-sizing: border-box; height: 60px; border: 10px solid green;}
.child{height:100%;background: red}

   <div class="parent"><div class="child"></div></div>


问:
Prestashop module development - How can I call a controller initMethod at module installation?
In controllers/front I created a controller named abandonedCarts:

```<code>class <moduleName>AbandonedCartsModuleFrontController extends ModuleFrontController
{

public function __construct()
{
    parent::__construct();
    $this->context = Context::getContext();
    $this->store_debug('Controller - __construct');
}

public function initContent()
{
    parent::initContent();
    $this->store_debug('Controller - init');
}

}
</code>```

where store_debug is a function that simply logs on the db something (just for check).
Thanks to this I know that when I call the controller from URL in this way

```<code>site/index.php?fc=module&module=olyo&controller=abandonedCarts
</code>```

the construct and init methods are being called, but what I need is the controller being called when the module is installed (or at its first start).

In the main file I also put in the constructor this line:

```<code>$this->controllers = array('abandonedCarts');
</code>```

But I'm not sure I even need it

答:
You should not instantiate a FrontController in admin context, here is a workaround :

Your module :

```<code><?php
class MyModule extends Module {
  public install(){
     $result = parent::install();
     if ($result) {
         $this->doStuff();
     }
     return $result;
  }

  public function doStuff() {
     // do stuff
  }
}
</code>```

your controller

```<code><?php
class <moduleName>AbandonedCartsModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        parent::initContent();
        $this->module->doStuff();
    }
}
</code>```

Body:
In controllers/front I created a controller named abandonedCarts:

class <moduleName>AbandonedCartsModuleFrontController extends ModuleFrontController
{

public function __construct()
{
    parent::__construct();
    $this->context = Context::getContext();
    $this->store_debug('Controller - __construct');
}

public function initContent()
{
    parent::initContent();
    $this->store_debug('Controller - init');
}

}

where store_debug is a function that simply logs on the db something (just for check).
Thanks to this I know that when I call the controller from URL in this way

site/index.php?fc=module&module=olyo&controller=abandonedCarts

the construct and init methods are being called, but what I need is the controller being called when the module is installed (or at its first start).

In the main file I also put in the constructor this line:

$this->controllers = array('abandonedCarts');

But I'm not sure I even need it

Body:
You should not instantiate a FrontController in admin context, here is a workaround :

Your module :

<?php
class MyModule extends Module {
  public install(){
     $result = parent::install();
     if ($result) {
         $this->doStuff();
     }
     return $result;
  }

  public function doStuff() {
     // do stuff
  }
}

your controller

<?php
class <moduleName>AbandonedCartsModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        parent::initContent();
        $this->module->doStuff();
    }
}


问:
Unexpected character '@' You may need an appropriate loader to handle this file type
This is what I get when I try to run webpack: the error I get is:

"ERROR in ./v3/app/styles/main.scss
  Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '@' (1:0)
  You may need an appropriate loader to handle this file type."

it can't resolve @import, any ideas on this?

my webpack config is as follow:

```<code>    const childProcess = require('child_process')
    const CopyWebpackPlugin = require('copy-webpack-plugin')
    const ExtractTextPlugin = require('extract-text-webpack-plugin')
    const trimEnd = require('lodash/trimEnd')
    const webpack = require('webpack')
    const path = require('path')

    const ENV = {
      NODE_ENV: process.env.NODE_ENV,
      API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
    + process.env.NODE_ENV),
      BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
    count').toString(), '\n'),
      BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
    1').toString(), '\n'),
      BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
    -n 1').toString(), '\n')
    }
    const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
    process.env.NODE_ENV === 'prd'
    const CSS_MAPS = !prodLikeEnvironment
    module.exports = {

      entry: {
        init: [
          './app/init.js'
        ],
        login: [
          './app/login.js'
        ],
        authentication: [
          './v3/app/authenticator.js'
        ],
        common: [
          './app/common.js'
        ]
      },
      target: 'web',
      output: {
        path: path.join(__dirname, 'dist', process.env.NODE_ENV),
        pathinfo: true,
        publicPath: '/assets/widgets/login/v2/',
        filename: '[name].bundle.js',
        chunkFilename: '[id].bundle.js',
        libraryTarget: 'umd'
      },
      resolve: {
        alias: {
          'react': 'preact-compat',
          'react-dom': 'preact-compat'
        },
        modules: [
          path.resolve('./app'),
          path.resolve('./node_modules')
        ]
      },
      module: {
        loaders: [
          {
            test: /\.jsx?$/,
            loaders: ['babel-loader'],
            exclude: [/bower_components/, /node_modules/]
          },
          {
    // Transform our own .(scss|css) files with PostCSS and CSS-modules
            test: /\.(scss|css)$/,
            include: [path.resolve(__dirname, 'v3/app')],
            options: {
              sourceMap: true
            },
            loader: [
              `style-loader?singleton`,
              `css-loader?modules&importLoaders=1&localIdentName=
    [local]${process.env.CSS_MODULES_IDENT ||
    '_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
              'postcss-loader',
              `sass-loader?sourceMap=${CSS_MAPS}`
            ].join('!')
          },
          {
            test: /\.(scss|css)$/,
            exclude: [path.resolve(__dirname, 'v3/app')],
            options: {
            sourceMap: true
            },
            loader: [
              `style-loader?singleton`,
              `css-loader?sourceMap=${CSS_MAPS}`,
              `postcss-loader`,
              `sass-loader?sourceMap=${CSS_MAPS}`
            ].join('!')
          },
          {
            test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
            use: 'base64-font-loader'
          },
          {
            test: /.json$/,
            loader: 'json'
          },
          {
            test: /\.jpe?g$|\.gif$|\.png$/,
            use: 'base64-image-loader'
          },
          {
            test: /\.html?$/,
            loader: 'html'
          },
          {
            test: /\.js$/,
            loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
          }
        ]
      },
      plugins: [
        new webpack.LoaderOptionsPlugin({
          minimize: true
          // postcss: [
          //   autoprefixer({ browsers: 'last 2 versions' })
          // ]
        }),
        new CopyWebpackPlugin([
    { from: 'public' }
        ]),
        new ExtractTextPlugin('[name].bundle.css'),
        new webpack.DefinePlugin({
          ENV: JSON.stringify(ENV),
    // Only used for react prod bundle. Refer to ENV.NODE_ENV for business
    logic
          'process.env': {
            'NODE_ENV': JSON.stringify('production')
          }
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
          output: {
            comments: false
          },
          compress: {
            unsafe_comps: true,
            properties: true,
            keep_fargs: false,
            pure_getters: true,
            collapse_vars: true,
            unsafe: true,
            warnings: false,
            screw_ie8: true,
            sequences: true,
            dead_code: true,
            drop_debugger: true,
            comparisons: true,
            conditionals: true,
            evaluate: true,
            booleans: true,
            loops: true,
            unused: true,
            hoist_funs: true,
            if_return: true,
            join_vars: true,
            cascade: true,
            drop_console: true
          }
        })
      ]
    }
</code>```

答:
You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.

```<code>{
  test: /\.css$/,
  include: helpers.root('src', 'app'),
  loader: 'raw-loader'
},
// // css global which not include in components
{
  test: /\.css$/,
  exclude: helpers.root('src', 'app'),
  use: ExtractTextPlugin.extract({
    use: 'raw-loader'
  })
},

{
  test: /\.scss$/,
  include: helpers.root('src', 'app'),
  use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
  test: /\.scss$/,
  exclude: helpers.root('src', 'app'),
  use: ExtractTextPlugin.extract({
    use: ['raw-loader', 'sass-loader']
  })
}
</code>```

Add my root()function.

```<code>var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [_root].concat(args));
}
exports.root = root;
</code>```

Hope this will work.

ContentLicense: CC BY-SA 4.0

Body:
This is what I get when I try to run webpack: the error I get is:

"ERROR in ./v3/app/styles/main.scss
  Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '@' (1:0)
  You may need an appropriate loader to handle this file type."

it can't resolve @import, any ideas on this?

my webpack config is as follow:

    const childProcess = require('child_process')
    const CopyWebpackPlugin = require('copy-webpack-plugin')
    const ExtractTextPlugin = require('extract-text-webpack-plugin')
    const trimEnd = require('lodash/trimEnd')
    const webpack = require('webpack')
    const path = require('path')

    const ENV = {
      NODE_ENV: process.env.NODE_ENV,
      API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
    + process.env.NODE_ENV),
      BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
    count').toString(), '\n'),
      BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
    1').toString(), '\n'),
      BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
    -n 1').toString(), '\n')
    }
    const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
    process.env.NODE_ENV === 'prd'
    const CSS_MAPS = !prodLikeEnvironment
    module.exports = {

      entry: {
        init: [
          './app/init.js'
        ],
        login: [
          './app/login.js'
        ],
        authentication: [
          './v3/app/authenticator.js'
        ],
        common: [
          './app/common.js'
        ]
      },
      target: 'web',
      output: {
        path: path.join(__dirname, 'dist', process.env.NODE_ENV),
        pathinfo: true,
        publicPath: '/assets/widgets/login/v2/',
        filename: '[name].bundle.js',
        chunkFilename: '[id].bundle.js',
        libraryTarget: 'umd'
      },
      resolve: {
        alias: {
          'react': 'preact-compat',
          'react-dom': 'preact-compat'
        },
        modules: [
          path.resolve('./app'),
          path.resolve('./node_modules')
        ]
      },
      module: {
        loaders: [
          {
            test: /\.jsx?$/,
            loaders: ['babel-loader'],
            exclude: [/bower_components/, /node_modules/]
          },
          {
    // Transform our own .(scss|css) files with PostCSS and CSS-modules
            test: /\.(scss|css)$/,
            include: [path.resolve(__dirname, 'v3/app')],
            options: {
              sourceMap: true
            },
            loader: [
              `style-loader?singleton`,
              `css-loader?modules&importLoaders=1&localIdentName=
    [local]${process.env.CSS_MODULES_IDENT ||
    '_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
              'postcss-loader',
              `sass-loader?sourceMap=${CSS_MAPS}`
            ].join('!')
          },
          {
            test: /\.(scss|css)$/,
            exclude: [path.resolve(__dirname, 'v3/app')],
            options: {
            sourceMap: true
            },
            loader: [
              `style-loader?singleton`,
              `css-loader?sourceMap=${CSS_MAPS}`,
              `postcss-loader`,
              `sass-loader?sourceMap=${CSS_MAPS}`
            ].join('!')
          },
          {
            test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
            use: 'base64-font-loader'
          },
          {
            test: /.json$/,
            loader: 'json'
          },
          {
            test: /\.jpe?g$|\.gif$|\.png$/,
            use: 'base64-image-loader'
          },
          {
            test: /\.html?$/,
            loader: 'html'
          },
          {
            test: /\.js$/,
            loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
          }
        ]
      },
      plugins: [
        new webpack.LoaderOptionsPlugin({
          minimize: true
          // postcss: [
          //   autoprefixer({ browsers: 'last 2 versions' })
          // ]
        }),
        new CopyWebpackPlugin([
    { from: 'public' }
        ]),
        new ExtractTextPlugin('[name].bundle.css'),
        new webpack.DefinePlugin({
          ENV: JSON.stringify(ENV),
    // Only used for react prod bundle. Refer to ENV.NODE_ENV for business
    logic
          'process.env': {
            'NODE_ENV': JSON.stringify('production')
          }
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
          output: {
            comments: false
          },
          compress: {
            unsafe_comps: true,
            properties: true,
            keep_fargs: false,
            pure_getters: true,
            collapse_vars: true,
            unsafe: true,
            warnings: false,
            screw_ie8: true,
            sequences: true,
            dead_code: true,
            drop_debugger: true,
            comparisons: true,
            conditionals: true,
            evaluate: true,
            booleans: true,
            loops: true,
            unused: true,
            hoist_funs: true,
            if_return: true,
            join_vars: true,
            cascade: true,
            drop_console: true
          }
        })
      ]
    }

Body:
You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.

{
  test: /\.css$/,
  include: helpers.root('src', 'app'),
  loader: 'raw-loader'
},
// // css global which not include in components
{
  test: /\.css$/,
  exclude: helpers.root('src', 'app'),
  use: ExtractTextPlugin.extract({
    use: 'raw-loader'
  })
},

{
  test: /\.scss$/,
  include: helpers.root('src', 'app'),
  use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
  test: /\.scss$/,
  exclude: helpers.root('src', 'app'),
  use: ExtractTextPlugin.extract({
    use: ['raw-loader', 'sass-loader']
  })
}

Add my root()function.

var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [_root].concat(args));
}
exports.root = root;

Hope this will work.


问:
Initializing FB session on client using javascript sdk and long lived token
I am a bit confused about the implementation of access token in FB graph api.

According to the docs I can pass the access token to client and initialize the session using this access token

https://developers.facebook.com/docs/facebook-login/access-tokens

So if I have a long lived access token on server side and pass it to the javascript sdk on client side...is it possible to make graph api calls from client? How?

答:
Facebooks's JS SDK .api() method always accepts a parameter called access_token, that can be a User access_token or a Page access_token depending on the calls you are making. See the following example using Angular's SDK:

Get a
this.fb.api(pageId + '?fields=picture,fan_count,name', 'get', { 'access_token': <USER_ACCESS_TOKEN> })

Where <USER_ACCESS_TOKEN> is given to you by your backend without exposing your API secret ever. So, in summary.

See Generating Long-Lived User Tokens from Server-Side Long-Lived Tokens for more info.


问:
String to bytes to Big Int conversion VICE VERSA error
im trying to convert a hash to a big integer so i can do some calculations with it. Im successful in that but on the other side i need to be able to convert the big integer back to the hash to do verification. But i cant do the conversion back succesfully, below is my code and the output. Please do advise and assist..

This is the code

```<code>//convert hash to bytes then to big int to mod pow
BigInteger hashy = new
BigInteger(hash.getBytes(StandardCharsets.ISO_8859_1));
System.out.println("hashy: " +hashy);
//test if convert back to big int works
String convertedBackHash = (hashy.toByteArray()).toString();
System.out.println("hash to hashy to hash: " + convertedBackHash);
</code>```

This is the output

```<code>hash: d1bb961ac85f6d9ae66b469b5cabe83f9f88e4ee
hashy: 835979497806227327262557895525398820611883198135120938003873334575862278693562754177889725605221
hash to hashy to hash: [B@60e53b93
</code>```

Anyone knows what went wrong?

答:
```<code>String convertedBackHash = (hashy.toByteArray()).toString();
</code>```

You are using Array#toString method which represents array object in hex format.

If you want to convert your bytes to string

```<code>String result = new String(hashy.toByteArray());
System.out.println("hash to hashy to hash: " + result);
</code>```

Body:
im trying to convert a hash to a big integer so i can do some calculations with it. Im successful in that but on the other side i need to be able to convert the big integer back to the hash to do verification. But i cant do the conversion back succesfully, below is my code and the output. Please do advise and assist..

This is the code

//convert hash to bytes then to big int to mod pow
BigInteger hashy = new
BigInteger(hash.getBytes(StandardCharsets.ISO_8859_1));
System.out.println("hashy: " +hashy);
//test if convert back to big int works
String convertedBackHash = (hashy.toByteArray()).toString();
System.out.println("hash to hashy to hash: " + convertedBackHash);

This is the output

hash: d1bb961ac85f6d9ae66b469b5cabe83f9f88e4ee
hashy: 835979497806227327262557895525398820611883198135120938003873334575862278693562754177889725605221
hash to hashy to hash: [B@60e53b93

Anyone knows what went wrong?

Body:
String convertedBackHash = (hashy.toByteArray()).toString();

You are using Array#toString method which represents array object in hex format.

If you want to convert your bytes to string

String result = new String(hashy.toByteArray());
System.out.println("hash to hashy to hash: " + result);


问:
linking issue - trying to build a library and use another archive with it
Is it possible to build a library that uses another, already compiled library?

I have some make files that are used to normally build an executable. When making the executable, I use -L ../include/lib1.a to include the original library.

Now, I am building a separate program that is calling the classes from the executable, which was never built into a library, just compiled to the executable with a link like

```<code>${CPP} -c ${INC} ${CFLAGS} MyFile.cpp ${OBJ} ${LIB2} -lm
</code>```

Where LIB2 includes the reference to lib1.a

Now I want to access the class MyFile.cpp directly, and when I build it to its own library lib2.a, and try to call it from the new program, I get a bunch of errors that the classes it references are missing. This is in spite of the fact that when building the new program I am linking in both lib1.a and lib2.a

答:
Should:

```<code>-L../include/lib1.a
</code>```

not be:

```<code>-L../include -llib1
</code>```

I.e. -L denotes the library search path and -l the archive name?

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to build a library that uses another, already compiled library?

I have some make files that are used to normally build an executable. When making the executable, I use -L ../include/lib1.a to include the original library.

Now, I am building a separate program that is calling the classes from the executable, which was never built into a library, just compiled to the executable with a link like

${CPP} -c ${INC} ${CFLAGS} MyFile.cpp ${OBJ} ${LIB2} -lm

Where LIB2 includes the reference to lib1.a

Now I want to access the class MyFile.cpp directly, and when I build it to its own library lib2.a, and try to call it from the new program, I get a bunch of errors that the classes it references are missing. This is in spite of the fact that when building the new program I am linking in both lib1.a and lib2.a

Body:
Should:

-L../include/lib1.a

not be:

-L../include -llib1

I.e. -L denotes the library search path and -l the archive name?


问:
Shrink the size of 2D array by removing specific rows and columns from it
I'm learning C, and I can't find a solution to this problem.

If I have a matrix of random size filled with '*'(star), '-'(horizontal bar), '|'(vertical bar),'+'(plus sign) and I want to remove every row that has a '-', every column that has a '|', every row and column in which there is a '+'.

How would i reduce the size of the matrix so that when i print the remaining '*'(star) there are no rows and columns between them that were removed?

For example:

```<code>char mat[3][3] = {{'|', '*', '*'},
                  {'*', '*', '*'},
                  {'*', '*', '*'}};
</code>```

The output would be:

```<code>**
**
**
</code>```

Another example:

```<code>char mat[3][3] = {{'*', '*', '*'},
                  {'*', '+', '*'},
                  {'*', '*', '*'}};
</code>```

The output would be:

```<code>**
**
</code>```

Larger matrix:

```<code>char mat[4][5] = {{'*', '|', '*', '|', '*'},
                  {'*', '*', '*', '*', '*'},
                  {'*', '+', '*', '-', '*'}
                  {'*', '*', '*', '*', '-'}};
</code>```

The output would be:

```<code>***
***
</code>```

Thanks in advance.

答:
You cannot shrink a statically defined array as the one in your example. You can mark a column or a row though, so that when the printing phase comes around, you simply skip the invalidated column(s) and row(s).

Example for the '|' case:

```<code>#include <stdio.h>

#define N 3
#define M 3

void invalidate_col(char mat[N][M], const int col)
{
    for(int i = 0; i < N; ++i)
    {
        mat[i][col] = 'n';
    }
}

void print(char mat[N][M])
{
    for(int i = 0; i < N; ++i)
    {
        for(int j = 0; j < M; ++j)
        {
            if(mat[i][j] != 'n')
                printf("%c ", mat[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    char mat[N][M] = {{'|', '*', '*'},
                  {'*', '*', '*'},
                  {'*', '*', '*'}};
    for(int i = 0; i < N; ++i)
    {
        for(int j = 0; j < M; ++j)
        {
            if(mat[i][j] == '|')
            {
                invalidate_col(mat, j);
            }
        }
    }
    print(mat);
    return 0;
}
</code>```

Output:

```<code>* *
* *
* *
</code>```

If you really need to delete these column(s) and row(s), then you need to dynamically allocate the matrix (check my example), use realloc() to shrink it accordingly, and at the end free() to dellocate that memory.

Body:
I'm learning C, and I can't find a solution to this problem.

If I have a matrix of random size filled with '*'(star), '-'(horizontal bar), '|'(vertical bar),'+'(plus sign) and I want to remove every row that has a '-', every column that has a '|', every row and column in which there is a '+'.

How would i reduce the size of the matrix so that when i print the remaining '*'(star) there are no rows and columns between them that were removed?

For example:

char mat[3][3] = {{'|', '*', '*'},
                  {'*', '*', '*'},
                  {'*', '*', '*'}};

The output would be:

**
**
**

Another example:

char mat[3][3] = {{'*', '*', '*'},
                  {'*', '+', '*'},
                  {'*', '*', '*'}};

The output would be:

**
**

Larger matrix:

char mat[4][5] = {{'*', '|', '*', '|', '*'},
                  {'*', '*', '*', '*', '*'},
                  {'*', '+', '*', '-', '*'}
                  {'*', '*', '*', '*', '-'}};

The output would be:

***
***

Thanks in advance.

Body:
You cannot shrink a statically defined array as the one in your example. You can mark a column or a row though, so that when the printing phase comes around, you simply skip the invalidated column(s) and row(s).

Example for the '|' case:

#include <stdio.h>

#define N 3
#define M 3

void invalidate_col(char mat[N][M], const int col)
{
    for(int i = 0; i < N; ++i)
    {
        mat[i][col] = 'n';
    }
}

void print(char mat[N][M])
{
    for(int i = 0; i < N; ++i)
    {
        for(int j = 0; j < M; ++j)
        {
            if(mat[i][j] != 'n')
                printf("%c ", mat[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    char mat[N][M] = {{'|', '*', '*'},
                  {'*', '*', '*'},
                  {'*', '*', '*'}};
    for(int i = 0; i < N; ++i)
    {
        for(int j = 0; j < M; ++j)
        {
            if(mat[i][j] == '|')
            {
                invalidate_col(mat, j);
            }
        }
    }
    print(mat);
    return 0;
}

Output:

* *
* *
* *

If you really need to delete these column(s) and row(s), then you need to dynamically allocate the matrix (check my example), use realloc() to shrink it accordingly, and at the end free() to dellocate that memory.


问:
What is the Vuex "context" object?
I am trying to get better understanding of what the "context" object is in Vuex.

The context object is referred to numerous times in the Vuex documentation.  For example, in https://vuex.vuejs.org/en/actions.html, we have:

Action handlers receive a context object which exposes the same set of
  methods/properties on the store instance, so you can call
  context.commit to commit a mutation...

I understand how to use it, and also that we can use destructuring if we only want to use the "commit" from the context object, but was hoping for a little more depth, just so I can better understand what is going on.

As a start, I found a couple ~8.5 year old posts on the "context object" as a  pattern:
what is context object design pattern? and
Can you explain the Context design pattern?

However, specifically to Vuex, I'd love a better understanding of:

What is the context object / what is its purpose?

What are all the properties/methods that it is making available to use in Vuex?

Thank you!

答:
From the documentation you pointed out you can read:

We will see why this context object is not the store instance itself when we introduce Modules later.

The main idea of the context object is to abstract the scope of the current Module. If you simply access store.state, it will always be the root state.

The context object of actions and its properties/methods are described here in the source code and also referenced in the API documentation

Here is the list:

```<code>{
  state,      // same as store.state, or local state if in modules
  rootState,  // same as store.state, only in modules
  commit,     // same as store.commit
  dispatch,   // same as store.dispatch
  getters,    // same as store.getters, or local getters if in modules
  rootGetters // same as store.getters, only in modules
}
</code>```

Title: What is the Vuex "context" object?

Body:
From the documentation you pointed out you can read:

We will see why this context object is not the store instance itself when we introduce Modules later.

The main idea of the context object is to abstract the scope of the current Module. If you simply access store.state, it will always be the root state.

The context object of actions and its properties/methods are described here in the source code and also referenced in the API documentation

Here is the list:

{
  state,      // same as store.state, or local state if in modules
  rootState,  // same as store.state, only in modules
  commit,     // same as store.commit
  dispatch,   // same as store.dispatch
  getters,    // same as store.getters, or local getters if in modules
  rootGetters // same as store.getters, only in modules
}


问:
Start JMeter thread after another thread
I want to run a thread x times. The thread group contains three samplers and because I dont want them to be mixed up in the result windows I only want to start the next thread when another is finished. I don't want to use a Ramp-Up Period because a thread could take 1 to 20 seconds.</p>

答:
Your use case is not very clear, however if you need to limit JMeter to X concurrent threads only the most obvious choice would be going for the Concurrency Thread Group

As per Advanced Load Testing Scenarios with JMeter Part 4 - Stepping Thread Group and Concurrency Thread Group article:

The Concurrency Thread Group provides a better simulation of user behaviour because it lets you control the length of your test more easily, and it creates replacement threads in case a thread finishes in the middle of the process.

You can install Concurrency Thread Group as a part of Custom Threads Group bundle using JMeter Plugins Manager

Regarding your three listeners bit, I would recommend reconsidering this approach as per JMeter Best Practices you should not be using any listeners, instead of it you need to run JMeter in non-GUI mode and use -l command-line argument to specify the results file name. Once your test is finished you can open the .jtl results file with a listener of your choice or generate a reporting dashboard from it.


问:
Parse data from OpenWeatherMap, using retrofit2 and rxJava2
I've started to learn Retrofit and RxJava, and I've decided to create weatherApp. Now my goal is to retrieve weather data from OpenWeatherMap Api. Here's my code:
For api:

```<code>package com.example.aldres.workingwithapis.Api;

import com.example.aldres.workingwithapis.models.WeatherData;

import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;

public interface Api {
    @GET("weather?")
    Observable<WeatherData> getWeatherData(@Query("q") String city);
}
</code>```

Also code for my WeatherData model:

```<code>package com.example.aldres.workingwithapis.models;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class WeatherData {

    @SerializedName("coord")
    @Expose
    private Coord coord;
    @SerializedName("weather")
    @Expose
    private List<Weather> weather = null;
    @SerializedName("base")
    @Expose
    private String base;
    @SerializedName("main")
    @Expose
    private Main main;
    @SerializedName("visibility")
    @Expose
    private Integer visibility;
    @SerializedName("wind")
    @Expose
    private Wind wind;
    @SerializedName("clouds")
    @Expose
    private Clouds clouds;
    @SerializedName("dt")
    @Expose
    private Integer dt;
    @SerializedName("sys")
    @Expose
    private Sys sys;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("cod")
    @Expose
    private Integer cod;

    public Coord getCoord() {
        return coord;
    }

    public void setCoord(Coord coord) {
        this.coord = coord;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }

    public Integer getVisibility() {
        return visibility;
    }

    public void setVisibility(Integer visibility) {
        this.visibility = visibility;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }

    public Clouds getClouds() {
        return clouds;
    }

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;
    }

    public Integer getDt() {
        return dt;
    }

    public void setDt(Integer dt) {
        this.dt = dt;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        this.sys = sys;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCod() {
        return cod;
    }

    public void setCod(Integer cod) {
        this.cod = cod;
    }

}
</code>```

And also my mainActivity:

```<code>package com.example.aldres.workingwithapis;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.aldres.workingwithapis.Api.Api;
import com.example.aldres.workingwithapis.models.WeatherData;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private TextView middleText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        middleText = findViewById(R.id.middleText);

        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://api.openweathermap.org/data/2.5/")
                .build();
        Api apiService = retrofit.create(Api.class);

        Observable<WeatherData> observable = apiService.getWeatherData("London");

                observable
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WeatherData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(WeatherData weatherData) {
                        middleText.setText(weatherData.getWind());
                    }
                });
    }
}
</code>```

At this point, my app should display string with wind parameter into my TextView middleText, but when I start my app, it starts without any errors, but I don't have my text in the TextView. What have I done wrong?

答:
Your request is probably erroring out without you knowing about it as you ignore the onError method.
Add e.printStackTrace() to that method to see if this is the case.

Body:
I've started to learn Retrofit and RxJava, and I've decided to create weatherApp. Now my goal is to retrieve weather data from OpenWeatherMap Api. Here's my code:
For api:

package com.example.aldres.workingwithapis.Api;

import com.example.aldres.workingwithapis.models.WeatherData;

import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;

public interface Api {
    @GET("weather?")
    Observable<WeatherData> getWeatherData(@Query("q") String city);
}

Also code for my WeatherData model:

package com.example.aldres.workingwithapis.models;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class WeatherData {

    @SerializedName("coord")
    @Expose
    private Coord coord;
    @SerializedName("weather")
    @Expose
    private List<Weather> weather = null;
    @SerializedName("base")
    @Expose
    private String base;
    @SerializedName("main")
    @Expose
    private Main main;
    @SerializedName("visibility")
    @Expose
    private Integer visibility;
    @SerializedName("wind")
    @Expose
    private Wind wind;
    @SerializedName("clouds")
    @Expose
    private Clouds clouds;
    @SerializedName("dt")
    @Expose
    private Integer dt;
    @SerializedName("sys")
    @Expose
    private Sys sys;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("cod")
    @Expose
    private Integer cod;

    public Coord getCoord() {
        return coord;
    }

    public void setCoord(Coord coord) {
        this.coord = coord;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }

    public Integer getVisibility() {
        return visibility;
    }

    public void setVisibility(Integer visibility) {
        this.visibility = visibility;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }

    public Clouds getClouds() {
        return clouds;
    }

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;
    }

    public Integer getDt() {
        return dt;
    }

    public void setDt(Integer dt) {
        this.dt = dt;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        this.sys = sys;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCod() {
        return cod;
    }

    public void setCod(Integer cod) {
        this.cod = cod;
    }

}

And also my mainActivity:

package com.example.aldres.workingwithapis;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.aldres.workingwithapis.Api.Api;
import com.example.aldres.workingwithapis.models.WeatherData;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private TextView middleText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        middleText = findViewById(R.id.middleText);

        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://api.openweathermap.org/data/2.5/")
                .build();
        Api apiService = retrofit.create(Api.class);

        Observable<WeatherData> observable = apiService.getWeatherData("London");

                observable
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WeatherData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(WeatherData weatherData) {
                        middleText.setText(weatherData.getWind());
                    }
                });
    }
}

At this point, my app should display string with wind parameter into my TextView middleText, but when I start my app, it starts without any errors, but I don't have my text in the TextView. What have I done wrong?


问:
How to include single row multiple column subquery (PIPELINED function) results in the result set
I am using Oracle 11g.

So, lets say that I have a test data table like this one

```<code>with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)
</code>```

Also I have a piplined function that returns one row per call, with multiple columns like the following:

```<code>CREATE OR REPLACE PACKAGE MY_PACK AS
  TYPE result_record is RECORD(
   surname           varchar2(27),
   telephone          varchar2(50),
   place_of_birth     varchar2(50)
       );

  TYPE result_table IS TABLE OF result_record;
  function runPipe(id number) RETURN result_table PIPELINED;
END ERC_PACK;
/

CREATE OR REPLACE PACKAGE BODY MY_PACK AS
    function runPipe(id number) RETURN result_table PIPELINED IS
    rec           result_record:=null;
    begin
       if  (id=1) then
         select 'Smih','139289289','Paris' into rec from dual;
       end if;
       if  (id=2) then
         select 'Lock','1888888888','London' into rec from dual;
       end if;
       if  (id=3) then
         select 'May','99999999999','Berlin' into rec from dual;
       end if;
       pipe row (rec);
       return;
  end;
END ERC_PACK;
/
</code>```

And of course the

```<code>select * from table(MY_PACK.runPipe(1))
</code>```

returns

```<code>Smih    139289289   Paris
</code>```

Now I would like a select statement that will return all the rows of the test_data  along with the corresponding values from pipeline function

e.g. something like

```<code>select test_data.*, (select * from table(MY_PACK.runPipe(id))) from test_data
</code>```

which of course doses not work
but the expected results would be something like:

```<code>1 John  Smih    139289289   Paris
2 Jack  Lock    1888888888  London
3 Peter May     99999999999 Berlin
</code>```

So how to achieve the above expected result, given the test_data table and the pipelined function?

答:
try this select :</p>

```<code>    with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)
select td.*, s.*
from test_data td
LEFT JOIN  table(MY_PACK.runPipe(td.id)) s ON 1 = 1;
</code>```

Body:
I am using Oracle 11g.

So, lets say that I have a test data table like this one

with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)

Also I have a piplined function that returns one row per call, with multiple columns like the following:

CREATE OR REPLACE PACKAGE MY_PACK AS
  TYPE result_record is RECORD(
   surname           varchar2(27),
   telephone          varchar2(50),
   place_of_birth     varchar2(50)
       );

  TYPE result_table IS TABLE OF result_record;
  function runPipe(id number) RETURN result_table PIPELINED;
END ERC_PACK;
/

CREATE OR REPLACE PACKAGE BODY MY_PACK AS
    function runPipe(id number) RETURN result_table PIPELINED IS
    rec           result_record:=null;
    begin
       if  (id=1) then
         select 'Smih','139289289','Paris' into rec from dual;
       end if;
       if  (id=2) then
         select 'Lock','1888888888','London' into rec from dual;
       end if;
       if  (id=3) then
         select 'May','99999999999','Berlin' into rec from dual;
       end if;
       pipe row (rec);
       return;
  end;
END ERC_PACK;
/

And of course the

select * from table(MY_PACK.runPipe(1))

returns

Smih    139289289   Paris

Now I would like a select statement that will return all the rows of the test_data  along with the corresponding values from pipeline function

e.g. something like

select test_data.*, (select * from table(MY_PACK.runPipe(id))) from test_data

which of course doses not work
but the expected results would be something like:

1 John  Smih    139289289   Paris
2 Jack  Lock    1888888888  London
3 Peter May     99999999999 Berlin

So how to achieve the above expected result, given the test_data table and the pipelined function?

Body:
try this select :

    with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)
select td.*, s.*
from test_data td
LEFT JOIN  table(MY_PACK.runPipe(td.id)) s ON 1 = 1;


问:
Disabled Select dropdown not showing option value in Reactive Forms Angular 4 Application
I have a very simple Dropdown in a Angular Form which is loading only one option where object name coming through rest service.

I also want to disable the dropdown based on some condition. I know I can't use [disabled] property on HTML elements in reactive forms. So I am stuck with two options.
Either using [attr.disabled] or custom directive.

But both options not showing option value in disabled dropdown. Here is the code.

```<code><select class="custom-select"
     name="objectName"
     id="objectName"
     formControlName="objectNameDropDown"
     [attr.disabled]="conditionTrue ? 'disabled': null"
     *ngIf="!someCondition; else loadDifferentDropdown;">
       <option>{{object.name}}</option>
</select>
</code>```

I tried to use ngModel too but I think it is not needed. I also used custom Directive in place of [attr.disabled] but it is producing same result. Dropdown is disabled and empty. Option value is there but it is not coming as selected.

Note:- Above code is working fine if I place this dropdown out of angular form and use [disabled]="someCondition"

Any idea what I am doing wrong here?

答:
If you using reactive form, you have to disable it from formbuilder itself as below example</p>

```<code>this.yourForm = this.formBuilder.group({
    objectNameDropDown: [{value:"", disabled: true}],
});
</code>```

Body:
I have a very simple Dropdown in a Angular Form which is loading only one option where object name coming through rest service.

I also want to disable the dropdown based on some condition. I know I can't use [disabled] property on HTML elements in reactive forms. So I am stuck with two options.
Either using [attr.disabled] or custom directive.

But both options not showing option value in disabled dropdown. Here is the code.

<select class="custom-select"
     name="objectName"
     id="objectName"
     formControlName="objectNameDropDown"
     [attr.disabled]="conditionTrue ? 'disabled': null"
     *ngIf="!someCondition; else loadDifferentDropdown;">
       <option>{{object.name}}</option>
</select>

I tried to use ngModel too but I think it is not needed. I also used custom Directive in place of [attr.disabled] but it is producing same result. Dropdown is disabled and empty. Option value is there but it is not coming as selected.

Note:- Above code is working fine if I place this dropdown out of angular form and use [disabled]="someCondition"

Any idea what I am doing wrong here?

Body:
If you using reactive form, you have to disable it from formbuilder itself as below example

this.yourForm = this.formBuilder.group({
    objectNameDropDown: [{value:"", disabled: true}],
});


问:
C# rounding differently depending on platform?
I have this tiny piece of code

```<code>double s = -2.6114289999999998;
double s7 = Math.Round(s, 7);
double s5 = Math.Round(s, 5);
double s6 = Math.Round(s, 6);
</code>```

With Platform = Any CPU, I get

```<code>s7: -2.611429
s5: -2.61143
s6: -2.611429
</code>```

With Platform = x64, I get

```<code>s7: -2.6114289999999998
s5: -2.61143
s6: -2.6114289999999998
</code>```

Why? (Output copied from VS's Locals window)

The whole piece of code is:

```<code>    private void btnAlign_Click(object sender, EventArgs e)
    {
        double s = -2.6114289999999998;
        double s7 = Math.Round(s, 7);
        double s5 = Math.Round(s, 5);
        double s6 = Math.Round(s, 6);
    }
</code>```

答: The value -2.611429 cannot be represented using 64-bit floating point. When compiling in 32-bit mode the value will instead use 80-bit (extended precision).

Body:
I have this tiny piece of code

double s = -2.6114289999999998;
double s7 = Math.Round(s, 7);
double s5 = Math.Round(s, 5);
double s6 = Math.Round(s, 6);

With Platform = Any CPU, I get

s7: -2.611429
s5: -2.61143
s6: -2.611429

With Platform = x64, I get

s7: -2.6114289999999998
s5: -2.61143
s6: -2.6114289999999998

Why? (Output copied from VS's Locals window)

The whole piece of code is:

    private void btnAlign_Click(object sender, EventArgs e)
    {
        double s = -2.6114289999999998;
        double s7 = Math.Round(s, 7);
        double s5 = Math.Round(s, 5);
        double s6 = Math.Round(s, 6);
    }


问:
How do I create arrays within an array in C without a predefined size?
I would like to create arrays within an array in C without a pre-defined number of characters or input in the array.
The following is my code:

```<code>{
    int noOfStudents,noOfItems;
    int *grades;
    int i;
    char a[];
    printf("Please enter number of students\n");
    scanf("%d", &noOfStudents);
    printf("Please enter number of items\n");
    scanf("%d", &noOfItems);

    for (i = 0; i < noOfStudents; i++)
    {
        a[i] = (int *)malloc((sizeof(int))*noOfItems);
    }
</code>```

I've been thrown an error

c(2133): 'a': unknown size

How do I successfully create arrays within an array by means of malloc?

答:
You can make use of a VLA (Variable length array).

You need to rearrange your code like

```<code>int noOfStudents = -1, noOfItems = -1;
int *grades;                                //is it used?
int i;

printf("Please enter number of students\n");
scanf("%d", &noOfStudents);

//fail check

int *a[noOfStudents];             // this needs to be proper.

//VLA

printf("Please enter number of items\n");
scanf("%d", &noOfItems);

//fail check

for (i = 0; i < noOfStudents; i++)
{
    a[i] = malloc(noOfItems * sizeof(a[i]));   //do not cast
}
</code>```

Body:
I would like to create arrays within an array in C without a pre-defined number of characters or input in the array.
The following is my code:

{
    int noOfStudents,noOfItems;
    int *grades;
    int i;
    char a[];
    printf("Please enter number of students\n");
    scanf("%d", &noOfStudents);
    printf("Please enter number of items\n");
    scanf("%d", &noOfItems);

    for (i = 0; i < noOfStudents; i++)
    {
        a[i] = (int *)malloc((sizeof(int))*noOfItems);
    }

I've been thrown an error

c(2133): 'a': unknown size

How do I successfully create arrays within an array by means of malloc?

Body:
You can make use of a VLA (Variable length array).

You need to rearrange your code like

int noOfStudents = -1, noOfItems = -1;
int *grades;                                //is it used?
int i;

printf("Please enter number of students\n");
scanf("%d", &noOfStudents);

//fail check

int *a[noOfStudents];             // this needs to be proper.

//VLA

printf("Please enter number of items\n");
scanf("%d", &noOfItems);

//fail check

for (i = 0; i < noOfStudents; i++)
{
    a[i] = malloc(noOfItems * sizeof(a[i]));   //do not cast
}


问:
IIS Server 403.7 error not recognizing Client Certificate for ASP.NET app
I am attempting to perform mutual authentication between 2 systems but server keeps returning 403.7 even though the client is possessing the correct certificate. I have done some diagnosis and it seems that although the app is processing the certificate, it is some how being "discarded" somewhere (when using a wrong cert, it doesnt return 403.16 but 403.7).

Some background below

Server - ASP.NET Webservice on IIS, WSDL accessible for SOAP calls. Has 2 root certs, one for server name, other for authenticating client certificates. Certs are all self-signed for local area testing.

Client - ASP.NET application on IIS with SOAP calls to server. Issued client certificate from server and has both root certs installed as Trusted CAs. Accesses a dll to perform SOAP calls specifically for the server. Client cert is a X509Certificate2 and client access it via file (Not cert store).

The client is actually a server for another web application and there needs to be an interface between client and server. Client and server will be on different networks and mutual authentication via SSL certificates are required. Connection between both systems are TLS1.2

Diagnosis performed thus far

Client able to compile the same dll and run as a console app, picks up the correct client cert and authenticate successfully with server (Proves code is working). When deliberately selecting the wrong cert, 403.16 is returned (Correct behavior)

Client browser able to access server page and authenticate with correct client cert (Proves cert is working)

Client web app using the dll file is able to access and process the correct cert (proves that web app is able to access cert). When deliberately selecting the wrong cert, 403.7 is still returned and not 403.16. (Where is my cert going?)

Wireshark indicates that both sides are talking but i am unable to get wireshark to perform decryption to provide more in-depth details (Working on this)

The Problem

As per the title, server keeps returning 403.7 (via IIS Failed-Request-Tracing) even though the client web application is able to access the file. Since the client is a web app running on IIS and interfacing with server, i would assume that the client IIS service is handling these web requests.

I am suspecting that it has something to do with either

client IIS accounts and/or its rights

Some funky windows/TLS/SSL protocol i am not aware off

IIS settings?

Appreciate some insight on how to debug further or address this issue?

答:
Well after going 1 big round to test and troubleshoot via wireshark, it seems that the application couldnt access the private key because there was none to begin with. Quick change from .cer to .pfx with the private key quickly fixed that.

However it still doesnt explain why the console application could access the server with a .cer instead of a .pfx (no private key, could be something to do with IIS but i am just making an assumption. )

A similiar case occured with another development application however they were using a .pfx file with the private key. Further debugging indicates that they were using X509Certificate instead of X509Certificate2. Well the issue for this case is due to the fact that they couldnt not access the private key with the older class.

In summary,
- Ensure private key is present for the application to access in order to properly present the correct certificate or else no certificate will be presented at all.


问:
jQuery AJAX with text and file input in one call
How do you pass both text input as well as a file in one jQuery AJAX call?
The code I have below passes the text input fields well but the file input returns an error (see below).

```<code>var formData = new FormData();

    formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val()
    };

    formData.append('profile_pic', $('input[id="profile_pic"]')[0].files[0]);

    // process the form
    $.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })
</code>```

On trying to receive the request on the PHP end like this:

```<code>$target_dir = "image_uploads/";
$target_file = $target_dir .rand(1,999). basename(str_replace(" ","",$_FILES["profile_pic"]["name"]));
</code>```

I get the following error:

Undefined index: profile_pic

I have checked out a couple of solutions here on Stack Overflow already but none has done the trick for me yet.

How can I resolve this?

答:
Just bind submit listener for your form and pass form data to your ajax automatically like below:</p>

```<code>$('#form').submit(function(e){
    e.preventDefault();
    var formData = new FormData(this);

    $.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        processData : false,
        contentType : false,
        encode      : true
    })

})
</code>```

Body:
How do you pass both text input as well as a file in one jQuery AJAX call?
The code I have below passes the text input fields well but the file input returns an error (see below).

var formData = new FormData();

    formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val()
    };

    formData.append('profile_pic', $('input[id="profile_pic"]')[0].files[0]);

    // process the form
    $.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })

On trying to receive the request on the PHP end like this:

$target_dir = "image_uploads/";
$target_file = $target_dir .rand(1,999). basename(str_replace(" ","",$_FILES["profile_pic"]["name"]));

I get the following error:

Undefined index: profile_pic

I have checked out a couple of solutions here on Stack Overflow already but none has done the trick for me yet.

How can I resolve this?

Body:
Just bind submit listener for your form and pass form data to your ajax automatically like below:

$('#form').submit(function(e){
    e.preventDefault();
    var formData = new FormData(this);

    $.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        processData : false,
        contentType : false,
        encode      : true
    })

})


问:
Why a struct declared by let can be changed?
In the following code, 'ptr' is a struct declared by let, but its member variable 'pointee' could be changed, Why?

    let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
    ptr.pointee = 1

答:
UnsafeMutablePointer is a struct, but it declares

```<code>public struct UnsafeMutablePointer<Pointee> : Strideable, Hashable {

    public var pointee: Pointee { get nonmutating set }
    public subscript(i: Int) -> Pointee { get nonmutating set }

}
</code>```

Here "nonmutating set" means that setting the property does not mutate
the state of the pointer variable itself.

Therefore ptr.pointee can be assigned a new value even if ptr
is a constant, and the same is true for the subscript setter:

```<code>let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
ptr.pointee = 1
ptr[0] = 2
</code>```

Body:
UnsafeMutablePointer is a struct, but it declares

public struct UnsafeMutablePointer<Pointee> : Strideable, Hashable {

    public var pointee: Pointee { get nonmutating set }
    public subscript(i: Int) -> Pointee { get nonmutating set }

}

Here "nonmutating set" means that setting the property does not mutate
the state of the pointer variable itself.

Therefore ptr.pointee can be assigned a new value even if ptr
is a constant, and the same is true for the subscript setter:

let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
ptr.pointee = 1
ptr[0] = 2


问:
While executing the below code getting an error bad geometry specifier in python
While trying the below code:

```<code>import tkinter

print(tkinter.TkVersion)

print(tkinter.TclVersion)

mainWindow = tkinter.Tk()

mainWindow.title("Hello Python")

mainWindow.geometry("1200X1024")

mainWindow.mainloop()
</code>```

I am getting an error:

```<code> Traceback (most recent call last):
   File "C:\Users\Satya\IdeaProjects\GUO_python\tkinter1.py", line 11, in <module>
     mainWindow.geometry("1200X1024")
   File "C:\Users\Satya\Anaconda3\lib\tkinter\__init__.py", line 1835, in wm_geometry
     return self.tk.call('wm', 'geometry', self._w, newGeometry)
 _tkinter.TclError: bad geometry specifier "1200X1024"
</code>```

https://i.stack.imgur.com/EJyn6.jpg

答:
You can use also add "+" to specify where you want your window to position on your screen

("1200x1024+100+10")

```<code>import tkinter

print(tkinter.TkVersion)

print(tkinter.TclVersion)

mainWindow = tkinter.Tk()

mainWindow.title("Hello Python")

mainWindow.geometry("1200x1024") # use "x" instead of " X"

mainWindow.mainloop()
</code>```

Body:
While trying the below code:

import tkinter

print(tkinter.TkVersion)

print(tkinter.TclVersion)

mainWindow = tkinter.Tk()

mainWindow.title("Hello Python")

mainWindow.geometry("1200X1024")

mainWindow.mainloop()

I am getting an error:

 Traceback (most recent call last):
   File "C:\Users\Satya\IdeaProjects\GUO_python\tkinter1.py", line 11, in <module>
     mainWindow.geometry("1200X1024")
   File "C:\Users\Satya\Anaconda3\lib\tkinter\__init__.py", line 1835, in wm_geometry
     return self.tk.call('wm', 'geometry', self._w, newGeometry)
 _tkinter.TclError: bad geometry specifier "1200X1024"

https://i.stack.imgur.com/EJyn6.jpg

Body:
You can use also add "+" to specify where you want your window to position on your screen

("1200x1024+100+10")

import tkinter

print(tkinter.TkVersion)

print(tkinter.TclVersion)

mainWindow = tkinter.Tk()

mainWindow.title("Hello Python")

mainWindow.geometry("1200x1024") # use "x" instead of " X"

mainWindow.mainloop()


答:
You want a bi-dimensional array, to hold the list of lists of integer items. You can do that by declaring a pointer on integer pointers.

So you want to declare

```<code>int **a;
</code>```

then

```<code>printf("Please enter number of students\n");
if (scanf("%d", &noOfStudents)==0 && noOfStudents<=0)  // bonus: small safety
{
    printf("input error\n");
    exit(1);
}
// now we are sure that noOfStudents is strictly positive & properly entered
a = malloc(sizeof(int*)*noOfStudents);
</code>```

Then you have your array of pointers allocated, and the rest of your code is OK (don't cast the return value of malloc BTW)

A variant is:

```<code>a = malloc(sizeof(*a)*noOfStudents);
</code>```

(so if type of a changes, the size follows, not that it matters here since they're all pointers)

Title: How do I create arrays within an array in C without a predefined size?

Body:
You want a bi-dimensional array, to hold the list of lists of integer items. You can do that by declaring a pointer on integer pointers.

So you want to declare

int **a;

then

printf("Please enter number of students\n");
if (scanf("%d", &noOfStudents)==0 && noOfStudents<=0)  // bonus: small safety
{
    printf("input error\n");
    exit(1);
}
// now we are sure that noOfStudents is strictly positive & properly entered
a = malloc(sizeof(int*)*noOfStudents);

Then you have your array of pointers allocated, and the rest of your code is OK (don't cast the return value of malloc BTW)

A variant is:

a = malloc(sizeof(*a)*noOfStudents);

(so if type of a changes, the size follows, not that it matters here since they're all pointers)


问:
HTML Input - Remove leading Character
I have an HTML form showing a table where the user can scan a product barcode to enter the serial number into a text input field like this:

```<code><td id="9856623"><input type="text" class="form-control serialNumber" placeholder="Serial #" name="serialNumber" autocomplete="off" value=""></td>
</code>```

When the cursor is in the input field the user scans a barcode to insert the barcode value into this input field, which then triggers a script that runs in the background to do a database update via PHP. We need to check if the first characters in the serial number that is scanned is an 'S' and if so then remove this. We handle this in PHP like this:

```<code>$serialNumber = 'STRQWEF412421';

$serialFirstChar = substr( $serialNumber , 0, 1);

if ($serialFirstChar == 'S') {
    $serialNumber = substr($serialNumber, 1);
}
</code>```

but I now need to do the same in Javascript to update the entered serial number in the text input field so also remove the leading 'S' character if present. Here's the current script that runs when the Serial Number is entered:

```<code>$(document).ready(function() {
  $(".form-control.serialNumber").change(function() {
    //$("input[type='text']").change(function(){
    //alert( "Handler for .change() called." );
    var parent = $(this).parents('tr');
    var recid = $(this).closest('td').attr('id');
    var serialNumber = $(this).val();
    // Create a reference to $(this) here:
    $this = $(this);
    $.post('updateAsset.php', {
      type: 'updateDatabase',
      recid: recid,
      serialNumber: serialNumber
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Serial Number - ' + ajaxError + '. Please contact the Helpdesk';
        $this.closest('td').addClass("has-error");
        //display AJAX error details
        $("#serialNumberErrorMessage").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        var dateReceived = (data.dateReceived);
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
        $this.closest('tr').children('.DateReceived').html(dateReceived);
        // if you want to show a success alert enable the following
        // $("#ajaxAlert").addClass("alert alert-success").html(data.text);
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Serial Number - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Helpdesk';
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberErrorMessage").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});
</code>```

```

I have no idea how to go about this at this point, and whether I can update my existing script to also update the entered serial number and remove any leading 'S' character?

答:
if cropping first letter is what u want then this can help; </p>

```<code>let stringFromScanner = "ScannedString";
if(stringFromScanner.substr(0,1) == "S" || stringFromScanner.substr(0,1) == "s") {
   stringFromScanner.slice(1,stringFromScanner.length);
}
</code>```

Title: HTML Input - Remove leading Character

Body:
I have an HTML form showing a table where the user can scan a product barcode to enter the serial number into a text input field like this:

<input type="text" class="form-control serialNumber" placeholder="Serial #" name="serialNumber" autocomplete="off" value="">

When the cursor is in the input field the user scans a barcode to insert the barcode value into this input field, which then triggers a script that runs in the background to do a database update via PHP. We need to check if the first characters in the serial number that is scanned is an 'S' and if so then remove this. We handle this in PHP like this:

$serialNumber = 'STRQWEF412421';

$serialFirstChar = substr( $serialNumber , 0, 1);

if ($serialFirstChar == 'S') {
    $serialNumber = substr($serialNumber, 1);
}

but I now need to do the same in Javascript to update the entered serial number in the text input field so also remove the leading 'S' character if present. Here's the current script that runs when the Serial Number is entered:

$(document).ready(function() {
  $(".form-control.serialNumber").change(function() {
    //$("input[type='text']").change(function(){
    //alert( "Handler for .change() called." );
    var parent = $(this).parents('tr');
    var recid = $(this).closest('td').attr('id');
    var serialNumber = $(this).val();
    // Create a reference to $(this) here:
    $this = $(this);
    $.post('updateAsset.php', {
      type: 'updateDatabase',
      recid: recid,
      serialNumber: serialNumber
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Serial Number - ' + ajaxError + '. Please contact the Helpdesk';
        $this.closest('td').addClass("has-error");
        //display AJAX error details
        $("#serialNumberErrorMessage").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        var dateReceived = (data.dateReceived);
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
        $this.closest('tr').children('.DateReceived').html(dateReceived);
        // if you want to show a success alert enable the following
        // $("#ajaxAlert").addClass("alert alert-success").html(data.text);
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Serial Number - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Helpdesk';
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberErrorMessage").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});

I have no idea how to go about this at this point, and whether I can update my existing script to also update the entered serial number and remove any leading 'S' character?

Body:
if cropping first letter is what u want then this can help;

let stringFromScanner = "ScannedString";
if(stringFromScanner.substr(0,1) == "S" || stringFromScanner.substr(0,1) == "s") {
   stringFromScanner.slice(1,stringFromScanner.length);
}


问:
Google Sheets Filter Function if no value multiple columns
I want to pull all relevant data from Data!F:G on this sheet:
https://docs.google.com/spreadsheets/d/18hJW4ojAbe1dUF1lDdSOI11cTEaMeJ6N-VZ6BB7LrAY/edit#gid=1162973857

I am assuming it's a filter function but want to ensure that all data is pulled if the fields in Dashboard!C1:C5 are empty.

=filter(Data!F:G,
         Data!A:A = C1,
         Data!B:B = C2,
         Data!C:C = C3,
         Data!D:D = C4,
         Data!E:E = C5)

works when all fields are complete but not if one of them is empty.

Thank you!

答:
See if this works</p>

```<code>=iferror(query(Data!A:G, "select F, G where F is not null" &IF(len(C1), " and A = '"&C1&"'",)&IF(len(C2), " and B = '"&C2&"'",)&IF(len(C3), " and C = '"&C3&"'",)&IF(len(C4), " and D = '"&C4&"'",)&IF(len(C5), " and E = '"&C5&"'",),0), "no matches found")
</code>```

Body:
See if this works

=iferror(query(Data!A:G, "select F, G where F is not null" &IF(len(C1), " and A = '"&C1&"'",)&IF(len(C2), " and B = '"&C2&"'",)&IF(len(C3), " and C = '"&C3&"'",)&IF(len(C4), " and D = '"&C4&"'",)&IF(len(C5), " and E = '"&C5&"'",),0), "no matches found")


问:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 321-322: ordinal not in range(128)
I am trying to join column values in xlsx file using pandas. I am using the below code to that.

```<code>(df.astype(str).groupby('name', as_index=False, sort=False)
             .apply(lambda x: pd.Series({v: ','.join(x[v].unique()) for v in x})))
</code>```

But, I am getting error like

```<code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 321-322: ordinal not in range(128)
</code>```

答: If you only need string for your DataFrame, you can use the option dtype = unicode in your read_excel function and remove the astype(str).

Body:
I am trying to join column values in xlsx file using pandas. I am using the below code to that.

(df.astype(str).groupby('name', as_index=False, sort=False)
             .apply(lambda x: pd.Series({v: ','.join(x[v].unique()) for v in x})))

But, I am getting error like

UnicodeEncodeError: 'ascii' codec can't encode characters in position 321-322: ordinal not in range(128)


问:
Go array initialization
```<code>func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}
</code>```

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?

答:
If you were writing your program using Go idioms, you would be using slices. For example,</p>

```<code>package main

import "fmt"

func Identity(n int) []float {
    m := make([]float, n*n)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            if i == j {
                m[i*n+j] = 1.0
            }
        }
    }
    return m
}

func main() {
    fmt.Println(Identity(4))
}

Output: [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1]
</code>```

Title: Go array initialization

Body:
func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?

Body:
If you were writing your program using Go idioms, you would be using slices. For example,

package main

import "fmt"

func Identity(n int) []float {
    m := make([]float, n*n)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            if i == j {
                m[i*n+j] = 1.0
            }
        }
    }
    return m
}

func main() {
    fmt.Println(Identity(4))
}

Output: [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1]