问:
UIImageView perspective tilt
What I want: https://imgur.com/zE6kgb1

What I have achieved: https://imgur.com/8Ylq5yp

Below is the function I am using:

```<code>- (void) showViewWithImageFromAsset: (PHAsset *) asset
 {
     UIView *imageContainer = [[UIView alloc] initWithFrame:CGRectMake(25, 320, 400, 400)];
     [imageContainer setBackgroundColor:[UIColor whiteColor]];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 250, 200)];

     CGFloat shadowRadius = 0.0;
     CGFloat width = imageView.frame.size.width;
     CGFloat height = imageView.frame.size.height; // Get width and height of the view

// Plot the path
UIBezierPath *shadowPath = [[UIBezierPath alloc] init];
[shadowPath moveToPoint:CGPointMake(width, 0)];
[shadowPath addLineToPoint:CGPointMake((width)+10, 10)];
[shadowPath addLineToPoint:CGPointMake((width)+10, height-10)];
[shadowPath addLineToPoint:CGPointMake(width, height)];

imageView.layer.shadowColor = UIColor.blackColor.CGColor;
imageView.layer.shadowPath = shadowPath.CGPath;
imageView.layer.shadowRadius = shadowRadius;
imageView.layer.shadowOffset = CGSizeZero;
imageView.layer.shadowOpacity = 1.0;

PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = YES;

PHImageManager *manager = [PHImageManager defaultManager];

// assets contains PHAsset objects.
__block UIImage *ima;

[manager requestImageForAsset:asset
                   targetSize:PHImageManagerMaximumSize
                  contentMode:PHImageContentModeDefault
                      options:requestOptions
                resultHandler:^void(UIImage *image, NSDictionary *info) {
                    ima = image;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [imageView setImage:ima];

                        CATransform3D t = CATransform3DIdentity;
                        t.m34 = .005;
                        imageContainer.layer.sublayerTransform = t;
                        imageView.layer.transform = CATransform3DMakeRotation(-10,0,1,0);
                        [imageContainer addSubview:imageView];
                        //[imageContainer addSubview:imageSideView];
                        [self.view addSubview:imageContainer];
                        [self.view bringSubviewToFront:imageView];
                    });

                }];

}
</code>```

As you can see, I have achieved the desired effect albeit with an inverted (or mirrored) image. I do not intend to use any third party framework/library to achieve this since I know it is possible by modifying the existing code.

While I can change the y value in CATransform3DMakeRotation(-10,0,1,0), from 1 to 0 to get the correct image orientation, that will aslo change the perspective to this https://imgur.com/yKL4NQA

I need something to get the right image without changing the perspective. Any help is greatly appreciated.

答:
The biggest issue is that the first argument to CATransform3DMakeRotation needs to be radians, not degrees.

```<code>imageView.layer.transform = CATransform3DMakeRotation(-10 * M_PI / 180.0, 0, 1, 0);
</code>```

Then you need to change the x of the shadowPath:

```<code>[shadowPath moveToPoint:CGPointMake(0, 0)];
[shadowPath addLineToPoint:CGPointMake(-10, 10)];
[shadowPath addLineToPoint:CGPointMake(-10, height-10)];
[shadowPath addLineToPoint:CGPointMake(0, height)];
</code>```

This gives the desired result.

Title: UIImageView perspective tilt

Body:
What I want: https://imgur.com/zE6kgb1

What I have achieved: https://imgur.com/8Ylq5yp

Below is the function I am using:

- (void) showViewWithImageFromAsset: (PHAsset *) asset
 {
     UIView *imageContainer = [[UIView alloc] initWithFrame:CGRectMake(25, 320, 400, 400)];
     [imageContainer setBackgroundColor:[UIColor whiteColor]];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 250, 200)];

     CGFloat shadowRadius = 0.0;
     CGFloat width = imageView.frame.size.width;
     CGFloat height = imageView.frame.size.height; // Get width and height of the view

// Plot the path
UIBezierPath *shadowPath = [[UIBezierPath alloc] init];
[shadowPath moveToPoint:CGPointMake(width, 0)];
[shadowPath addLineToPoint:CGPointMake((width)+10, 10)];
[shadowPath addLineToPoint:CGPointMake((width)+10, height-10)];
[shadowPath addLineToPoint:CGPointMake(width, height)];

imageView.layer.shadowColor = UIColor.blackColor.CGColor;
imageView.layer.shadowPath = shadowPath.CGPath;
imageView.layer.shadowRadius = shadowRadius;
imageView.layer.shadowOffset = CGSizeZero;
imageView.layer.shadowOpacity = 1.0;

PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = YES;

PHImageManager *manager = [PHImageManager defaultManager];

// assets contains PHAsset objects.
__block UIImage *ima;

[manager requestImageForAsset:asset
                   targetSize:PHImageManagerMaximumSize
                  contentMode:PHImageContentModeDefault
                      options:requestOptions
                resultHandler:^void(UIImage *image, NSDictionary *info) {
                    ima = image;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [imageView setImage:ima];

                        CATransform3D t = CATransform3DIdentity;
                        t.m34 = .005;
                        imageContainer.layer.sublayerTransform = t;
                        imageView.layer.transform = CATransform3DMakeRotation(-10,0,1,0);
                        [imageContainer addSubview:imageView];
                        //[imageContainer addSubview:imageSideView];
                        [self.view addSubview:imageContainer];
                        [self.view bringSubviewToFront:imageView];
                    });

                }];

}

As you can see, I have achieved the desired effect albeit with an inverted (or mirrored) image. I do not intend to use any third party framework/library to achieve this since I know it is possible by modifying the existing code.

While I can change the y value in CATransform3DMakeRotation(-10,0,1,0), from 1 to 0 to get the correct image orientation, that will aslo change the perspective to this https://imgur.com/yKL4NQA

I need something to get the right image without changing the perspective. Any help is greatly appreciated.

Body:
The biggest issue is that the first argument to CATransform3DMakeRotation needs to be radians, not degrees.

imageView.layer.transform = CATransform3DMakeRotation(-10 * M_PI / 180.0, 0, 1, 0);

Then you need to change the x of the shadowPath:

[shadowPath moveToPoint:CGPointMake(0, 0)];
[shadowPath addLineToPoint:CGPointMake(-10, 10)];
[shadowPath addLineToPoint:CGPointMake(-10, height-10)];
[shadowPath addLineToPoint:CGPointMake(0, height)];

This gives the desired result.


来源: stackexchange

问:
Why isn't pandas logical operator aligning on the index like it should?
Consider this simple setup:

```<code>x = pd.Series([1, 2, 3], index=list('abc'))
y = pd.Series([2, 3, 3], index=list('bca'))

x

a    1
b    2
c    3
dtype: int64

y

b    2
c    3
a    3
dtype: int64
</code>```

As you can see, the indexes are the same, just in a different order.

Now, consider a simple logical comparison using the equality (==) operator:

```<code>x == y
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
</code>```

This throws a ValueError, most likely because the indexes do not match. On the other hand, calling the equivalent eq operator works:

```<code>x.eq(y)

a    False
b     True
c     True
dtype: bool
</code>```

OTOH, the operator method works given y is first reordered...

```<code>x == y.reindex_like(x)

a    False
b     True
c     True
dtype: bool
</code>```

My understanding was that the function and operator comparison should do the same thing, all other things equal. What is eq doing that the operator comparison doesn't?

答:
One thing I love about python is that you can peak into source code of almost anything. And from pd.Series.eq source code, it calls:

```<code>def flex_wrapper(self, other, level=None, fill_value=None, axis=0):
    # other stuff
    # ...

    if isinstance(other, ABCSeries):
        return self._binop(other, op, level=level, fill_value=fill_value)
</code>```

and go on to pd.Series._binop:

```<code>def _binop(self, other, func, level=None, fill_value=None):

    # other stuff
    # ...
    if not self.index.equals(other.index):
        this, other = self.align(other, level=level, join='outer',
                                 copy=False)
        new_index = this.index
</code>```

That means the eq operator aligns the two series before comparison (which, apparently, the normal operator == does not).

ContentLicense: CC BY-SA 4.0

Body:
Consider this simple setup:

x = pd.Series([1, 2, 3], index=list('abc'))
y = pd.Series([2, 3, 3], index=list('bca'))

x

a    1
b    2
c    3
dtype: int64

y

b    2
c    3
a    3
dtype: int64

As you can see, the indexes are the same, just in a different order.

Now, consider a simple logical comparison using the equality (==) operator:

x == y
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

This throws a ValueError, most likely because the indexes do not match. On the other hand, calling the equivalent eq operator works:

x.eq(y)

a    False
b     True
c     True
dtype: bool

OTOH, the operator method works given y is first reordered...

x == y.reindex_like(x)

a    False
b     True
c     True
dtype: bool

My understanding was that the function and operator comparison should do the same thing, all other things equal. What is eq doing that the operator comparison doesn't?

Body:
One thing I love about python is that you can peak into source code of almost anything. And from pd.Series.eq source code, it calls:

def flex_wrapper(self, other, level=None, fill_value=None, axis=0):
    # other stuff
    # ...

    if isinstance(other, ABCSeries):
        return self._binop(other, op, level=level, fill_value=fill_value)

and go on to pd.Series._binop:

def _binop(self, other, func, level=None, fill_value=None):

    # other stuff
    # ...
    if not self.index.equals(other.index):
        this, other = self.align(other, level=level, join='outer',
                                 copy=False)
        new_index = this.index

That means the eq operator aligns the two series before comparison (which, apparently, the normal operator == does not).


问:
VueJS and tinyMCE, custom directives
I've been struggling hard with getting VueJS and TinyMCE to work together. I've come to the conclusion that using directives would be the way to go.

So far I've been able to pass in the body as a directive parameter, and tinyMCE sets the content. However, I can't get the two way binding to work. I'm also afraid that I'm doing things completely wrong based on the tinyMCE api.

The relevant tinyMCE functions I assume would be:

http://community.tinymce.com/wiki.php/api4:method.tinymce.Editor.setContent

```<code>// Sets the content of a specific editor (my_editor in this example)
tinymce.get('my_editor').setContent(data);
</code>```

and

http://community.tinymce.com/wiki.php/api4:method.tinymce.Editor.getContent

```<code>// Get content of a specific editor:
tinymce.get('content id').getContent()
</code>```

HTML

```<code><div id="app">
  <h3>This is the tinyMCE editor</h3>
  <textarea id="editor" v-editor :body="body"></textarea>

  <hr>
  <p>This input field is properly binded</p>
  <input v-model="body">

  <hr>
  ```data binding: {{ body }} ```
</div>
</code>```

JS

```<code>tinymce.init({
    selector:'#editor',
});

Vue.directive('editor', {
    twoWay: true,
    params: ['body'],

    bind: function () {
        tinyMCE.get('editor').setContent(this.params.body);
        tinyMCE.get('editor').on('change', function(e) {
            alert("changed");
        });
    },
    update: function (value) {
        $(this.el).val(value).trigger('change')
    },
});

var editor = new Vue({
    el: '#app',
    data: {
        body: 'The message'
    }
})
</code>```

Fiddle

https://jsfiddle.net/nf3ftm8f/

答:
There is now an npm package which is a thin wrapper around TinyMCE, making it easier to use in a Vue application.

It is open source with code on GitHub.

Installation:

```<code>$ npm install @tinymce/tinymce-vue
</code>```

Usage:

```<code> import Editor from '@tinymce/tinyme-vue';
</code>```

Templates:

```<code><editor api-key="API_KEY" :init="{plugins: 'wordcount'}"></editor>
</code>```

Where API_KEY is your API key from tiny.  The init section is the same as the default init statement except you do not need the selector.  For an example see the documentation.

ContentLicense: CC BY-SA 3.0

Title: VueJS and tinyMCE, custom directives

Body:
I've been struggling hard with getting VueJS and TinyMCE to work together. I've come to the conclusion that using directives would be the way to go.

So far I've been able to pass in the body as a directive parameter, and tinyMCE sets the content. However, I can't get the two way binding to work. I'm also afraid that I'm doing things completely wrong based on the tinyMCE api.

The relevant tinyMCE functions I assume would be:

http://community.tinymce.com/wiki.php/api4:method.tinymce.Editor.setContent

// Sets the content of a specific editor (my_editor in this example)
tinymce.get('my_editor').setContent(data);

and

http://community.tinymce.com/wiki.php/api4:method.tinymce.Editor.getContent

// Get content of a specific editor:
tinymce.get('content id').getContent()

HTML

This is the tinyMCE editor

  <textarea id="editor" v-editor :body="body"></textarea>

This input field is properly binded

  <input v-model="body">

data binding: {{ body }}

JS

tinymce.init({
    selector:'#editor',
});

Vue.directive('editor', {
    twoWay: true,
    params: ['body'],

    bind: function () {
        tinyMCE.get('editor').setContent(this.params.body);
        tinyMCE.get('editor').on('change', function(e) {
            alert("changed");
        });
    },
    update: function (value) {
        $(this.el).val(value).trigger('change')
    },
});

var editor = new Vue({
    el: '#app',
    data: {
        body: 'The message'
    }
})

Fiddle

https://jsfiddle.net/nf3ftm8f/

Body:
There is now an npm package which is a thin wrapper around TinyMCE, making it easier to use in a Vue application.

It is open source with code on GitHub.

Installation:

$ npm install @tinymce/tinymce-vue

Usage:

 import Editor from '@tinymce/tinyme-vue';

Templates:

<editor api-key="API_KEY" :init="{plugins: 'wordcount'}"></editor>

Where API_KEY is your API key from tiny.  The init section is the same as the default init statement except you do not need the selector.  For an example see the documentation.


问:
How to save the dictionary that have tuple keys
I would like to save the dictionary having tuple on keys.

I tried pickle, ujson, json to save the dictionary. All of them did not work.

The dictionary has:

```<code>dictionary = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}
</code>```

I tried:

```<code>with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(dictionary)

import json
a, b, c = "abc"
data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
on_disk = json.dumps(data.items())
</code>```

答:
You should use ujson, this is appropriate to address what you want. I just tried it and it works properly. If you use json you will get the following error:

TypeError: keys must be str, int, float, bool or None, not tuple

```<code>import ujson

d = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

# save dictionary
with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(d))
</code>```

Make sure you installed ujson since it is not part of the Python standard library:

```<code>pip install ujson
</code>```

Body:
I would like to save the dictionary having tuple on keys.

I tried pickle, ujson, json to save the dictionary. All of them did not work.

The dictionary has:

dictionary = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

I tried:

with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(dictionary)

import json
a, b, c = "abc"
data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
on_disk = json.dumps(data.items())

Body:
You should use ujson, this is appropriate to address what you want. I just tried it and it works properly. If you use json you will get the following error:

TypeError: keys must be str, int, float, bool or None, not tuple

import ujson

d = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

# save dictionary
with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(d))

Make sure you installed ujson since it is not part of the Python standard library:

pip install ujson


问:
The best way to run npm install for nested folders?
What is the most correct way to install npm packages in nested sub folders?

```<code>my-app
  /my-sub-module
  package.json
package.json
</code>```

What is the best way to have packages in /my-sub-module be installed automatically when npm install run in my-app?

答:
Inspired by the scripts provided here, I built a configurable example which:

can be setup to use yarn or npm

can be setup to determine the command to use based on lock files so that if you set it to use yarn but a directory only has a package-lock.json it will use npm for that directory (defaults to true).

configure logging

runs installations in parallel using cp.spawn

can do dry runs to let you see what it would do first

can be run as a function or auto run using env vars

when run as a function, optionally provide array of directories to check

returns a promise that resolves when completed

allows setting max depth to look if needed

knows to stop recursing if it finds a folder with yarn workspaces (configurable)

allows skipping directories using a comma separated env var or by passing the config an array of strings to match against or a function which receives the file name, file path, and the fs.Dirent obj and expects a boolean result.

```<code>const path = require('path');
const { promises: fs } = require('fs');
const cp = require('child_process');

// if you want to have it automatically run based upon
// process.cwd()
const AUTO_RUN = Boolean(process.env.RI_AUTO_RUN);

/**
 * Creates a config object from environment variables which can then be
 * overriden if executing via its exported function (config as second arg)
 */
const getConfig = (config = {}) => ({
  // we want to use yarn by default but RI_USE_YARN=false will
  // use npm instead
  useYarn: process.env.RI_USE_YARN !== 'false',
  // should we handle yarn workspaces?  if this is true (default)
  // then we will stop recursing if a package.json has the "workspaces"
  // property and we will allow `yarn` to do its thing.
  yarnWorkspaces: process.env.RI_YARN_WORKSPACES !== 'false',
  // if truthy, will run extra checks to see if there is a package-lock.json
  // or yarn.lock file in a given directory and use that installer if so.
  detectLockFiles: process.env.RI_DETECT_LOCK_FILES !== 'false',
  // what kind of logging should be done on the spawned processes?
  // if this exists and it is not errors it will log everything
  // otherwise it will only log stderr and spawn errors
  log: process.env.RI_LOG || 'errors',
  // max depth to recurse?
  maxDepth: process.env.RI_MAX_DEPTH || Infinity,
  // do not install at the root directory?
  ignoreRoot: Boolean(process.env.RI_IGNORE_ROOT),
  // an array (or comma separated string for env var) of directories
  // to skip while recursing. if array, can pass functions which
  // return a boolean after receiving the dir path and fs.Dirent args
  // @see https://nodejs.org/api/fs.html#fs_class_fs_dirent
  skipDirectories: process.env.RI_SKIP_DIRS
    ? process.env.RI_SKIP_DIRS.split(',').map(str => str.trim())
    : undefined,
  // just run through and log the actions that would be taken?
  dry: Boolean(process.env.RI_DRY_RUN),
  ...config
});

function handleSpawnedProcess(dir, log, proc) {
  return new Promise((resolve, reject) => {
    proc.on('error', error => {
      console.log(`
----------------
  [RI] | [ERROR] | Failed to Spawn Process
  - Path:   ${dir}
  - Reason: ${error.message}
----------------
  `);
      reject(error);
    });

    if (log) {
      proc.stderr.on('data', data => {
        console.error(`[RI] | [${dir}] | ${data}`);
      });
    }

    if (log && log !== 'errors') {
      proc.stdout.on('data', data => {
        console.log(`[RI] | [${dir}] | ${data}`);
      });
    }

    proc.on('close', code => {
      if (log && log !== 'errors') {
        console.log(`
----------------
  [RI] | [COMPLETE] | Spawned Process Closed
  - Path: ${dir}
  - Code: ${code}
----------------
        `);
      }
      if (code === 0) {
        resolve();
      } else {
        reject(
          new Error(
            `[RI] | [ERROR] | [${dir}] | failed to install with exit code ${code}`
          )
        );
      }
    });
  });
}

async function recurseDirectory(rootDir, config) {
  const {
    useYarn,
    yarnWorkspaces,
    detectLockFiles,
    log,
    maxDepth,
    ignoreRoot,
    skipDirectories,
    dry
  } = config;

  const installPromises = [];

  function install(cmd, folder, relativeDir) {
    const proc = cp.spawn(cmd, ['install'], {
      cwd: folder,
      env: process.env
    });
    installPromises.push(handleSpawnedProcess(relativeDir, log, proc));
  }

  function shouldSkipFile(filePath, file) {
    if (!file.isDirectory() || file.name === 'node_modules') {
      return true;
    }
    if (!skipDirectories) {
      return false;
    }
    return skipDirectories.some(check =>
      typeof check === 'function' ? check(filePath, file) : check === file.name
    );
  }

  async function getInstallCommand(folder) {
    let cmd = useYarn ? 'yarn' : 'npm';
    if (detectLockFiles) {
      const [hasYarnLock, hasPackageLock] = await Promise.all([
        fs
          .readFile(path.join(folder, 'yarn.lock'))
          .then(() => true)
          .catch(() => false),
        fs
          .readFile(path.join(folder, 'package-lock.json'))
          .then(() => true)
          .catch(() => false)
      ]);
      if (cmd === 'yarn' && !hasYarnLock && hasPackageLock) {
        cmd = 'npm';
      } else if (cmd === 'npm' && !hasPackageLock && hasYarnLock) {
        cmd = 'yarn';
      }
    }
    return cmd;
  }

  async function installRecursively(folder, depth = 0) {
    if (dry || (log && log !== 'errors')) {
      console.log('[RI] | Check Directory --> ', folder);
    }

    let pkg;

    if (folder !== rootDir || !ignoreRoot) {
      try {
        // Check if package.json exists, if it doesnt this will error and move on
        pkg = JSON.parse(await fs.readFile(path.join(folder, 'package.json')));
        // get the command that we should use.  if lock checking is enabled it will
        // also determine what installer to use based on the available lock files
        const cmd = await getInstallCommand(folder);
        const relativeDir = `${path.basename(rootDir)} -> ./${path.relative(
          rootDir,
          folder
        )}`;
        if (dry || (log && log !== 'errors')) {
          console.log(
            `[RI] | Performing (${cmd} install) at path "${relativeDir}"`
          );
        }
        if (!dry) {
          install(cmd, folder, relativeDir);
        }
      } catch {
        // do nothing when error caught as it simply indicates package.json likely doesnt
        // exist.
      }
    }

    if (
      depth >= maxDepth ||
      (pkg && useYarn && yarnWorkspaces && pkg.workspaces)
    ) {
      // if we have reached maxDepth or if our package.json in the current directory
      // contains yarn workspaces then we use yarn for installing then this is the last
      // directory we will attempt to install.
      return;
    }

    const files = await fs.readdir(folder, { withFileTypes: true });

    return Promise.all(
      files.map(file => {
        const filePath = path.join(folder, file.name);
        return shouldSkipFile(filePath, file)
          ? undefined
          : installRecursively(filePath, depth + 1);
      })
    );
  }

  await installRecursively(rootDir);
  await Promise.all(installPromises);
}

async function startRecursiveInstall(directories, _config) {
  const config = getConfig(_config);
  const promise = Array.isArray(directories)
    ? Promise.all(directories.map(rootDir => recurseDirectory(rootDir, config)))
    : recurseDirectory(directories, config);
  await promise;
}

if (AUTO_RUN) {
  startRecursiveInstall(process.cwd());
}

module.exports = startRecursiveInstall;

</code>```

And with it being used:

```<code>const installRecursively = require('./recursive-install');

installRecursively(process.cwd(), { dry: true })
</code>```

Body:
What is the most correct way to install npm packages in nested sub folders?

my-app
  /my-sub-module
  package.json
package.json

What is the best way to have packages in /my-sub-module be installed automatically when npm install run in my-app?

Body:
Inspired by the scripts provided here, I built a configurable example which:

can be setup to use yarn or npm

can be setup to determine the command to use based on lock files so that if you set it to use yarn but a directory only has a package-lock.json it will use npm for that directory (defaults to true).

configure logging

runs installations in parallel using cp.spawn

can do dry runs to let you see what it would do first

can be run as a function or auto run using env vars

when run as a function, optionally provide array of directories to check

returns a promise that resolves when completed

allows setting max depth to look if needed

knows to stop recursing if it finds a folder with yarn workspaces (configurable)

allows skipping directories using a comma separated env var or by passing the config an array of strings to match against or a function which receives the file name, file path, and the fs.Dirent obj and expects a boolean result.

const path = require('path');
const { promises: fs } = require('fs');
const cp = require('child_process');

// if you want to have it automatically run based upon
// process.cwd()
const AUTO_RUN = Boolean(process.env.RI_AUTO_RUN);

/**
 * Creates a config object from environment variables which can then be
 * overriden if executing via its exported function (config as second arg)
 */
const getConfig = (config = {}) => ({
  // we want to use yarn by default but RI_USE_YARN=false will
  // use npm instead
  useYarn: process.env.RI_USE_YARN !== 'false',
  // should we handle yarn workspaces?  if this is true (default)
  // then we will stop recursing if a package.json has the "workspaces"
  // property and we will allow `yarn` to do its thing.
  yarnWorkspaces: process.env.RI_YARN_WORKSPACES !== 'false',
  // if truthy, will run extra checks to see if there is a package-lock.json
  // or yarn.lock file in a given directory and use that installer if so.
  detectLockFiles: process.env.RI_DETECT_LOCK_FILES !== 'false',
  // what kind of logging should be done on the spawned processes?
  // if this exists and it is not errors it will log everything
  // otherwise it will only log stderr and spawn errors
  log: process.env.RI_LOG || 'errors',
  // max depth to recurse?
  maxDepth: process.env.RI_MAX_DEPTH || Infinity,
  // do not install at the root directory?
  ignoreRoot: Boolean(process.env.RI_IGNORE_ROOT),
  // an array (or comma separated string for env var) of directories
  // to skip while recursing. if array, can pass functions which
  // return a boolean after receiving the dir path and fs.Dirent args
  // @see https://nodejs.org/api/fs.html#fs_class_fs_dirent
  skipDirectories: process.env.RI_SKIP_DIRS
    ? process.env.RI_SKIP_DIRS.split(',').map(str => str.trim())
    : undefined,
  // just run through and log the actions that would be taken?
  dry: Boolean(process.env.RI_DRY_RUN),
  ...config
});

function handleSpawnedProcess(dir, log, proc) {
  return new Promise((resolve, reject) => {
    proc.on('error', error => {
      console.log(`
----------------
  [RI] | [ERROR] | Failed to Spawn Process
  - Path:   ${dir}
  - Reason: ${error.message}
----------------
  `);
      reject(error);
    });

    if (log) {
      proc.stderr.on('data', data => {
        console.error(`[RI] | [${dir}] | ${data}`);
      });
    }

    if (log && log !== 'errors') {
      proc.stdout.on('data', data => {
        console.log(`[RI] | [${dir}] | ${data}`);
      });
    }

    proc.on('close', code => {
      if (log && log !== 'errors') {
        console.log(`
----------------
  [RI] | [COMPLETE] | Spawned Process Closed
  - Path: ${dir}
  - Code: ${code}
----------------
        `);
      }
      if (code === 0) {
        resolve();
      } else {
        reject(
          new Error(
            `[RI] | [ERROR] | [${dir}] | failed to install with exit code ${code}`
          )
        );
      }
    });
  });
}

async function recurseDirectory(rootDir, config) {
  const {
    useYarn,
    yarnWorkspaces,
    detectLockFiles,
    log,
    maxDepth,
    ignoreRoot,
    skipDirectories,
    dry
  } = config;

  const installPromises = [];

  function install(cmd, folder, relativeDir) {
    const proc = cp.spawn(cmd, ['install'], {
      cwd: folder,
      env: process.env
    });
    installPromises.push(handleSpawnedProcess(relativeDir, log, proc));
  }

  function shouldSkipFile(filePath, file) {
    if (!file.isDirectory() || file.name === 'node_modules') {
      return true;
    }
    if (!skipDirectories) {
      return false;
    }
    return skipDirectories.some(check =>
      typeof check === 'function' ? check(filePath, file) : check === file.name
    );
  }

  async function getInstallCommand(folder) {
    let cmd = useYarn ? 'yarn' : 'npm';
    if (detectLockFiles) {
      const [hasYarnLock, hasPackageLock] = await Promise.all([
        fs
          .readFile(path.join(folder, 'yarn.lock'))
          .then(() => true)
          .catch(() => false),
        fs
          .readFile(path.join(folder, 'package-lock.json'))
          .then(() => true)
          .catch(() => false)
      ]);
      if (cmd === 'yarn' && !hasYarnLock && hasPackageLock) {
        cmd = 'npm';
      } else if (cmd === 'npm' && !hasPackageLock && hasYarnLock) {
        cmd = 'yarn';
      }
    }
    return cmd;
  }

  async function installRecursively(folder, depth = 0) {
    if (dry || (log && log !== 'errors')) {
      console.log('[RI] | Check Directory --> ', folder);
    }

    let pkg;

    if (folder !== rootDir || !ignoreRoot) {
      try {
        // Check if package.json exists, if it doesnt this will error and move on
        pkg = JSON.parse(await fs.readFile(path.join(folder, 'package.json')));
        // get the command that we should use.  if lock checking is enabled it will
        // also determine what installer to use based on the available lock files
        const cmd = await getInstallCommand(folder);
        const relativeDir = `${path.basename(rootDir)} -> ./${path.relative(
          rootDir,
          folder
        )}`;
        if (dry || (log && log !== 'errors')) {
          console.log(
            `[RI] | Performing (${cmd} install) at path "${relativeDir}"`
          );
        }
        if (!dry) {
          install(cmd, folder, relativeDir);
        }
      } catch {
        // do nothing when error caught as it simply indicates package.json likely doesnt
        // exist.
      }
    }

    if (
      depth >= maxDepth ||
      (pkg && useYarn && yarnWorkspaces && pkg.workspaces)
    ) {
      // if we have reached maxDepth or if our package.json in the current directory
      // contains yarn workspaces then we use yarn for installing then this is the last
      // directory we will attempt to install.
      return;
    }

    const files = await fs.readdir(folder, { withFileTypes: true });

    return Promise.all(
      files.map(file => {
        const filePath = path.join(folder, file.name);
        return shouldSkipFile(filePath, file)
          ? undefined
          : installRecursively(filePath, depth + 1);
      })
    );
  }

  await installRecursively(rootDir);
  await Promise.all(installPromises);
}

async function startRecursiveInstall(directories, _config) {
  const config = getConfig(_config);
  const promise = Array.isArray(directories)
    ? Promise.all(directories.map(rootDir => recurseDirectory(rootDir, config)))
    : recurseDirectory(directories, config);
  await promise;
}

if (AUTO_RUN) {
  startRecursiveInstall(process.cwd());
}

module.exports = startRecursiveInstall;

And with it being used:

const installRecursively = require('./recursive-install');

installRecursively(process.cwd(), { dry: true })


问:
Wait for Firestore queries to complete
I am currently trying to run multiple queries in firestore and want to wait for them to all complete before executing the next code. I've read up on several possible avenues but I have yet to find a good Android example.

public HashMap<String,Boolean> multipleQueries(String collection, String field, final ArrayList<String> criteria) {

HashMap<String,Boolean> resultMap = new HashMap<>();

for (int i = 0; i < criteria.size(); i++){
    final int index = i;
    db.collection(collection).whereEqualTo(field,criteria.get(i)).limit(1)
    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
    if(task.isSuccessful()) {
         if(task.getResult().size() != 0 ){
           resultMap.put(criteria.get(index),true);
         } else {
             resultMap.put(criteria.get(index),false);
          }
    } else {
        resultMap.put(criteria.get(index),false);

    }

    }

     });
   }
   return resultMap;

}

```

答:
Since get() returns a Task, you can use Tasks.whenAll(...).

But you won't be able to return a List from this function, since all data is asynchronously loaded. The best you can do is return the result from Task.whenAll(...), which is itself a Task. See Doug Stevenson's great article on becoming a task master: https://firebase.googleblog.com/2016/10/become-a-firebase-taskmaster-part-4.html

Title: Wait for Firestore queries to complete


问:
Is there a speed difference in MySQL operations?
I was discussing speed of MySQL statements and someone asked me: Between SELECT, INSERT, UPDATE, and DELETE, which is faster and why?

I didn't know the answer. Does anyone know if one is faster than the other, and if so, why? Or are they all generally the same speed?

答:
You're not quite asking the right question.  SELECT, for example, has to compute, in some fashion, the set of all rows that match the selection, and then return them via some mechanism that may be anything from a big-ass dynamic array in something like sqlite (because it's in memory and in the same process) to data passed remotely across the internet.

So, for example, SELECT * FROM USERDATA returning 10 rows locally might take microseconds, but take minutes if it's returning 10,000,000 rows across a WAN.

OwnerDisplayName: rocket

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charlie Martin


问:
Drupal - Full node content not teaser
I'm making a blog, but I don't have a large experience with Drupal (I'm using Drupal 6).

The index page should have a post with full content and the next 10 posts showing the teaser. I want to know how to show the full content of just the first loaded node.

I'm hitting my head against the keyboard for hours, but I can't get a simple solution for it. I've tried to see all defined_vars and all are filled with the teaser, I've tried to use node_view($node->nid) but it seems to enter in a infinite recursion. I've been searching a lot in Google, but nothing seems to satisfy.

I guess that I don't need to use the View module for it, cause I just wanna change the $teaser = true to false when I get loaded a node.

Someone have an idea for it?

Thank you all!

答:
Views is a great fit for your problem.  If you use views you can create a view for all the teasers and then add the full node view as the view header or use a view theme.  a view theme gives you allot of flexibility.

If you want to do everything programmatically, try this to load the node.

```<code>$node = node_load($nid);
$content = node_build_content($node);
</code>```

if that doesn't work try

```<code>$node = node_load($nid);
$node = (object)$node; // may need to cast to an object
$content = node_build_content($node);
</code>```

Title: Drupal - Full node content not teaser

Body:
Views is a great fit for your problem.  If you use views you can create a view for all the teasers and then add the full node view as the view header or use a view theme.  a view theme gives you allot of flexibility.

If you want to do everything programmatically, try this to load the node.

$node = node_load($nid);
$content = node_build_content($node);

if that doesn't work try

$node = node_load($nid);
$node = (object)$node; // may need to cast to an object
$content = node_build_content($node);


答:
Back to 2012 , when we do not have eq , ne and gt , pandas have the problem : disorder Series will return the unexpected output with logic (>,<,==,!=) , so they doing with a fix (new function added, gt,ge,ne..)

GitHub Ticket reference

Title: Why isn't pandas logical operator aligning on the index like it should?


问:
Can Ajax CalendarExtender have Boundfield as the TargetControlID
Can Ajax CalendarExtender have asp:BoundField as the TragetControlID because in the grid i have, it says unavailable. How can i get each date from the calendar into the BoundField?

```<code><asp:TemplateField ItemStyle-HorizontalAlign="center" ItemStyle-VerticalAlign="Middle" FooterStyle-Width="25px" HeaderText="Schedule">
                <ItemTemplate>
         <asp:ImageButton ID="CalendarIcon" runat="server" ImageUrl="~/images/calender-no-edit.gif" />
               <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" PopupPosition="Left" PopupButtonID="CalendarIcon"
                    TargetControlID="ScheduleDate" >
                </ajaxToolkit:CalendarExtender>
                </ItemTemplate>
            </asp:TemplateField>
                <asp:BoundField DataField="ScheduleDate" HeaderText="Deal"><HeaderStyle HorizontalAlign="Left" /></asp:BoundField>
</code>```

Thanks,

答: Check out this thread on the asp.net forums: Ajax Calendar Extender Within Gridview</p>

Body:
Can Ajax CalendarExtender have asp:BoundField as the TragetControlID because in the grid i have, it says unavailable. How can i get each date from the calendar into the BoundField?

<asp:TemplateField ItemStyle-HorizontalAlign="center" ItemStyle-VerticalAlign="Middle" FooterStyle-Width="25px" HeaderText="Schedule">
                <ItemTemplate>
         <asp:ImageButton ID="CalendarIcon" runat="server" ImageUrl="~/images/calender-no-edit.gif" />
               <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" PopupPosition="Left" PopupButtonID="CalendarIcon"
                    TargetControlID="ScheduleDate" >
                </ajaxToolkit:CalendarExtender>
                </ItemTemplate>
            </asp:TemplateField>
                <asp:BoundField DataField="ScheduleDate" HeaderText="Deal"><HeaderStyle HorizontalAlign="Left" /></asp:BoundField>

Thanks,


答:
Viewing the whole traceback for a Series comparison with mismatched indexes, particularly focusing on the exception message:

```<code>In [1]: import pandas as pd
In [2]: x = pd.Series([1, 2, 3], index=list('abc'))
In [3]: y = pd.Series([2, 3, 3], index=list('bca'))
In [4]: x == y
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-73b2790c1e5e> in <module>()
----> 1 x == y
/usr/lib/python3.7/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
   1188
   1189         elif isinstance(other, ABCSeries) and not self._indexed_same(othe
r):
-> 1190             raise ValueError("Can only compare identically-labeled "
   1191                              "Series objects")
   1192
ValueError: Can only compare identically-labeled Series objects
</code>```

we see that this is a deliberate implementation decision. Also, this is not unique to Series objects - DataFrames raise a similar error.

Digging through the Git blame for the relevant lines eventually turns up some relevant commits and issue tracker threads. For example, Series.__eq__ used to completely ignore the RHS's index, and in a comment on a bug report about that behavior, Pandas author Wes McKinney says the following:

This is actually a feature / deliberate choice and not a bug-- it's
  related to #652. Back in January I changed the comparison methods to
  do auto-alignment, but found that it led to a large amount of bugs /
  breakage for users and, in particular, many NumPy functions (which
  regularly do things like arr[1:] == arr[:-1]; example: np.unique)
  stopped working.

This gets back to the issue that Series isn't quite ndarray-like
  enough and should probably not be a subclass of ndarray.

So, I haven't got a good answer for you except for that;
  auto-alignment would be ideal but I don't think I can do it unless I
  make Series not a subclass of ndarray. I think this is probably a good
  idea but not likely to happen until 0.9 or 0.10 (several months down
  the road).

This was then changed to the current behavior in pandas 0.19.0. Quoting the "what's new" page:

Following Series operators have been changed to make all operators
  consistent, including DataFrame (GH1134, GH4581,
  GH13538)

Series comparison operators now raise ValueError when index are different.

Series logical operators align both index of left and right hand side.

This made the Series behavior match that of DataFrame, which already rejected mismatched indices in comparisons.

In summary, making the comparison operators align indices automatically turned out to break too much stuff, so this was the best alternative.

Body:
Viewing the whole traceback for a Series comparison with mismatched indexes, particularly focusing on the exception message:

In [1]: import pandas as pd
In [2]: x = pd.Series([1, 2, 3], index=list('abc'))
In [3]: y = pd.Series([2, 3, 3], index=list('bca'))
In [4]: x == y
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-73b2790c1e5e> in <module>()
----> 1 x == y
/usr/lib/python3.7/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
   1188
   1189         elif isinstance(other, ABCSeries) and not self._indexed_same(othe
r):
-> 1190             raise ValueError("Can only compare identically-labeled "
   1191                              "Series objects")
   1192
ValueError: Can only compare identically-labeled Series objects

we see that this is a deliberate implementation decision. Also, this is not unique to Series objects - DataFrames raise a similar error.

Digging through the Git blame for the relevant lines eventually turns up some relevant commits and issue tracker threads. For example, Series.__eq__ used to completely ignore the RHS's index, and in a comment on a bug report about that behavior, Pandas author Wes McKinney says the following:

This is actually a feature / deliberate choice and not a bug-- it's
  related to #652. Back in January I changed the comparison methods to
  do auto-alignment, but found that it led to a large amount of bugs /
  breakage for users and, in particular, many NumPy functions (which
  regularly do things like arr[1:] == arr[:-1]; example: np.unique)
  stopped working.

This gets back to the issue that Series isn't quite ndarray-like
  enough and should probably not be a subclass of ndarray.

So, I haven't got a good answer for you except for that;
  auto-alignment would be ideal but I don't think I can do it unless I
  make Series not a subclass of ndarray. I think this is probably a good
  idea but not likely to happen until 0.9 or 0.10 (several months down
  the road).

This was then changed to the current behavior in pandas 0.19.0. Quoting the "what's new" page:

Following Series operators have been changed to make all operators
  consistent, including DataFrame (GH1134, GH4581,
  GH13538)

Series comparison operators now raise ValueError when index are different.

Series logical operators align both index of left and right hand side.

This made the Series behavior match that of DataFrame, which already rejected mismatched indices in comparisons.

In summary, making the comparison operators align indices automatically turned out to break too much stuff, so this was the best alternative.


问:
python mpl_toolkits installation issue
After command pip install mpl_toolkits I receive next error:

Could not find a version that satisfies the requirement mpl_toolkits (from versions: )

No matching distribution found for mpl_toolkits

I tried to google, but nothing helps. How can I solve this?

答:
I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

```<code>pacman -S python-basemap
</code>```

Title: python mpl_toolkits installation issue

Body:
I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap


问:
How can I create custom bubble animation for angular material slider thumb?
I'm implementing angular material slider for content versioning. There is a requirement to add bubble that would follow mat-slider-thumb along the slider track. The biggest problem is to trigger animation on every mat-slider-thumb position change.
I'm super new to angular animations and I can't get it started.
I would appreciate any feedback!

Compare version

    <mat-slider
        [disabled]="disableSlider"
        tickInterval="1"
        [step]="revisionsCount"
        color="primary" class="slider"
        (input)="getCurrentVersion($event)">
    </mat-slider>

        <mat-icon>today</mat-icon>
        {{ revision.date | date: 'dd-MM-yyyy' }}
        <mat-icon>restore</mat-icon>
        {{ revision.date | date: 'HH:mm' }}

```

答:
According to this question: Parameter into animation you can add your output from the mat-slider to your bubble component/animation.

The answer also provides an example that fits to your problem.


问:
Email validation C# asp.net
I used the following pattern to validate my email field.

```<code>    return Regex.IsMatch(email,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
</code>```

It uses the following reference:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

My requirement is to have maximum number of 64 characters for user part, and max length for whole email string is 254 characters.  The pattern in the reference only allow max 134 characters. Can someone give clear explanation of the meaning for the pattern? What is the right pattern to achieve my goal?

答:
Several years back, I wrote an email validation attribute in C# that should recognize most of that subset of syntactically valid email addresses that have the form local-part@domain — I say "most" because I didn't bother to try do deal with things like punycode, IPv4 address literals (dotted quads), or IPv6 address literals.

I'm sure there's lots of other edge cases I missed as well. But it worked well enough for our purposes at the time.

Use it in good health: C# Email Address validation

Before you go down the road of writing you own, you might want to read through the multiple relevant RFCs and try to understand the vagaries of what constitutes a "valid"  email address (it's not what you think), and (2) stop trying to validate an RFC 822 email address. About the only way to "validate" an email address is to send mail to it and see if it bounces or not. Which doesn't mean that anybody is home at that address, or that that mailbox won't disappear next week.

https://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/

https://jackfoxy.github.io/FsRegEx/emailregex.html

Jeffrey Friedl's book Mastering Regular Expressions has a [more-or-less?] complete regular expression to match syntactically valid email addresses. It's 6,598 characters long.

Did you know that postmaster@. is a legal email address? It theoretically gets you to the postmaster of the root DNS server.

Or that [theoretically] "bang path" email addresses like  MyDepartmentServer!MainServer!BigRouter!TheirDepartmentServer!SpecificServer!jsmith are valid. Here you define the actual path through the network that the email should take. Helps if you know the network topology involved.

Title: Email validation C# asp.net

Body:
I used the following pattern to validate my email field.

    return Regex.IsMatch(email,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

It uses the following reference:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

My requirement is to have maximum number of 64 characters for user part, and max length for whole email string is 254 characters.  The pattern in the reference only allow max 134 characters. Can someone give clear explanation of the meaning for the pattern? What is the right pattern to achieve my goal?


问:
How to Implement Custom Error Pages with Application Insights
I recently implemented Application Insights into my MVC C# app.  I was able to confirm the logging including error messages like 404.  I updated my web config to use a custom error page instead of the ugly default.  However, errors are no longer logged with Application Insights - just the fact that the error page was called.

I assume I have two options.

1) I turned off the custom error config and set a break point in the AiHandleErrorAttribute.cs file that was automatically added when I added Application Insights.  I was hoping to redirect to my error page after the exception but the break point was never reached.

```<code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AiHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
        {
            //If customError is Off, then AI HTTPModule will report the exception
            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {
                var ai = new TelemetryClient();
                ai.TrackException(filterContext.Exception);
                //redirect to error page - never gets called
            }
        }
        base.OnException(filterContext);
    }
}
</code>```

2) Call Application Insights from my controller for the error handling page, however, there are no errors (at least that I can tell) once I land/get redirected to my error handling page.

```<code>public class ErrorHandlerController : Controller
{
    // GET: ErrorHandler
    public ActionResult Index()
    {
        var ai = new TelemetryClient();
        ai.TrackException(can't find exception at this point);
        return View();
    }
}
</code>```

答:
you can do this:</p>

```<code>  var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    ai.TrackException(exceptionHandlerPathFeature.Error);
</code>```

Body:
I recently implemented Application Insights into my MVC C# app.  I was able to confirm the logging including error messages like 404.  I updated my web config to use a custom error page instead of the ugly default.  However, errors are no longer logged with Application Insights - just the fact that the error page was called.

I assume I have two options.

1) I turned off the custom error config and set a break point in the AiHandleErrorAttribute.cs file that was automatically added when I added Application Insights.  I was hoping to redirect to my error page after the exception but the break point was never reached.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AiHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
        {
            //If customError is Off, then AI HTTPModule will report the exception
            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {
                var ai = new TelemetryClient();
                ai.TrackException(filterContext.Exception);
                //redirect to error page - never gets called
            }
        }
        base.OnException(filterContext);
    }
}

2) Call Application Insights from my controller for the error handling page, however, there are no errors (at least that I can tell) once I land/get redirected to my error handling page.

public class ErrorHandlerController : Controller
{
    // GET: ErrorHandler
    public ActionResult Index()
    {
        var ai = new TelemetryClient();
        ai.TrackException(can't find exception at this point);
        return View();
    }
}

Body:
you can do this:

  var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    ai.TrackException(exceptionHandlerPathFeature.Error);


问:
Dart Firestore add to array
I'm writing a Flutter app and am trying to add an element to an array. I'm trying to follow the example here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array - however, My DocumentReference object does not have an update object:

So, how do I go about adding an element to an array in this document?

For reference, I'm using the cloud_firestore: 0.12.1 dependency.

答:
The method you should use is updateData(). You pass to it a map.

Here is an example adding an element (the string 'element') to an array (named loosely 'arrayName') :

```<code>userPantry.updateData({'arrayName': FieldValue.arrayUnion(['element'])})
</code>```

Title: Dart Firestore add to array

Body:
The method you should use is updateData(). You pass to it a map.

Here is an example adding an element (the string 'element') to an array (named loosely 'arrayName') :

userPantry.updateData({'arrayName': FieldValue.arrayUnion(['element'])})


问:
how to change the order of columns in a matrix in R
How to change the position of the columns in a matrix, in the manner of the last column in M, sea the first in G, the second column in M, sea the penultimate in G and so on

for example

```<code>     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
</code>```

and I want

```<code>     [,1] [,2] [,3] [,4]
[1,]    13    9    5   1
[2,]    14    10   6   2
[3,]    15    11   7   3
[4,]    16    12   8   4
</code>```

thanks!

Body:
How to change the position of the columns in a matrix, in the manner of the last column in M, sea the first in G, the second column in M, sea the penultimate in G and so on

for example

     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16

and I want

     [,1] [,2] [,3] [,4]
[1,]    13    9    5   1
[2,]    14    10   6   2
[3,]    15    11   7   3
[4,]    16    12   8   4

thanks!

Body:
Simplest way would be -

mat[, ncol(mat):1]

     [,1] [,2] [,3] [,4]
[1,]   13    9    5    1
[2,]   14   10    6    2
[3,]   15   11    7    3
[4,]   16   12    8    4


问:
How to create a switching function in Python?
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

```<code>def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)
</code>```

it outputs:

```<code>value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
</code>```

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

答:
Probably most fun and simple use case of Clousers. Concept works in many other programming languages including javascript, perl etc and even syntax is almost same:

```<code>def switch():
    string = 'o'
    def change():
        nonlocal string
        if(string == 'x'):
            string = 'o'
        else:
            string = 'x'
        return string

    return change

switcher = switch()
for _ in range(4):
    print(switcher())
</code>```

output:

```<code>x
o
x
o
</code>```

Body:
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)

it outputs:

value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

Body:
Probably most fun and simple use case of Clousers. Concept works in many other programming languages including javascript, perl etc and even syntax is almost same:

def switch():
    string = 'o'
    def change():
        nonlocal string
        if(string == 'x'):
            string = 'o'
        else:
            string = 'x'
        return string

    return change

switcher = switch()
for _ in range(4):
    print(switcher())

output:

x
o
x
o


问:
404 Not Found error in preflight OPTIONS when executing a PUT method in CakePHP API with axios in React App
So, we have an API with CakePHP 3.7. We are using resources to generate CRUD methods. The API is hosted in a server with apache2 and is accessed through a manager app using React (this app is a microservice). The manager makes the calls through axios and is correctly managing the GET, POST and HEAD requests (simple CORS requests) but we're having problems when it comes to more complex requests such as PUT or DELETE.

When executing PUT or DELETE requests it makes a preflight OPTIONS request and it returns a 404 Not Found error. And some messages in console related with CORS which are:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSPreflightDidNotSucceed?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default

We already tried several fixes, such as using CakePHP CORS plugin, adding CORS Headers in the response in the beforeRender and beforeFilter methods of AppController and also adding CORS headers in the apache, none of this seams to be working.

    private function setCorsHeaders() {
        $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['*'])
            ->exposeHeaders(['X-Total-Pages'])
            ->maxAge(800)
            ->build();
    }

    public function beforeRender(Event $event)
    {
        $this->setCorsHeaders();
    }

    public function beforeFilter(Event $event)
    {
        if($this->request->is('options')) {
            $this->setCorsHeaders();
            return $this->response;
        }
    }
```

```Header set Access-Control-Expose-Headers "X-Total-Pages"
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"
```

The expected behaviour is that the PUT and DELETE methods are executed properly (the preflight OPTIONS should pass successfully). Any help is apreciated.

答:
In CakePHP >=3.4, Http\Response objects are treated as immutable by many methods. The method chain called on $this->request->cors() uses the CorsBuilder class to queue the desired headers on an immutable response which is returned when calling build().

Try assigning the return from CorsBuilder::build() with the queued headers to $this->response.

```<code>    private function setCorsHeaders() {
        $this->response = $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['*'])
            ->exposeHeaders(['X-Total-Pages'])
            ->maxAge(800)
            ->build();
    }
</code>```

Body:
So, we have an API with CakePHP 3.7. We are using resources to generate CRUD methods. The API is hosted in a server with apache2 and is accessed through a manager app using React (this app is a microservice). The manager makes the calls through axios and is correctly managing the GET, POST and HEAD requests (simple CORS requests) but we're having problems when it comes to more complex requests such as PUT or DELETE.

When executing PUT or DELETE requests it makes a preflight OPTIONS request and it returns a 404 Not Found error. And some messages in console related with CORS which are:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSPreflightDidNotSucceed?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default

We already tried several fixes, such as using CakePHP CORS plugin, adding CORS Headers in the response in the beforeRender and beforeFilter methods of AppController and also adding CORS headers in the apache, none of this seams to be working.

    private function setCorsHeaders() {
        $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['*'])
            ->exposeHeaders(['X-Total-Pages'])
            ->maxAge(800)
            ->build();
    }

    public function beforeRender(Event $event)
    {
        $this->setCorsHeaders();
    }

    public function beforeFilter(Event $event)
    {
        if($this->request->is('options')) {
            $this->setCorsHeaders();
            return $this->response;
        }
    }

Header set Access-Control-Expose-Headers "X-Total-Pages"
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"

The expected behaviour is that the PUT and DELETE methods are executed properly (the preflight OPTIONS should pass successfully). Any help is apreciated.

Body:
In CakePHP >=3.4, Http\Response objects are treated as immutable by many methods. The method chain called on $this->request->cors() uses the CorsBuilder class to queue the desired headers on an immutable response which is returned when calling build().

Try assigning the return from CorsBuilder::build() with the queued headers to $this->response.

    private function setCorsHeaders() {
        $this->response = $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['*'])
            ->exposeHeaders(['X-Total-Pages'])
            ->maxAge(800)
            ->build();
    }


问:
How to generate imports and boilerplate lists using Template Haskell?
I'd like to replace this boilerplate with code generation:

```<code>import qualified Y15.D01
import qualified Y15.D02
import qualified Y15.D03
import qualified Y15.D04
import qualified Y15.D05
import qualified Y15.D06HM
import qualified Y15.D06IO
import qualified Y15.D06ST
import qualified Y15.D07
import qualified Y15.D08
import qualified Y15.D09
import qualified Y15.D10
import qualified Y15.D11
import qualified Y15.D12
import qualified Y15.D13

...

days :: [(String, [String -> IO String])]
days =
    [ ("Y15.D01",  i2ios   [Y15.D01.solve1,   Y15.D01.solve2])
    , ("Y15.D02",  i2ios   [Y15.D02.solve1,   Y15.D02.solve2])
    , ("Y15.D03",  i2ios   [Y15.D03.solve1,   Y15.D03.solve2])
    , ("Y15.D04",  i2ios   [Y15.D04.solve1,   Y15.D04.solve2])
    , ("Y15.D05",  i2ios   [Y15.D05.solve1,   Y15.D05.solve2])
    , ("Y15.D06HM",i2ios   [Y15.D06HM.solve1, Y15.D06HM.solve2]) -- Data.Map.Strict
    , ("Y15.D06IO",ioi2ios [Y15.D06IO.solve1, Y15.D06IO.solve2]) -- Data.Array.IO
    , ("Y15.D06ST",i2ios   [Y15.D06ST.solve1, Y15.D06ST.solve2]) -- Data.Array.ST
    , ("Y15.D07",  i2ios   [Y15.D07.solve1,   Y15.D07.solve2])
    , ("Y15.D08",  i2ios   [Y15.D08.solve1,   Y15.D08.solve2])
    , ("Y15.D09",  i2ios   [Y15.D09.solve1,   Y15.D09.solve2])
    , ("Y15.D10",  i2ios   [Y15.D10.solve1,   Y15.D10.solve2])
    , ("Y15.D11",  s2ios   [Y15.D11.solve1,   Y15.D11.solve2])
    , ("Y15.D12",  i2ios   [Y15.D12.solve1,   Y15.D12.solve2])
    , ("Y15.D13",  i2ios   [Y15.D13.solve1,   Y15.D13.solve2])
    ]
  where s2ios :: [a -> b] -> [a -> IO b]
        s2ios   = fmap (return .)
        i2ios :: [a -> Int] -> [a -> IO String]
        i2ios   = fmap ((return . show) .)
        ioi2ios :: [a -> IO Int] -> [a -> IO String]
        ioi2ios = fmap (fmap show .)
</code>```

https://github.com/oshyshko/adventofcode/blob/master/src/Main.hs

I am new to Template Haskell and I would appreciate any help/suggestions on where to start with these questions:

How to list modules in a project that match /Y\d\d.D\d\d.*/ pattern?

How to generate imports for p.1?

How to retrieve types of solve1 and solve2 fns from a given module?

How to generate days list?

答:
With respect to question (2), Template Haskell cannot generate import statements.  You can see a very old feature request for it in the bug tracker on GitLab but no one's been sufficiently inspired to implement it.

With respect to question (3), if modules have been imported and their names are available as strings, you can use TH to retrieve the type of a binding in each module like so.  Given:

```<code>-- M001.hs
module M001 where
solve1 :: Int
solve1 = 10

-- M002.hs
module M002 where
solve1 :: IO Int
solve1 = return 20

-- THTest1.hs
{-# LANGUAGE TemplateHaskell #-}

module THTest1 where

import M001
import M002

import Language.Haskell.TH

let
  modules = ["M001", "M002"]

  showType :: String -> Q ()
  showType nm = do
    Just n <- lookupValueName nm
    VarI _ typ _ <- reify n
    reportWarning $ show nm ++ " has type " ++ show typ
    return ()

  in do mapM_ showType (map (++ ".solve1") modules)
        return []
</code>```

Then compiling THTest.hs will generate two warnings:

```<code>warning: "M001.solve1" has type ConT GHC.Types.Int
warning: "M002.solve1" has type AppT (ConT GHC.Types.IO)
     (ConT GHC.Types.Int)
</code>```

For question (4), here's a simplified example using modules M001 and M002 as defined above.  Compile this program with ghc -ddump-splices to see the definition generated for days:

```<code>-- THTest2.hs
{-# LANGUAGE TemplateHaskell #-}

import M001
import M002

import Control.Monad
import GHC.Types
import Language.Haskell.TH

let
  -- list of modules to search
  modules = ["M001", "M002"]
  -- assoc list of adapter function by argument type
  funcs = [(ConT ''Int, 'return), (AppT (ConT ''IO) (ConT ''Int), 'id)]

  getDay :: String -> Q Exp
  getDay modname = do
    -- look up name (e.g., M001.solve1)
    Just n <- lookupValueName (modname ++ ".solve1")
    -- get type of binding
    VarI _ typ _ <- reify n
    -- look up appropriate adapter function
    let Just f = lookup typ funcs
    -- ("M001", adapter_f M001.solve1)
    [|($(pure $ LitE (StringL modname)),
       $(pure $ AppE (VarE f) (VarE n)))|]

  makeDays :: Q [Dec]
  makeDays = do
    [d| days :: [(String, IO Int)]
        days = $(ListE <$> mapM getDay modules)
      |]
  in makeDays

main = do
  forM days $ \(modname, action) -> do
    putStr modname
    putStr ": "
    print =<< action
</code>```

Then running it will output:

```<code>M001: 10
M002: 20
</code>```

Body:
I'd like to replace this boilerplate with code generation:

import qualified Y15.D01
import qualified Y15.D02
import qualified Y15.D03
import qualified Y15.D04
import qualified Y15.D05
import qualified Y15.D06HM
import qualified Y15.D06IO
import qualified Y15.D06ST
import qualified Y15.D07
import qualified Y15.D08
import qualified Y15.D09
import qualified Y15.D10
import qualified Y15.D11
import qualified Y15.D12
import qualified Y15.D13

...

days :: [(String, [String -> IO String])]
days =
    [ ("Y15.D01",  i2ios   [Y15.D01.solve1,   Y15.D01.solve2])
    , ("Y15.D02",  i2ios   [Y15.D02.solve1,   Y15.D02.solve2])
    , ("Y15.D03",  i2ios   [Y15.D03.solve1,   Y15.D03.solve2])
    , ("Y15.D04",  i2ios   [Y15.D04.solve1,   Y15.D04.solve2])
    , ("Y15.D05",  i2ios   [Y15.D05.solve1,   Y15.D05.solve2])
    , ("Y15.D06HM",i2ios   [Y15.D06HM.solve1, Y15.D06HM.solve2]) -- Data.Map.Strict
    , ("Y15.D06IO",ioi2ios [Y15.D06IO.solve1, Y15.D06IO.solve2]) -- Data.Array.IO
    , ("Y15.D06ST",i2ios   [Y15.D06ST.solve1, Y15.D06ST.solve2]) -- Data.Array.ST
    , ("Y15.D07",  i2ios   [Y15.D07.solve1,   Y15.D07.solve2])
    , ("Y15.D08",  i2ios   [Y15.D08.solve1,   Y15.D08.solve2])
    , ("Y15.D09",  i2ios   [Y15.D09.solve1,   Y15.D09.solve2])
    , ("Y15.D10",  i2ios   [Y15.D10.solve1,   Y15.D10.solve2])
    , ("Y15.D11",  s2ios   [Y15.D11.solve1,   Y15.D11.solve2])
    , ("Y15.D12",  i2ios   [Y15.D12.solve1,   Y15.D12.solve2])
    , ("Y15.D13",  i2ios   [Y15.D13.solve1,   Y15.D13.solve2])
    ]
  where s2ios :: [a -> b] -> [a -> IO b]
        s2ios   = fmap (return .)
        i2ios :: [a -> Int] -> [a -> IO String]
        i2ios   = fmap ((return . show) .)
        ioi2ios :: [a -> IO Int] -> [a -> IO String]
        ioi2ios = fmap (fmap show .)

https://github.com/oshyshko/adventofcode/blob/master/src/Main.hs

I am new to Template Haskell and I would appreciate any help/suggestions on where to start with these questions:

How to list modules in a project that match /Y\d\d.D\d\d.*/ pattern?

How to generate imports for p.1?

How to retrieve types of solve1 and solve2 fns from a given module?

How to generate days list?

Body:
With respect to question (2), Template Haskell cannot generate import statements.  You can see a very old feature request for it in the bug tracker on GitLab but no one's been sufficiently inspired to implement it.

With respect to question (3), if modules have been imported and their names are available as strings, you can use TH to retrieve the type of a binding in each module like so.  Given:

-- M001.hs
module M001 where
solve1 :: Int
solve1 = 10

-- M002.hs
module M002 where
solve1 :: IO Int
solve1 = return 20

-- THTest1.hs
{-# LANGUAGE TemplateHaskell #-}

module THTest1 where

import M001
import M002

import Language.Haskell.TH

let
  modules = ["M001", "M002"]

  showType :: String -> Q ()
  showType nm = do
    Just n <- lookupValueName nm
    VarI _ typ _ <- reify n
    reportWarning $ show nm ++ " has type " ++ show typ
    return ()

  in do mapM_ showType (map (++ ".solve1") modules)
        return []

Then compiling THTest.hs will generate two warnings:

warning: "M001.solve1" has type ConT GHC.Types.Int
warning: "M002.solve1" has type AppT (ConT GHC.Types.IO)
     (ConT GHC.Types.Int)

For question (4), here's a simplified example using modules M001 and M002 as defined above.  Compile this program with ghc -ddump-splices to see the definition generated for days:

-- THTest2.hs
{-# LANGUAGE TemplateHaskell #-}

import M001
import M002

import Control.Monad
import GHC.Types
import Language.Haskell.TH

let
  -- list of modules to search
  modules = ["M001", "M002"]
  -- assoc list of adapter function by argument type
  funcs = [(ConT ''Int, 'return), (AppT (ConT ''IO) (ConT ''Int), 'id)]

  getDay :: String -> Q Exp
  getDay modname = do
    -- look up name (e.g., M001.solve1)
    Just n <- lookupValueName (modname ++ ".solve1")
    -- get type of binding
    VarI _ typ _ <- reify n
    -- look up appropriate adapter function
    let Just f = lookup typ funcs
    -- ("M001", adapter_f M001.solve1)
    [|($(pure $ LitE (StringL modname)),
       $(pure $ AppE (VarE f) (VarE n)))|]

  makeDays :: Q [Dec]
  makeDays = do
    [d| days :: [(String, IO Int)]
        days = $(ListE <$> mapM getDay modules)
      |]
  in makeDays

main = do
  forM days $ \(modname, action) -> do
    putStr modname
    putStr ": "
    print =<< action

Then running it will output:

M001: 10
M002: 20


问:
Viewing a particular html + django
I am trying to learn django by reading the tutorial and Django book on the net.

I am trying to display a web page on a url.

For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function.

Also in the home function I wrote

```<code>def home( request ):

      return render_to_response("home.html",None) // home.html is placed in the templates folder along with its .css
</code>```

This must be wrong as I don't intend to pass any response ... so please tell what i should write here...

However the issue I am facing is that when I go to the url the html comes in plain without the css styling without the color etc.....

When I check my html template however that is fine ...

So what do I need to do to display the html as it is in the url ???

Thanks..

答:
You need to put the .css in the STATIC_FILES directory (if you are using 1.3 or MEDIA_URL for 1.2)

http://docs.djangoproject.com/en/dev/howto/static-files/

Then you need to link to the css in the head of the html file with something like:

```<code><head>
  {% load static %}
  <link rel="stylesheet" href="{% get_static_prefix %}html.css" />
</head>
</code>```

Title: Viewing a particular html + django

Body:
I am trying to learn django by reading the tutorial and Django book on the net.

I am trying to display a web page on a url.

For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function.

Also in the home function I wrote

def home( request ):

      return render_to_response("home.html",None) // home.html is placed in the templates folder along with its .css

This must be wrong as I don't intend to pass any response ... so please tell what i should write here...

However the issue I am facing is that when I go to the url the html comes in plain without the css styling without the color etc.....

When I check my html template however that is fine ...

So what do I need to do to display the html as it is in the url ???

Thanks..

Body:
You need to put the .css in the STATIC_FILES directory (if you are using 1.3 or MEDIA_URL for 1.2)

http://docs.djangoproject.com/en/dev/howto/static-files/

Then you need to link to the css in the head of the html file with something like:

<head>
  {% load static %}
  <link rel="stylesheet" href="{% get_static_prefix %}html.css" />
</head>


问:
React - Unable to setState inside a Promise then
I'm trying to set the state inside a then() of a Promise, but the state value is not getting saved and is not accessible outside of the then().

Below is the UPDATED code:

```<code>handleSelect = location => {
  this.setState({ location });
  geocodeByAddress(
    location
  )
  .then(results => getLatLng(results[0]))
  .then(latLng => {
    this.setState({
      location_latitude: latLng.lat,
      location_longitude: latLng.lng,
    })
    console.log(this.state.location_latitude); // returns the correct value
  })
  console.log(this.state.location_latitude); // returns null (the originally declared value)
}
</code>```

If I console.log(this.state.location_latitude) I get a null value. But if I console.log inside the then() block, I get the correct value. How do I set the state in this case?

UPDATED explanation:

To give a better context to the whole logic here: I'm using a Google Places Autocomplete component which allows the user to select a location from the dropdown. The above method handleSelect is called when the user selects a location from the dropdown. I then extract the latitude and longitude of the place selected by the user using the geocodeByAddress method, which is a promise. I need to then retrieve the latitude and longitude and set the state accordingly, which is later used to send to the database. I can't submit the value to the database yet because there are other form inputs that the user needs to fill (which are also stored in the state) and once he clicks on Submit, I'll be submitting all the state elements in a single call to the backend. So, there is nothing I want to update with componentDidMount() or nothing is getting updated yet to use componentDidUpdate(). In any case, I can only store the state value inside the then of geocodeByAddress (please correct me if I'm wrong here). So, I HAVE to be able to modify the state value inside the then block.

答:
This is clearly an issue with your data call not react.

Your react code looks fine but I suggest spitting the code.

1) service.js file - this does your query and returns data or returns error.

2) location component, componentDidMount() or useEffect(() => {}, []) gets the data and updates state/useState()

—

To give you a code snippet I need to you to provide a console log of latLang & results.

Many thanks

Body:
I'm trying to set the state inside a then() of a Promise, but the state value is not getting saved and is not accessible outside of the then().

Below is the UPDATED code:

handleSelect = location => {
  this.setState({ location });
  geocodeByAddress(
    location
  )
  .then(results => getLatLng(results[0]))
  .then(latLng => {
    this.setState({
      location_latitude: latLng.lat,
      location_longitude: latLng.lng,
    })
    console.log(this.state.location_latitude); // returns the correct value
  })
  console.log(this.state.location_latitude); // returns null (the originally declared value)
}

If I console.log(this.state.location_latitude) I get a null value. But if I console.log inside the then() block, I get the correct value. How do I set the state in this case?

UPDATED explanation:

To give a better context to the whole logic here: I'm using a Google Places Autocomplete component which allows the user to select a location from the dropdown. The above method handleSelect is called when the user selects a location from the dropdown. I then extract the latitude and longitude of the place selected by the user using the geocodeByAddress method, which is a promise. I need to then retrieve the latitude and longitude and set the state accordingly, which is later used to send to the database. I can't submit the value to the database yet because there are other form inputs that the user needs to fill (which are also stored in the state) and once he clicks on Submit, I'll be submitting all the state elements in a single call to the backend. So, there is nothing I want to update with componentDidMount() or nothing is getting updated yet to use componentDidUpdate(). In any case, I can only store the state value inside the then of geocodeByAddress (please correct me if I'm wrong here). So, I HAVE to be able to modify the state value inside the then block.


问:
How to chain promises in series in a while loop
I have to make a query to multiple databases in series. Basically a set of promises that have to be completed in series. I am implementing it in a while loop. The databases are named based on dates. I also have to set a request delay of 400ms times the amount of loops passed (400*count) between each promise. If it helps I am using cloudant as my database, similar to mongodb/couchdb but an online instance.

So I have implemented a query function that will take a start and end date and will retrieve all the values in the range. If the dates are the same then it will query one database, otherwise it will query multiple databases for each day between the range of dates. I am mainly having trouble with the else block in the if statement as you can see below.

```<code>db.predQuery = (start, end, locationCode) => {
        return new Promise((resolve, reject) => {
            let data = [];
            const startDate = moment(start, "MM/DD/YYYY");
            const endDate = moment(end, "MM/DD/YYYY");
            if (startDate.diff(endDate) === 0) {
                // THIS IF BLOCK WORKS GOOD
                let dbName = `prediction_${String(locationCode)}_`;
                dbName += startDate.format("YYYY-MM-DD");
                const db = this.cloudant.use(dbName);
                return db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                    data = body.docs;
                    return resolve(data);
                });
            } else {
                // THIS BLOCK IS WHERE THE PROBLEM IS

                // This is to start off the promise chain in the while loop
                let chainProm = Promise.resolve(1);
                let iterator = moment(startDate);
                let count = 0;

                // While loop for the series of promises
                while (iterator.isBefore(endDate) || iterator.isSame(endDate)) {
                    //dbName Format: prediction_0_2019-05-28
                    let dbName = `prediction_${String(locationCode)}_`;
                    dbName += iterator.format("YYYY-MM-DD");
                    const db = this.cloudant.use(dbName);
                    count += 1;

                    // Set off chain of promises
                    chainProm = chainProm.then(() => {
                        setTimeout(()=>{
                            db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                                // Keep adding on to the old array
                                data = data.concat(body.docs);
                            });
                        },count*400);
                    });

                    // Move to the next day
                    iterator.add(1,'days');
                }
                // Once all done resolve with the array of all the documents
                return resolve (data);
            }
        })
    };
</code>```

Basically the output is suppose to be an array of all the documents between the range of dates. Now the single date works, but when I do a range of dates it either the request doesn't not go through, or I hit the limit or it says the promise is never resolved. I don't think this may not be the best way to approach this, and am open to any solution. Any help is greatly appreciated.

答:
Your chainProm is not being connected with the outer call of predQuery - the resolve is being called immediately.

You'll probably find it a lot easier to use async/await instead, the delay-inside-loop logic will be much easier to understand:

```<code>const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
db.predQuery = async (start, end, locationCode) => {
  const startDate = moment(start, "MM/DD/YYYY");
  const endDate = moment(end, "MM/DD/YYYY");
  if (startDate.diff(endDate) === 0) {
    // THIS IF BLOCK WORKS GOOD
    let dbName = `prediction_${String(locationCode)}_`;
    dbName += startDate.format("YYYY-MM-DD");
    const db = this.cloudant.use(dbName);
    const body = await db.find({selector: {_id: {'$gt': 0}}});
    return body.docs;
  }
  const iterator = moment(startDate);
  const data = [];
  const testShouldIterate = () => iterator.isBefore(endDate) || iterator.isSame(endDate);
  let shouldIterate = testShouldIterate();
  while (shouldIterate) {
    //dbName Format: prediction_0_2019-05-28
    let dbName = `prediction_${String(locationCode)}_`;
    dbName += iterator.format("YYYY-MM-DD");
    const db = this.cloudant.use(dbName);
    const body = await db.find({selector: {_id: {'$gt': 0}}});
    data.push(body.docs);
    // Move to the next day
    iterator.add(1,'days');
    shouldIterate = testShouldIterate();
    // Don't delay on the final iteration:
    if (!shouldIterate) {
      break;
    }
    await delay(400);
  }
  // Once all done resolve with the array of all the documents
  return data;
};
</code>```

With this implementation, any errors will be sent to the caller of predQuery (an error will result in the Promise it returns being rejected), so when calling predQuery, make sure to put a catch afterwards.

Body:
I have to make a query to multiple databases in series. Basically a set of promises that have to be completed in series. I am implementing it in a while loop. The databases are named based on dates. I also have to set a request delay of 400ms times the amount of loops passed (400*count) between each promise. If it helps I am using cloudant as my database, similar to mongodb/couchdb but an online instance.

So I have implemented a query function that will take a start and end date and will retrieve all the values in the range. If the dates are the same then it will query one database, otherwise it will query multiple databases for each day between the range of dates. I am mainly having trouble with the else block in the if statement as you can see below.

db.predQuery = (start, end, locationCode) => {
        return new Promise((resolve, reject) => {
            let data = [];
            const startDate = moment(start, "MM/DD/YYYY");
            const endDate = moment(end, "MM/DD/YYYY");
            if (startDate.diff(endDate) === 0) {
                // THIS IF BLOCK WORKS GOOD
                let dbName = `prediction_${String(locationCode)}_`;
                dbName += startDate.format("YYYY-MM-DD");
                const db = this.cloudant.use(dbName);
                return db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                    data = body.docs;
                    return resolve(data);
                });
            } else {
                // THIS BLOCK IS WHERE THE PROBLEM IS

                // This is to start off the promise chain in the while loop
                let chainProm = Promise.resolve(1);
                let iterator = moment(startDate);
                let count = 0;

                // While loop for the series of promises
                while (iterator.isBefore(endDate) || iterator.isSame(endDate)) {
                    //dbName Format: prediction_0_2019-05-28
                    let dbName = `prediction_${String(locationCode)}_`;
                    dbName += iterator.format("YYYY-MM-DD");
                    const db = this.cloudant.use(dbName);
                    count += 1;

                    // Set off chain of promises
                    chainProm = chainProm.then(() => {
                        setTimeout(()=>{
                            db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                                // Keep adding on to the old array
                                data = data.concat(body.docs);
                            });
                        },count*400);
                    });

                    // Move to the next day
                    iterator.add(1,'days');
                }
                // Once all done resolve with the array of all the documents
                return resolve (data);
            }
        })
    };

Basically the output is suppose to be an array of all the documents between the range of dates. Now the single date works, but when I do a range of dates it either the request doesn't not go through, or I hit the limit or it says the promise is never resolved. I don't think this may not be the best way to approach this, and am open to any solution. Any help is greatly appreciated.

Body:
Your chainProm is not being connected with the outer call of predQuery - the resolve is being called immediately.

You'll probably find it a lot easier to use async/await instead, the delay-inside-loop logic will be much easier to understand:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
db.predQuery = async (start, end, locationCode) => {
  const startDate = moment(start, "MM/DD/YYYY");
  const endDate = moment(end, "MM/DD/YYYY");
  if (startDate.diff(endDate) === 0) {
    // THIS IF BLOCK WORKS GOOD
    let dbName = `prediction_${String(locationCode)}_`;
    dbName += startDate.format("YYYY-MM-DD");
    const db = this.cloudant.use(dbName);
    const body = await db.find({selector: {_id: {'$gt': 0}}});
    return body.docs;
  }
  const iterator = moment(startDate);
  const data = [];
  const testShouldIterate = () => iterator.isBefore(endDate) || iterator.isSame(endDate);
  let shouldIterate = testShouldIterate();
  while (shouldIterate) {
    //dbName Format: prediction_0_2019-05-28
    let dbName = `prediction_${String(locationCode)}_`;
    dbName += iterator.format("YYYY-MM-DD");
    const db = this.cloudant.use(dbName);
    const body = await db.find({selector: {_id: {'$gt': 0}}});
    data.push(body.docs);
    // Move to the next day
    iterator.add(1,'days');
    shouldIterate = testShouldIterate();
    // Don't delay on the final iteration:
    if (!shouldIterate) {
      break;
    }
    await delay(400);
  }
  // Once all done resolve with the array of all the documents
  return data;
};

With this implementation, any errors will be sent to the caller of predQuery (an error will result in the Promise it returns being rejected), so when calling predQuery, make sure to put a catch afterwards.


问:
Output result to log file instead of console
Essentially i have this code and currently it prints to the console could someone modify the code so that it creates a log file in the same directory with the data instead</p>

```<code>using System;
using System.Net;
using System.Web;

class CSharpExample
{
  private static string API_KEY = "SAMPLE-KEY";

  public static void Main(string[] args)
  {
    try
    {
    Console.WriteLine(makeAPICall());
    }
    catch (WebException e)
    {
    Console.WriteLine(e.Message);
    }
  }

  static string makeAPICall()
  {
    var URL = new UriBuilder("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest");

    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString["start"] = "1";
    queryString["limit"] = "5000";
    queryString["convert"] = "USD";

    URL.Query = queryString.ToString();

    var client = new WebClient();
    client.Headers.Add("X-CMC_PRO_API_KEY", API_KEY);
    client.Headers.Add("Accepts", "application/json");
    return client.DownloadString(URL.ToString());

  }
}
</code>```

答:
You can use File.AppendAllText instead of Console.WriteLine to append text to a file (and it will create the file if it doesn't exist) instead of writing it to the console window. Pass the file path (or just the file name) as the first argument, and the text you want to add as the second argument. If you just pass a file name, it will use the path of your executable as the path.

Note that I added + Environment.NewLine to the end of the string so that each call writes a new line to the file instead of appending directly to the last line in the file.

For example:

```<code>File.AppendAllText("Program_Log.txt", makeAPICall() + Environment.NewLine);
</code>```

After running this line of code, I now have a file named "Program_Log.txt" created in my debug directory (because I was running it from Visual Studio in debug mode) that has the result of the makeAPICall method written to it.

Body:
Essentially i have this code and currently it prints to the console could someone modify the code so that it creates a log file in the same directory with the data instead

using System;
using System.Net;
using System.Web;

class CSharpExample
{
  private static string API_KEY = "SAMPLE-KEY";

  public static void Main(string[] args)
  {
    try
    {
    Console.WriteLine(makeAPICall());
    }
    catch (WebException e)
    {
    Console.WriteLine(e.Message);
    }
  }

  static string makeAPICall()
  {
    var URL = new UriBuilder("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest");

    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString["start"] = "1";
    queryString["limit"] = "5000";
    queryString["convert"] = "USD";

    URL.Query = queryString.ToString();

    var client = new WebClient();
    client.Headers.Add("X-CMC_PRO_API_KEY", API_KEY);
    client.Headers.Add("Accepts", "application/json");
    return client.DownloadString(URL.ToString());

  }
}

Body:
You can use File.AppendAllText instead of Console.WriteLine to append text to a file (and it will create the file if it doesn't exist) instead of writing it to the console window. Pass the file path (or just the file name) as the first argument, and the text you want to add as the second argument. If you just pass a file name, it will use the path of your executable as the path.

Note that I added + Environment.NewLine to the end of the string so that each call writes a new line to the file instead of appending directly to the last line in the file.

For example:

File.AppendAllText("Program_Log.txt", makeAPICall() + Environment.NewLine);

After running this line of code, I now have a file named "Program_Log.txt" created in my debug directory (because I was running it from Visual Studio in debug mode) that has the result of the makeAPICall method written to it.


问:
How to create Dataframe by adding row by row numpy arrays
So I am getting bunch of arrays in streaming fashion that I want to append to a dataframe. I am trying to do it as follows

```<code>df = pd.DataFrame(columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])

outputs = get_outputs()

for xp, yp in zip(outputs, labels):
     ex = np.append(xp, yp)
     print(ex)
     print(ex.shape)
     #trying here to create row-dataframe
     exdf = pd.DataFrame(ex, columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
     #want to append the row to the main dataframe
     df.append(exdf)
</code>```

I get output and error such

```<code>[  4.49039745  -9.63315201   7.70181465 -15.19582367  12.6580925
  -1.17788887  -5.21339655   2.6664052    2.96283174   1.22973883
   6.        ]
(11,)
...
ValueError: Shape of passed values is (11, 1), indices imply (11, 11)
</code>```

How am I supposed to do it?

EDIT:
after incorporating changing in answer

```<code>exdf = pd.DataFrame([ex], columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
print(exdf)
df.append(exdf)
print(df[:1])
</code>```

I receive empty dataframe

```<code>Out
          1         2         3          4  ...         8         9        10    y
0  4.490397 -9.633152  7.701815 -15.195824  ...  2.666405  2.962832  1.229739  6.0

[1 rows x 11 columns]
Empty DataFrame
Columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, y]
Index: []
</code>```

答:
Adding <code>[]</code> in your for loop </p>

```<code> for xp, yp in zip(outputs, labels):
 ex = np.append(xp, yp)
 print(ex)
 print(ex.shape)
 #trying here to create row-dataframe
 exdf = pd.DataFrame([ex], columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
 #want to append the row to the main dataframe
 df=df.append(exdf)
</code>```

Body:
So I am getting bunch of arrays in streaming fashion that I want to append to a dataframe. I am trying to do it as follows

df = pd.DataFrame(columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])

outputs = get_outputs()

for xp, yp in zip(outputs, labels):
     ex = np.append(xp, yp)
     print(ex)
     print(ex.shape)
     #trying here to create row-dataframe
     exdf = pd.DataFrame(ex, columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
     #want to append the row to the main dataframe
     df.append(exdf)

I get output and error such

[  4.49039745  -9.63315201   7.70181465 -15.19582367  12.6580925
  -1.17788887  -5.21339655   2.6664052    2.96283174   1.22973883
   6.        ]
(11,)
...
ValueError: Shape of passed values is (11, 1), indices imply (11, 11)

How am I supposed to do it?

EDIT:
after incorporating changing in answer

exdf = pd.DataFrame([ex], columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
print(exdf)
df.append(exdf)
print(df[:1])

I receive empty dataframe

Out
          1         2         3          4  ...         8         9        10    y
0  4.490397 -9.633152  7.701815 -15.195824  ...  2.666405  2.962832  1.229739  6.0

[1 rows x 11 columns]
Empty DataFrame
Columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, y]
Index: []

Body:
Adding [] in your for loop

 for xp, yp in zip(outputs, labels):
 ex = np.append(xp, yp)
 print(ex)
 print(ex.shape)
 #trying here to create row-dataframe
 exdf = pd.DataFrame([ex], columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
 #want to append the row to the main dataframe
 df=df.append(exdf)