问:
Access the HTML page inside service in AngularJS
I want to access particular HTML page inside a service. Currently, I have made the function inside a controller that can be called from its linked HTML page but I want to access that function from multiple pages. So, I'll want service or factory for it to make it available from anywhere.

In that function, I want the content of particular HTML page but that content is available only when I call the function from that page only.

Here is my function.

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

      var pdf = new jsPDF('p', 'pt', 'a4');
      var source;

      var options = {
         pagesplit: true,
         background: '#ffffff',
         letterRendering: true
      };
      pdf.internal.scaleFactor = 2;

      source = document.getElementsByClassName('complete-report')[0];

      pdf.addHTML(source, options, function () {
        pdf.save('report.pdf');
      });
  };
</code>```

document.getElementsByClassName('complete-report')[0]; It will get data from the HTML page linked with controller.

So, I need service which access the particular HTML page such that I use that function there to get the content of particular HTML page.

答:
As pointed to wprzechodzen, you shouldn't access directly your HTML inside a service but, instead, you should pass only source variable.

However, if you want to access HTML in service you have to do something like this:

```<code>yourApp.controller('something', function($scope, $window, $document, yourServiceName){
  yourServiceName.yourFunction($document)
})

yourApp.factory('yourServiceName', function(){
  return {
    yourFunction: function(doc){
       //here you get  $document
    }
  }
})
</code>```

Here's the $document's docs

Body:
I want to access particular HTML page inside a service. Currently, I have made the function inside a controller that can be called from its linked HTML page but I want to access that function from multiple pages. So, I'll want service or factory for it to make it available from anywhere.

In that function, I want the content of particular HTML page but that content is available only when I call the function from that page only.

Here is my function.

$scope.downloadReport = function(type) {

      var pdf = new jsPDF('p', 'pt', 'a4');
      var source;

      var options = {
         pagesplit: true,
         background: '#ffffff',
         letterRendering: true
      };
      pdf.internal.scaleFactor = 2;

      source = document.getElementsByClassName('complete-report')[0];

      pdf.addHTML(source, options, function () {
        pdf.save('report.pdf');
      });
  };

document.getElementsByClassName('complete-report')[0]; It will get data from the HTML page linked with controller.

So, I need service which access the particular HTML page such that I use that function there to get the content of particular HTML page.

Body:
As pointed to wprzechodzen, you shouldn't access directly your HTML inside a service but, instead, you should pass only source variable.

However, if you want to access HTML in service you have to do something like this:

yourApp.controller('something', function($scope, $window, $document, yourServiceName){
  yourServiceName.yourFunction($document)
})

yourApp.factory('yourServiceName', function(){
  return {
    yourFunction: function(doc){
       //here you get  $document
    }
  }
})

Here's the $document's docs


来源: stackexchange

问:
Master and Worker Clustering: On which core is the Master running?
On the documentation-page of Node.js clusters there are some examples where the workers are "spawned" like this:

```<code>  // Start workers and listen for messages containing notifyRequest
  const numCPUs = require('os').cpus().length;
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
</code>```

This means that for every CPU - core one worker is spawned, right?
On which CPU-Core is the master ? Node.js is single threaded so if there is only one master then there has to be 2 processes on at least one CPU - Core because the master has to run on one of the CPU-Cores. Is my assumption correct?

答:
Hope this helps taken from How do multi core processors handle programs

Check second paragraph. Its say about Single CPU programs like NodeJs.

Each CPU Core has a pre-determined number of threads, for example, a
  dual core CPU could potentially have 4 threads (Hyper-threading),
  meaning that any given program running will use its assigned amount of
  CPU resources on an assigned core. (Resource assignment is determined
  primarily by the system itself, and whether or not the user, and
  therefore the CPU has assigned resources to the workload). the CPU
  threads, and cores, all run at the CPU's rated frequency, that is,
  billion cycles per second. The faster the clock speed, the faster
  processes are completed. A CPU with more cores can split its workload
  more efficiently. For example, an 8 Core processor running at 1.5 Ghz
  may indeed complete a process quicker, if the process is using all 8
  cores at once. BUT, a single threaded program (A program using only
  one thread), will take a much higher advantage of a CPU with say 2
  cores running at 3 Ghz.

If two programs are open that are programmed to use only 1 CPU Core,
  the Program with the highest priority will be assigned to Core 0 (Core
  zero is the first core). Any other programs that are open will be
  assigned to the processor core that will complete the process
  quickest. More often than not, the computers operating system will
  work relatively well to split workloads across multiple cores,
  unfortunately, some programs are only programmed to take advantage of
  one core. If this is the case, the program likely does not need
  multiple cores, unlike a video editing program or 3D development
  program.

If 8 programs were open at once, and if they were all using a
  considerable amount of CPU resources, on a 4 core CPU, for 1, the
  computer would be noticeably slower than if it were idle. Each process
  will be given an assigned amount of CPU resources, and each program
  would be prioritised accordingly, and instructions would be stored in
  the CPU's cache, but if the programs open are using 100% of the CPU's
  usage, and is running at its maximum frequency, then the programs will
  slow down, as they will be held in a 'queue' and a considerable delay
  would be implied until the CPU has completed its instructions. Note, a
  similar effect can be witnessed when downloading files; 8 simultaneous
  downloads will download slower than 2, if the files are reaching the
  download speed limit.

Hope this helps, and as a general rule of thumb, for basic
  applications, CPU Speed is more important than core count, although
  generally speaking, a CPU with 2 or more cores is pretty good for
  general use.

ContentLicense: CC BY-SA 3.0

Body:
On the documentation-page of Node.js clusters there are some examples where the workers are "spawned" like this:

  // Start workers and listen for messages containing notifyRequest
  const numCPUs = require('os').cpus().length;
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

This means that for every CPU - core one worker is spawned, right?
On which CPU-Core is the master ? Node.js is single threaded so if there is only one master then there has to be 2 processes on at least one CPU - Core because the master has to run on one of the CPU-Cores. Is my assumption correct?


问:
Remove tracking branches no longer on remote
Is there a simple way to delete all tracking branches whose remote equivalent no longer exists?

Example:

Branches (local and remote)

master

origin/master

origin/bug-fix-a

origin/bug-fix-b

origin/bug-fix-c

Locally, I only have a master branch. Now I need to work on bug-fix-a, so I check it out, work on it, and push changes to the remote. Next I do the same with bug-fix-b.

Branches (local and remote)

master

bug-fix-a

bug-fix-b

origin/master

origin/bug-fix-a

origin/bug-fix-b

origin/bug-fix-c

Now I have local branches master, bug-fix-a, bug-fix-b. The Master branch maintainer will merge my changes into master and delete all branches he has already merged.

So the current state is now:

Branches (local and remote)

master

bug-fix-a

bug-fix-b

origin/master

origin/bug-fix-c

Now I would like to call some command to delete branches (in this case bug-fix-a, bug-fix-b), which are no longer represented in the remote repository.

It would be something like the existing command git remote prune origin, but more like git local prune origin.

答:
I use a short method to do the trick, I recommend you to do the same as it could save some hours & give you more visibility

Just add the following snippet into your .bashrc (.bashprofile on macos).

```<code>git-cleaner() { git fetch --all --prune && git branch --merged | grep -v -E "\bmaster|preprod|dmz\b" | xargs -n 1 git branch -d ;};
</code>```

Fetch all remotes

Get only merged branches from git

Remove from this list the "protected / important" branches

Remove the rest (e.g, clean and merged branches)

You'll have to edit the grep regex in order to fit to your needs (here, it prevent master, preprod and dmz from deletion)

ContentLicense: CC BY-SA 4.0

Body:
I use a short method to do the trick, I recommend you to do the same as it could save some hours & give you more visibility

Just add the following snippet into your .bashrc (.bashprofile on macos).

git-cleaner() { git fetch --all --prune && git branch --merged | grep -v -E "\bmaster|preprod|dmz\b" | xargs -n 1 git branch -d ;};

Fetch all remotes

Get only merged branches from git

Remove from this list the "protected / important" branches

Remove the rest (e.g, clean and merged branches)

You'll have to edit the grep regex in order to fit to your needs (here, it prevent master, preprod and dmz from deletion)


问:
Title bar contents becomes blank/invisible in chrome
Ext JS : ver 6.5.2.463 theme-classic (6.2.1.167)
Browser : Chrome Version 62.0.3202.94 (64-bit)
OS : Window 10 (64bit)

Few days ago I start my application as usual but encounter an awkward behavior when I opened already collapsed panel in Chrome its title bar text was blank. I tried in on another browser it was working fine there.
I tried it on another machine it was working fine there. but when the Chrome of other machine get updated the same problem is there too.
we updated our Ext JS version from 6.2.1.167(Classic) to 6.5.2.463(Classic) but the problem is still there.
we create the similar UI on the fiddle and link is attached. so you can verify it.
https://fiddle.sencha.com/#fiddle/2acg&view/editor
is there anyone else facing the same issue ?
To reproduce the issue:
1. Open the link to a fiddle.
2. Click on the expand button the title bar content will be shown.
3. Now click on the collapse then expand now content will disappear.

Screenshots are also attached.
title bar is blank there

答:
You need to go though with this config collapseMode and also with code file of collapseMode.

In this FIDDLE, I have used your code and made some change as per your requirement. Hope this will help you or guide you to solve your problem.

```<code>Ext.create('Ext.panel.Panel', {
    plugins: 'viewport',
    title: 'ViewPort Title',
    layout: 'fit',
    tbar: [{
        xtype: 'button',
        text: 'Expand',
        handler: function () {
            var panel = this.up('panel').down('#bottomPanel');
            panel.collapseMode = undefined;
            panel.expand();
        }
    }, {
        xtype: 'button',
        text: 'Collapse',
        handler: function () {
            this.up('panel').down('#bottomPanel').collapse();
        }
    }],
    items: [{
        xtype: 'container',
        layout: 'border',
        items: [{
            xtype: 'panel',
            title: 'Center Panel Title',
            region: 'center',
            html: 'Sample center panel text'
        }, {
            xtype: 'panel',
            itemId: 'bottomPanel',
            title: 'Bottom Panel Title',
            region: 'south',
            height: 150,
            collapsible: true,
            collapseMode: 'mini',
            collapsed: true,
            layout: 'fit',
            items: [{
                xtype: 'panel',
                html: 'Sample bottom inner panel text'
            }]
        }]
    }]
});
</code>```

Body:
You need to go though with this config collapseMode and also with code file of collapseMode.

In this FIDDLE, I have used your code and made some change as per your requirement. Hope this will help you or guide you to solve your problem.

Ext.create('Ext.panel.Panel', {
    plugins: 'viewport',
    title: 'ViewPort Title',
    layout: 'fit',
    tbar: [{
        xtype: 'button',
        text: 'Expand',
        handler: function () {
            var panel = this.up('panel').down('#bottomPanel');
            panel.collapseMode = undefined;
            panel.expand();
        }
    }, {
        xtype: 'button',
        text: 'Collapse',
        handler: function () {
            this.up('panel').down('#bottomPanel').collapse();
        }
    }],
    items: [{
        xtype: 'container',
        layout: 'border',
        items: [{
            xtype: 'panel',
            title: 'Center Panel Title',
            region: 'center',
            html: 'Sample center panel text'
        }, {
            xtype: 'panel',
            itemId: 'bottomPanel',
            title: 'Bottom Panel Title',
            region: 'south',
            height: 150,
            collapsible: true,
            collapseMode: 'mini',
            collapsed: true,
            layout: 'fit',
            items: [{
                xtype: 'panel',
                html: 'Sample bottom inner panel text'
            }]
        }]
    }]
});


问:
Batch Normalization - Tensorflow
I have looked at a few BN examples but still am a bit confused. So I am currently using this function which calls the function here;

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard4/tf.contrib.layers.batch_norm.md

```<code>from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
import tensorflow as tf

def bn(x,is_training,name):
    bn_train = batch_norm(x, decay=0.9, center=True, scale=True,
    updates_collections=None,
    is_training=True,
    reuse=None,
    trainable=True,
    scope=name)
    bn_inference = batch_norm(x, decay=1.00, center=True, scale=True,
    updates_collections=None,
    is_training=False,
    reuse=True,
    trainable=False,
    scope=name)
    z = tf.cond(is_training, lambda: bn_train, lambda: bn_inference)
    return z
</code>```

This following part is a toy run where I am just checking that the function reuses the means and variances calculated in a training step for two features. Running this part of the code in test mode i.e. is_training=False, the running mean/variances calculated in the training step are changing which can be seen when we print out the BN variables which I get from calling bnParams

```<code>if __name__ == "__main__":
    print("Example")

    import os
    import numpy as np
    import scipy.stats as stats
    np.set_printoptions(suppress=True,linewidth=200,precision=3)
    np.random.seed(1006)
    import pdb
    path = "batchNorm/"
    if not os.path.exists(path):
        os.mkdir(path)
    savePath = path + "bn.model"

    nFeats = 2
    X = tf.placeholder(tf.float32,[None,nFeats])
    is_training = tf.placeholder(tf.bool,name="is_training")
    Y = bn(X,is_training=is_training,name="bn")
    mvn = stats.multivariate_normal([0,100])
    bs = 4
    load = 0
    train = 1
    saver = tf.train.Saver()
    def bnCheck(batch,mu,std):
        # Checking calculation
        return (x - mu)/(std + 0.001)
    with tf.Session() as sess:
        if load == 1:
            saver.restore(sess,savePath)
        else:
            tf.global_variables_initializer().run()
        #### TRAINING #####
        if train == 1:
            for i in xrange(100):
                x = mvn.rvs(bs)
                y = Y.eval(feed_dict={X:x, is_training.name: True})

        def bnParams():
            beta, gamma, mean, var = [v.eval() for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope="bn")]
            return beta, gamma, mean, var

        beta, gamma, mean, var = bnParams()
        #### TESTING #####
        for i in xrange(10):
            x = mvn.rvs(1).reshape(1,-1)
            check = bnCheck(x,mean,np.sqrt(var))
            y = Y.eval(feed_dict={X:x, is_training.name: False})
            print("x = {0}, y = {1}, check = {2}".format(x,y,check))
            beta, gamma, mean, var = bnParams()
            print("BN Params: Beta {0} Gamma {1} mean {2} var{3} \n".format(beta,gamma,mean,var))

        saver.save(sess,savePath)
</code>```

The first three iterations of test loop look as follows;

```<code>x = [[  -1.782  100.941]], y = [[-1.843  1.388]], check = [[-1.842  1.387]]
BN Params: Beta [ 0.  0.] Gamma [ 1.  1.] mean [ -0.2   99.93] var[ 0.818  0.589]

x = [[  -1.245  101.126]], y = [[-1.156  1.557]], check = [[-1.155  1.557]]
BN Params: Beta [ 0.  0.] Gamma [ 1.  1.] mean [  -0.304  100.05 ] var[ 0.736  0.53 ]

x = [[ -0.107  99.349]], y = [[ 0.23  -0.961]], check = [[ 0.23 -0.96]]
BN Params: Beta [ 0.  0.] Gamma [ 1.  1.] mean [ -0.285  99.98 ] var[ 0.662  0.477]
</code>```

I am not doing BP so beta and gamma won't change. However my running means/variances are changing. Where am I going wrong?

EDIT:
It would be good to know why these variables need/do not need changing between test and train;

```<code>updates_collections, reuse, trainable
</code>```

答: When you use slim.batch_norm,be sure to use slim.learning.create_train_op instead of tf.train.GradientDecentOptimizer(lr).minimize(loss) or other optimizer. Try it to see if it works!

Title: Batch Normalization - Tensorflow

Body:
I have looked at a few BN examples but still am a bit confused. So I am currently using this function which calls the function here;

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard4/tf.contrib.layers.batch_norm.md

from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
import tensorflow as tf

def bn(x,is_training,name):
    bn_train = batch_norm(x, decay=0.9, center=True, scale=True,
    updates_collections=None,
    is_training=True,
    reuse=None,
    trainable=True,
    scope=name)
    bn_inference = batch_norm(x, decay=1.00, center=True, scale=True,
    updates_collections=None,
    is_training=False,
    reuse=True,
    trainable=False,
    scope=name)
    z = tf.cond(is_training, lambda: bn_train, lambda: bn_inference)
    return z

This following part is a toy run where I am just checking that the function reuses the means and variances calculated in a training step for two features. Running this part of the code in test mode i.e. is_training=False, the running mean/variances calculated in the training step are changing which can be seen when we print out the BN variables which I get from calling bnParams

if __name__ == "__main__":
    print("Example")

    import os
    import numpy as np
    import scipy.stats as stats
    np.set_printoptions(suppress=True,linewidth=200,precision=3)
    np.random.seed(1006)
    import pdb
    path = "batchNorm/"
    if not os.path.exists(path):
        os.mkdir(path)
    savePath = path + "bn.model"

    nFeats = 2
    X = tf.placeholder(tf.float32,[None,nFeats])
    is_training = tf.placeholder(tf.bool,name="is_training")
    Y = bn(X,is_training=is_training,name="bn")
    mvn = stats.multivariate_normal([0,100])
    bs = 4
    load = 0
    train = 1
    saver = tf.train.Saver()
    def bnCheck(batch,mu,std):
        # Checking calculation
        return (x - mu)/(std + 0.001)
    with tf.Session() as sess:
        if load == 1:
            saver.restore(sess,savePath)
        else:
            tf.global_variables_initializer().run()
        #### TRAINING #####
        if train == 1:
            for i in xrange(100):
                x = mvn.rvs(bs)
                y = Y.eval(feed_dict={X:x, is_training.name: True})

        def bnParams():
            beta, gamma, mean, var = [v.eval() for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope="bn")]
            return beta, gamma, mean, var

        beta, gamma, mean, var = bnParams()
        #### TESTING #####
        for i in xrange(10):
            x = mvn.rvs(1).reshape(1,-1)
            check = bnCheck(x,mean,np.sqrt(var))
            y = Y.eval(feed_dict={X:x, is_training.name: False})
            print("x = {0}, y = {1}, check = {2}".format(x,y,check))
            beta, gamma, mean, var = bnParams()
            print("BN Params: Beta {0} Gamma {1} mean {2} var{3} \n".format(beta,gamma,mean,var))

        saver.save(sess,savePath)

The first three iterations of test loop look as follows;

x = [[  -1.782  100.941]], y = [[-1.843  1.388]], check = [[-1.842  1.387]]
BN Params: Beta [ 0.  0.] Gamma [ 1.  1.] mean [ -0.2   99.93] var[ 0.818  0.589]

x = [[  -1.245  101.126]], y = [[-1.156  1.557]], check = [[-1.155  1.557]]
BN Params: Beta [ 0.  0.] Gamma [ 1.  1.] mean [  -0.304  100.05 ] var[ 0.736  0.53 ]

x = [[ -0.107  99.349]], y = [[ 0.23  -0.961]], check = [[ 0.23 -0.96]]
BN Params: Beta [ 0.  0.] Gamma [ 1.  1.] mean [ -0.285  99.98 ] var[ 0.662  0.477]

I am not doing BP so beta and gamma won't change. However my running means/variances are changing. Where am I going wrong?

EDIT:
It would be good to know why these variables need/do not need changing between test and train;

updates_collections, reuse, trainable


问:
Reactstrap Card component throws error
The issue is with the reactstrap cards: https://reactstrap.github.io/components/card/

Using reactstrap components like Card, etc is not working.

Component: Version I

```<code>import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;
</code>```

Output: *It works fine without any errors.

But when I try to use the rest of the components from reactstrap. It throws errors on console.

Component: Version II

```<code>import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                    <CardBody>
                        <CardTitle>Card title</CardTitle>
                        <CardSubtitle>Card subtitle</CardSubtitle>
                        <CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
                        <Button>Button</Button>
                    </CardBody>
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;
</code>```

Output:

package.json

```<code>{
  "name": "client",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-transition-group": "^2.2.1",
    "reactstrap": "^4.8.0",
    "redux": "^3.7.2",
    "redux-promise": "^0.5.3"
  }
}
</code>```

I am not able to debug this issue. Please help! TIA.

答:
The components such as CardBody, etc are not available in v4.8.0.

Upgrading to latest release (reactstrap v5.0.0-alpha.4) resolves this issue!

npm install --save reactstrap@5.0.0-alpha.4

Refer to the issue that I created on reactstrap@github for more details:
https://github.com/reactstrap/reactstrap/issues/730

Title: Reactstrap Card component throws error

Body:
The issue is with the reactstrap cards: https://reactstrap.github.io/components/card/

Using reactstrap components like Card, etc is not working.

Component: Version I

import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;

Output: *It works fine without any errors.

But when I try to use the rest of the components from reactstrap. It throws errors on console.

Component: Version II

import React, { Component } from 'react';
import { Card, Button, CardImg, CardTitle, CardText, CardDeck, CardSubtitle, CardBody } from 'reactstrap';

class MoviesIndex extends Component {

    render() {
        return (
            <CardDeck>
                <Card>
                    <CardImg top width="100%" src="" alt="Movie Poster" />
                    <CardBody>
                        <CardTitle>Card title</CardTitle>
                        <CardSubtitle>Card subtitle</CardSubtitle>
                        <CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
                        <Button>Button</Button>
                    </CardBody>
                </Card>
            </CardDeck>
        );
    }
}

export default MoviesIndex;

Output:

package.json

{
  "name": "client",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-transition-group": "^2.2.1",
    "reactstrap": "^4.8.0",
    "redux": "^3.7.2",
    "redux-promise": "^0.5.3"
  }
}

I am not able to debug this issue. Please help! TIA.


问:
Confusion with string pointers
```<code>#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}
</code>```

The output is: C is here.

Can anyone explain this to me its confusing me.

答:
First of all, string literals only separated by white-space (and comments) are concatenated into single strings. This happens before expression parsing (see e.g. this translation phase reference for more information). This means that the expression *(1+"AB" "CD"+1) is really parsed as *(1+"ABCD"+1).

The second thing to remember is that string literals like "ABCD" are really read-only arrays, and as such one can use normal array-indexing with them,  or letting them decay to pointers to their first element.

The third thing is that for any array or pointer p and index i, the expression *(p + i) is equal to p[i]. That means *(1+"ABCD"+1) (which is really the same as *("ABCD"+2)) is the same as "ABCD"[2]. Which gives you the third character in the string. And the third character in the string is 'C'.

Title: Confusion with string pointers

Body:
#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}

The output is: C is here.

Can anyone explain this to me its confusing me.


问:
Reverse linked list returning new linked list
I need to implement a function that reverses a linked list but i don't know how to return a newly formed linked list as a result.

```<code>typedef struct node_t* Node;

struct node_t {
    int n;
    Node next;
};

// create a new node with value n
Node nodeCreate(int n)
{
    Node node = malloc(sizeof(*node));
    if (node == NULL) return NULL;

    node->n = n;
    node->next = NULL;

    return node;
}

// reversing the linked list
Node reverseList(Node list)
{
    if (list == NULL) return NULL;

    Node current, prev, next;
    current = rev_head;
    prev = NULL;

    while( current != NULL)
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    list = prev;
    return list;
}
</code>```

This is the code I have written so far.

How do I insert this reverse linked list into a different new linked list within the function reverseList it self?

答:
You can simply create a new node for every node in the original list and set the link in opposite order. Code could be:</p>

```<code>Node createReversedList(Node node) {
    Node result = NULL;
    while (node != NULL) {
        Node n = nodeCreate(node->n);
        n->next = result;
        result = n;
        node = node->next;
    }
    return result;
}
</code>```

Body:
I need to implement a function that reverses a linked list but i don't know how to return a newly formed linked list as a result.

typedef struct node_t* Node;

struct node_t {
    int n;
    Node next;
};

// create a new node with value n
Node nodeCreate(int n)
{
    Node node = malloc(sizeof(*node));
    if (node == NULL) return NULL;

    node->n = n;
    node->next = NULL;

    return node;
}

// reversing the linked list
Node reverseList(Node list)
{
    if (list == NULL) return NULL;

    Node current, prev, next;
    current = rev_head;
    prev = NULL;

    while( current != NULL)
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    list = prev;
    return list;
}

This is the code I have written so far.

How do I insert this reverse linked list into a different new linked list within the function reverseList it self?

Body:
You can simply create a new node for every node in the original list and set the link in opposite order. Code could be:

Node createReversedList(Node node) {
    Node result = NULL;
    while (node != NULL) {
        Node n = nodeCreate(node->n);
        n->next = result;
        result = n;
        node = node->next;
    }
    return result;
}


问:
Jenkins pipeline starting and stopping a runtime environment
I am using Jenkins pipeline script for an job. I want to start a runtime env before a stage execution and stop it after the stage finishes. E.g. start a mongo db before the stage and stop after the stage which uses mongodb  ( Don't want to put start and stop inside the stage script).

I found wrap option in pipeline but it has some predefined option and I cannot start my runtime inside it.

I also tried using a parallel stage and started the runtime in it. But was not able to stop the stage(runtime) when the maine stage finished

Any other way to achieve the same

答:
Some of these types of actions you may want to delegate down to your scripts instead of orchestrating at the Jenkins Pipeline leve, so should be kept in mind. One way would be to use a try/catch/finally or try/finally structure to control the build flow.

```<code>try {
  // Prep database
  stage('mystage') {
    // Do work that may fail
  }
finally {
  // Clean up actions
}
</code>```

You can also use combinations of the sh/bat step that have the returnStatus and returnStdOut options to orchestrate your build pipeline.

Body:
Some of these types of actions you may want to delegate down to your scripts instead of orchestrating at the Jenkins Pipeline leve, so should be kept in mind. One way would be to use a try/catch/finally or try/finally structure to control the build flow.

try {
  // Prep database
  stage('mystage') {
    // Do work that may fail
  }
finally {
  // Clean up actions
}

You can also use combinations of the sh/bat step that have the returnStatus and returnStdOut options to orchestrate your build pipeline.


问:
MYSQL and phpmyadmin not allowing me to create user table
im trying to create a table using mysql and phpmyadmin with the w

```<code>CREATE DATABASE android_api

USE 'android_api'
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
unique_id VARCHAR(23) NOT NULL UNIQUE,
NAME VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
encrypted_password VARCHAR(80) NOT NULL,
salt VARCHAR(10) NOT NULL,
created_at DATETIME,
updated_at DATETIME NULL
);
</code>```

but i keep recieving an error :

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'USE 'android_api'
      CREATE TABLE users(
      id INT(11) PRIMARY KEY AUTO_INCREMEN' at line 3

i was wondering if anybody could help me

NOTE - i have tried putting '' around the database name and id, unique_id and so on.

答:
Try this:

```<code>CREATE DATABASE android_api;

USE android_api;

CREATE TABLE users(
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    unique_id VARCHAR(23) NOT NULL UNIQUE,
    NAME VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    encrypted_password VARCHAR(80) NOT NULL,
    salt VARCHAR(10) NOT NULL,
    created_at DATETIME,
    updated_at DATETIME NULL
</code>```

);

It should work like this:

```<code>mysql-sql> use android_api;
Query OK, 0 rows affected (0.00 sec)
mysql-sql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| android_api        |
| devel              |
[...]
+--------------------+
</code>```

Can verify you created the table

```<code>mysql-sql> show tables;
+-----------------------+
| Tables_in_android_api |
+-----------------------+
| users                 |
+-----------------------+
1 row in set (0.00 sec)
</code>```

Body:
im trying to create a table using mysql and phpmyadmin with the w

CREATE DATABASE android_api

USE 'android_api'
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
unique_id VARCHAR(23) NOT NULL UNIQUE,
NAME VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
encrypted_password VARCHAR(80) NOT NULL,
salt VARCHAR(10) NOT NULL,
created_at DATETIME,
updated_at DATETIME NULL
);

but i keep recieving an error :

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'USE 'android_api'
      CREATE TABLE users(
      id INT(11) PRIMARY KEY AUTO_INCREMEN' at line 3

i was wondering if anybody could help me

NOTE - i have tried putting '' around the database name and id, unique_id and so on.

Body:
Try this:

CREATE DATABASE android_api;

USE android_api;

CREATE TABLE users(
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    unique_id VARCHAR(23) NOT NULL UNIQUE,
    NAME VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    encrypted_password VARCHAR(80) NOT NULL,
    salt VARCHAR(10) NOT NULL,
    created_at DATETIME,
    updated_at DATETIME NULL

);

It should work like this:

mysql-sql> use android_api;
Query OK, 0 rows affected (0.00 sec)
mysql-sql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| android_api        |
| devel              |
[...]
+--------------------+

Can verify you created the table

mysql-sql> show tables;
+-----------------------+
| Tables_in_android_api |
+-----------------------+
| users                 |
+-----------------------+
1 row in set (0.00 sec)


问:
How to create a database from existing Database without any data?
I want to create a database from existing one without taking any data from it (only schema). I know, I can create a script for this purpose using SQL Server Management Studio, but I need some transact SQL script doing this dynamically</p>

答:
Were I to need to do this, this is the approach I'd use. This is not a trivial task and the built in scripting tools are better suited as has been noted. However, this is the approach I'd use if I had to do it.

Step 1 - Build tables - Build a cursor for all your tables using:

```<code>SELECT object_schema_name([object_id]), [name]
FROM   [sys].[objects]
WHERE  [type] IN ( N'U' )
ORDER  BY [name];
</code>```

Step through each and build dynamic SQL to "SELECT * INTO .. from ..

Step 2 - Build procedures and functions - Build a cursor using:

```<code>SELECT [name]
FROM   [sys].[objects]
WHERE  [type] IN ( N'P', N'TF', N'FN', N'IF' )
ORDER  BY [name];
</code>```

Step through the objects and run "exec sp_helptext '.'" on each. Catenate the resultant lines using a COALESCE string builder and execute the result. Execute the result on your target database.

Body:
Were I to need to do this, this is the approach I'd use. This is not a trivial task and the built in scripting tools are better suited as has been noted. However, this is the approach I'd use if I had to do it.

Step 1 - Build tables - Build a cursor for all your tables using:

SELECT object_schema_name([object_id]), [name]
FROM   [sys].[objects]
WHERE  [type] IN ( N'U' )
ORDER  BY [name];

Step through each and build dynamic SQL to "SELECT * INTO .. from ..

Step 2 - Build procedures and functions - Build a cursor using:

SELECT [name]
FROM   [sys].[objects]
WHERE  [type] IN ( N'P', N'TF', N'FN', N'IF' )
ORDER  BY [name];

Step through the objects and run "exec sp_helptext '.'" on each. Catenate the resultant lines using a COALESCE string builder and execute the result. Execute the result on your target database.


问:
How to convert PDF file to KML file
Is there a way to convert a map pdf file to a kml file? How can I convert it or is there any guidelines to do so?</p>

答:
Apache PDFBox is an open source Java library that can parse PDF document and extract content. The API includes methods to extract text, metadata, and embedded files from PDF files as well create PDF files from scratch. Apache PDFBox also includes several command-line utilities. One command-line tool called pdfbox-app has options to extract all text or images from PDF files.

There is also Apache Tika library which focuses solely on text extraction from a variety of file formats including PDF.

Title: How to convert PDF file to KML file


问:
Toggle class on click body
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

答:
To fix this you can check which element raised the click event that bubbled up the DOM. If it was not within the .col-search then you can toggle the class.

Also note that this logic makes your removeClass variable redundant.

$(".btn-search").click(function(e) {
  e.stopPropagation();
  $(".input-search").toggleClass('expanded');
});

$("html").click(function(e) {
  if ($(e.target).closest('.col-search').length == 0)
    $(".input-search").removeClass('expanded');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color: #fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

Title: Toggle class on click body

Body:
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

Body:
To fix this you can check which element raised the click event that bubbled up the DOM. If it was not within the .col-search then you can toggle the class.

Also note that this logic makes your removeClass variable redundant.

$(".btn-search").click(function(e) {
  e.stopPropagation();
  $(".input-search").toggleClass('expanded');
});

$("html").click(function(e) {
  if ($(e.target).closest('.col-search').length == 0)
    $(".input-search").removeClass('expanded');
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-search">
  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">
</div>


问:
Vertical Owl Carousel Slider
I am using Owl Carousel plugin in my website and I want to create a vertical slider with this. Overall layout for a section looks like this. I'm also using Bootstrap. However, creating a vertical slider as in the image is quite tricky part and I need your help for this.

$(function() {
  var owl = $('.history .owl-carousel');
  owl.owlCarousel({
    stagePadding: 0,
    margin: 15,
    loop: true,
    dots: false,
    nav: true,
    navText: [
      "",
      ""
    ],
    items: 3,
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box_area {
  width: 100%;
  margin: 10px auto 50px auto;
  font-size: 0px;
  letter-spacing: 0px;
  word-spacing: 0px;
}

.box_area:after {
  display: block;
  content: "";
  clear: both;
}

.leftarea {
  height: 500px;
}

.rightarea {
  height: 500px;
}

.rightarea img {
  width: 100%;
}</code>```

My Performance History

```

答:
I could not get your code working, so i made a quick setup.

Give the images that you want on the right a display: block; this will make them sit underneath each other.

I hope this helps.

.img-list img {
  display: block;
  padding: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="float: left;">
  <img src="http://via.placeholder.com/350x150" />
</div>
<div class="img-list">
  <img style="max-width: 20%;" src="http://via.placeholder.com/350x150" />
  <img style="max-width: 20%;" src="http://via.placeholder.com/350x150" />
</div></code>```

Title: Vertical Owl Carousel Slider

Body:
I am using Owl Carousel plugin in my website and I want to create a vertical slider with this. Overall layout for a section looks like this. I'm also using Bootstrap. However, creating a vertical slider as in the image is quite tricky part and I need your help for this.

$(function() {
  var owl = $('.history .owl-carousel');
  owl.owlCarousel({
    stagePadding: 0,
    margin: 15,
    loop: true,
    dots: false,
    nav: true,
    navText: [
      "",
      ""
    ],
    items: 3,
  });
});

.box_area {
  width: 100%;
  margin: 10px auto 50px auto;
  font-size: 0px;
  letter-spacing: 0px;
  word-spacing: 0px;
}

.box_area:after {
  display: block;
  content: "";
  clear: both;
}

.leftarea {
  height: 500px;
}

.rightarea {
  height: 500px;
}

.rightarea img {
  width: 100%;
}

My Performance History

Body:
I could not get your code working, so i made a quick setup.

Give the images that you want on the right a display: block; this will make them sit underneath each other.

I hope this helps.

.img-list img {
  display: block;
  padding: 8px;
}

<div style="float: left;">
  <img src="http://via.placeholder.com/350x150" />
</div>
<div class="img-list">
  <img style="max-width: 20%;" src="http://via.placeholder.com/350x150" />
  <img style="max-width: 20%;" src="http://via.placeholder.com/350x150" />
</div>


问:
Select and Update Query MSQL
I have a table named BOOK

I need a query that will discount the price of books by 10%, list the Book Code(PK),the Book Title and Discounted Price of each book.

I need to then change the price column to 'Discounted Price' as the name for the computed column.

I currently have

```<code>UPDATE BOOK SET PRICE = PRICE*0.9
SELECT CONCAT(PRICE) AS Discounted_Price,BOOK_CODE, BOOK_TITLE;
</code>```

But I am getting an error message.

答:
please try the query below:

UPDATE BOOK set PRICE = (PRICE * 0.9); Select PRICE as Discounter_Price, BOOK_CODE,BOOK_TITLE from BOOK;

Title: Select and Update Query MSQL

Body:
I have a table named BOOK

I need a query that will discount the price of books by 10%, list the Book Code(PK),the Book Title and Discounted Price of each book.

I need to then change the price column to 'Discounted Price' as the name for the computed column.

I currently have

UPDATE BOOK SET PRICE = PRICE*0.9
SELECT CONCAT(PRICE) AS Discounted_Price,BOOK_CODE, BOOK_TITLE;

But I am getting an error message.


问:
Is this a violation of the Law of Demeter? vs. readable code
The code below brakes apparently the Law of Demeter, i.e. methods getServer().methodx(...). From other side it looks pretty compact = better readable?

```<code>abstract class BaseManager {
    ResultSet find(String searchText) {
        return getServer().find(searchText);
    }

    ResultSet fetch(String fetchText) {
        return getServer().fetch(fetchText);
    }

    void save(String saveText) {
        getServer().save(saveText);
    }

    abstract BaseManager getServer();
}

class Server1Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server1;
    }
}

class Server2Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server2;
    }
}
</code>```

If the law is violated, them how to refactor this code?
Many thanks in advance.

答:
The code below brakes [sic] apparently the Law of Demeter, i.e.
  methods getServer().methodx(...). From other side it looks pretty
  compact = better readable?

The point of your design is lost on me.  If compactness is your goal, then would not this be even better?

```<code>class Manager {
    private Server server;

    public Manager(Server server) {
        this.server = server;
    }

    ResultSet find(String searchText) {
        server.find(searchText);
    }

    ResultSet fetch(String fetchText) {
        server.fetch(fetchText);
    }

    void save(String saveText) {
        server.save(saveText);
    }
}
</code>```

In addition to being even more compact and clear, that happens to conform to the Law of Demeter.  Moreover, it follows the principle of preferring composition over inheritance, which I think you'll see is favored (but not implied) by the Law of Demeter.

If the law is violated, them how to refactor this code?

I'm still liking what I presented above.

Is the
  following solution acceptable (does it not look like a code
  duplication)?: [...]

If you presented that to me for code review, I would certainly ask what you think you gain from inheritance there.  One might argue a bit over whether your code is technically duplicative, but it is certainly longer and more complex than the non-inheritance version I presented.  And the non-inheritance version leaves no question about code duplication.

Body:
The code below brakes apparently the Law of Demeter, i.e. methods getServer().methodx(...). From other side it looks pretty compact = better readable?

abstract class BaseManager {
    ResultSet find(String searchText) {
        return getServer().find(searchText);
    }

    ResultSet fetch(String fetchText) {
        return getServer().fetch(fetchText);
    }

    void save(String saveText) {
        getServer().save(saveText);
    }

    abstract BaseManager getServer();
}

class Server1Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server1;
    }
}

class Server2Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server2;
    }
}

If the law is violated, them how to refactor this code?
Many thanks in advance.

Body:
The code below brakes [sic] apparently the Law of Demeter, i.e.
  methods getServer().methodx(...). From other side it looks pretty
  compact = better readable?

The point of your design is lost on me.  If compactness is your goal, then would not this be even better?

class Manager {
    private Server server;

    public Manager(Server server) {
        this.server = server;
    }

    ResultSet find(String searchText) {
        server.find(searchText);
    }

    ResultSet fetch(String fetchText) {
        server.fetch(fetchText);
    }

    void save(String saveText) {
        server.save(saveText);
    }
}

In addition to being even more compact and clear, that happens to conform to the Law of Demeter.  Moreover, it follows the principle of preferring composition over inheritance, which I think you'll see is favored (but not implied) by the Law of Demeter.

If the law is violated, them how to refactor this code?

I'm still liking what I presented above.

Is the
  following solution acceptable (does it not look like a code
  duplication)?: [...]

If you presented that to me for code review, I would certainly ask what you think you gain from inheritance there.  One might argue a bit over whether your code is technically duplicative, but it is certainly longer and more complex than the non-inheritance version I presented.  And the non-inheritance version leaves no question about code duplication.


问:
How to create a random decimal between 0 and 1 vb.net
I need a random decimal between 0 and 1 in VB.NET

```<code>Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))
</code>```

I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.

It should be between 0 and 1, but it's just returning 0.

答:
The function Rnd already returns a decimal number between 0 and 1. (Docs)

Just use:

```<code>Dim Value as Decimal = Rnd()
</code>```

Body:
I need a random decimal between 0 and 1 in VB.NET

Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))

I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.

It should be between 0 and 1, but it's just returning 0.

Body:
The function Rnd already returns a decimal number between 0 and 1. (Docs)

Just use:

Dim Value as Decimal = Rnd()


问:
Will `nodetool rebuild` truncate the tables before it starts to stream?
Will nodetool rebuild truncate the tables before it starts to stream? Or will I need to empty the data directory first I've I'd like to reset the data on a node?

答: No, rebuild will just stream the data. You would need to truncate the data yourself first.


问:
Using a 3 symbols notation [constr:operconstr] expected after [constr:operconstr]
Say I have a relation and its reflexive and transitive closure (with n counting the number of "transitive steps":

```<code>Variable A: Type.

Inductive Relation: A -> A -> Prop :=
| rel: forall (a b: A), Relation a b.

Notation "a --> b" := (Relation a b) (at level 50).

Inductive Refl_Trans_Rel: A -> A -> nat -> Prop :=
| zero_step: forall a b, a --> b -> Refl_Trans_Rel a b 0
| n_steps: forall a b c n, a --> b /\ Refl_Trans_Rel b c n
    -> Refl_Trans_Rel a c (S n).
</code>```

Now, I want to have a notation similiar as a --> b:

```<code>Notation "a -->^ n b" :=
  (Refl_Trans_Rel a b n) (at level 50, n at next level, b at next level).
</code>```

For printing, there is no problem: Check forall a b n, Refl_Trans_Rel a b n. indeed prints:

```<code>forall (a b : A) (n : nat), a -->^ n b
 : Prop
</code>```

However, when I want to use the notation myself, there is a problem:

```<code>Check forall a b n, a -->^ n b.
</code>```

fail with:

```<code>Syntax error: [constr:operconstr] expected after [constr:operconstr]
  (in [constr:operconstr]).
</code>```

Any idea of why it fails ?

P.S.: feel free to edit the title with something more precise, since I have no idea of the cause, I have no idea for a better title.

答:
It seems that Coq is trying to parse the n b part in a -->^ n b as a function application. One way of overcoming this difficulty would be to put n at a lower level, like so:

```<code>Notation "a -->^ n b" := (Refl_Trans_Rel a b n) (at level 50, n at level 9).
Check forall (a b : A) (n : nat), a -->^ n b.
</code>```

Another option is to put a separator between b and n:

```<code>Notation "a --> b # n" := (Refl_Trans_Rel a b n) (at level 50).
Check forall (a b : A) (n : nat), a --> b # n.
</code>```

You can find out more about notations and parsing levels here.

Body:
Say I have a relation and its reflexive and transitive closure (with n counting the number of "transitive steps":

Variable A: Type.

Inductive Relation: A -> A -> Prop :=
| rel: forall (a b: A), Relation a b.

Notation "a --> b" := (Relation a b) (at level 50).

Inductive Refl_Trans_Rel: A -> A -> nat -> Prop :=
| zero_step: forall a b, a --> b -> Refl_Trans_Rel a b 0
| n_steps: forall a b c n, a --> b /\ Refl_Trans_Rel b c n
    -> Refl_Trans_Rel a c (S n).

Now, I want to have a notation similiar as a --> b:

Notation "a -->^ n b" :=
  (Refl_Trans_Rel a b n) (at level 50, n at next level, b at next level).

For printing, there is no problem: Check forall a b n, Refl_Trans_Rel a b n. indeed prints:

forall (a b : A) (n : nat), a -->^ n b
 : Prop

However, when I want to use the notation myself, there is a problem:

Check forall a b n, a -->^ n b.

fail with:

Syntax error: [constr:operconstr] expected after [constr:operconstr]
  (in [constr:operconstr]).

Any idea of why it fails ?

P.S.: feel free to edit the title with something more precise, since I have no idea of the cause, I have no idea for a better title.

Body:
It seems that Coq is trying to parse the n b part in a -->^ n b as a function application. One way of overcoming this difficulty would be to put n at a lower level, like so:

Notation "a -->^ n b" := (Refl_Trans_Rel a b n) (at level 50, n at level 9).
Check forall (a b : A) (n : nat), a -->^ n b.

Another option is to put a separator between b and n:

Notation "a --> b # n" := (Refl_Trans_Rel a b n) (at level 50).
Check forall (a b : A) (n : nat), a --> b # n.

You can find out more about notations and parsing levels here.


问:
RegEx in BigQuery
I need to split the following field:  LP1234354_CD12346

and get the 2 separate columns with the following values:1234354 and 12346.
I tried regex and right/left but not successful. Thank you in advance!
Dummy data:

```<code>SELECT 'LP1234354_CD12346' AS word UNION ALL
  SELECT 'LP1234456_CD12345'
</code>```

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'LP1234354_CD12346' AS word UNION ALL
  SELECT 2, 'LP1234456_CD12345'
)
SELECT id,
  REGEXP_EXTRACT_ALL(word, r'(\d+)')[SAFE_OFFSET(0)] AS val1,
  REGEXP_EXTRACT_ALL(word, r'(\d+)')[SAFE_OFFSET(1)] AS val2
FROM `project.dataset.table`
</code>```

Title: RegEx in BigQuery

Body:
I need to split the following field:  LP1234354_CD12346

and get the 2 separate columns with the following values:1234354 and 12346.
I tried regex and right/left but not successful. Thank you in advance!
Dummy data:

SELECT 'LP1234354_CD12346' AS word UNION ALL
  SELECT 'LP1234456_CD12345'

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'LP1234354_CD12346' AS word UNION ALL
  SELECT 2, 'LP1234456_CD12345'
)
SELECT id,
  REGEXP_EXTRACT_ALL(word, r'(\d+)')[SAFE_OFFSET(0)] AS val1,
  REGEXP_EXTRACT_ALL(word, r'(\d+)')[SAFE_OFFSET(1)] AS val2
FROM `project.dataset.table`


问:
How to get the last three days excluding holidays (french) and weekdays in SQL or PHP
I have a sql script that select the last three dates from current day in my base like below :

```<code>select distinct file_date
from my_database
where file_date > DATEADD(DAY, -3, CONVERT(date, SYSDATETIME()));
</code>```

This is correct for me just in Wednesday, Thursday and Friday, BUT in Monday i wanna excluding the weekdays
For Monday for example, I wanna just the file_date for Friday and current Monday .and For Tuesday, I wanna just the file_date for Tuesday and Monday only.
How can I excluding the holidays and weekdays.
Thanks for Help.

答:
No sample data and DB structure, also i asumed you have MYSQL DB so i will just give a hint how to do it in MYSQL
You can use  WEEKDAY() as filter for the days of week.
For example this in normal query filter the results only for monday to friday:

```<code>SELECT *
FROM some_table
WHERE WEEKDAY(date_field) < 5
</code>```

You can also do it in php. Increase your results to 5 rows (to include the possible weekends) and order the results by descending date.

```<code>//you have $results array with 5 elements
$lastThreeDays = [];
$i = 0;
foreach ($results as $res) {
    $tStamp = strtotime($res['date_field']);
    $weekDay = date('N',$tStamp);
    if ($weekDay < 6 && $i < 3) {
        $lastThreeDays[] = $res;
        $i++;
    }
}
</code>```

No you have 3 records of the last 3 days excluding the weekdays.

Body:
I have a sql script that select the last three dates from current day in my base like below :

select distinct file_date
from my_database
where file_date > DATEADD(DAY, -3, CONVERT(date, SYSDATETIME()));

This is correct for me just in Wednesday, Thursday and Friday, BUT in Monday i wanna excluding the weekdays
For Monday for example, I wanna just the file_date for Friday and current Monday .and For Tuesday, I wanna just the file_date for Tuesday and Monday only.
How can I excluding the holidays and weekdays.
Thanks for Help.

Body:
No sample data and DB structure, also i asumed you have MYSQL DB so i will just give a hint how to do it in MYSQL
You can use  WEEKDAY() as filter for the days of week.
For example this in normal query filter the results only for monday to friday:

SELECT *
FROM some_table
WHERE WEEKDAY(date_field) < 5

You can also do it in php. Increase your results to 5 rows (to include the possible weekends) and order the results by descending date.

//you have $results array with 5 elements
$lastThreeDays = [];
$i = 0;
foreach ($results as $res) {
    $tStamp = strtotime($res['date_field']);
    $weekDay = date('N',$tStamp);
    if ($weekDay < 6 && $i < 3) {
        $lastThreeDays[] = $res;
        $i++;
    }
}

No you have 3 records of the last 3 days excluding the weekdays.


问:
Passing data from javascript jquery to C# http post fails to work
Am trying to pass data from jquery to asp.net mvc controller to get a response but fails to work

This is what i have tried

In jquery

```<code> $('#Emp_Payroll_No').change(function () {
        var empdata = $(this).val();
        $.post('/tblHandOvers/GetEmployee', { payrollno: empdata}).then(function (res) {
            console.log("response is", res);  //res is always empty

        })
    })
</code>```

In my c# code

```<code>        public JsonResult GetEmployee(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string passedtext = context.Request.Form["payrollno"].ToString();

        var PersonsQuery = db.vwEmployee_HandoverContact.Where(x => x.Emp_Payroll_No == passedtext);
        return Json(PersonsQuery);
    }
</code>```

so am trying to pass payrollno

When using a manual value eg: EMP2001 in the controller it works like

```<code>        public JsonResult GetEmployee(HttpContext context)
     {
        var PersonsQuery = db.vwEmployee_HandoverContact
                             .Where(x => x.Emp_Payroll_No == "EMP2001 "); //passed manually
        return Json(PersonsQuery);
    }
</code>```

How do i go about this?

答:
In your C#, I would update to this:</p>

```<code>        public JsonResult GetEmployee(string payrollno)
{
    var PersonsQuery = db.vwEmployee_HandoverContact.Where(x => x.Emp_Payroll_No == payrollno);
    return Json(PersonsQuery);
}
</code>```

Body:
Am trying to pass data from jquery to asp.net mvc controller to get a response but fails to work

This is what i have tried

In jquery

 $('#Emp_Payroll_No').change(function () {
        var empdata = $(this).val();
        $.post('/tblHandOvers/GetEmployee', { payrollno: empdata}).then(function (res) {
            console.log("response is", res);  //res is always empty

        })
    })

In my c# code

        public JsonResult GetEmployee(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string passedtext = context.Request.Form["payrollno"].ToString();

        var PersonsQuery = db.vwEmployee_HandoverContact.Where(x => x.Emp_Payroll_No == passedtext);
        return Json(PersonsQuery);
    }

so am trying to pass payrollno

When using a manual value eg: EMP2001 in the controller it works like

        public JsonResult GetEmployee(HttpContext context)
     {
        var PersonsQuery = db.vwEmployee_HandoverContact
                             .Where(x => x.Emp_Payroll_No == "EMP2001 "); //passed manually
        return Json(PersonsQuery);
    }

How do i go about this?

Body:
In your C#, I would update to this:

        public JsonResult GetEmployee(string payrollno)
{
    var PersonsQuery = db.vwEmployee_HandoverContact.Where(x => x.Emp_Payroll_No == payrollno);
    return Json(PersonsQuery);
}


问:
Indexing Dataframe similar to numpy ndarray with 2d index
Motivation:

I have 3-dimensional velocity data stored in an Nx3 DataFrame. I need to detect events in the data and extract fixed length epochs for further analysis. I would like to store the detected epochs as an additional index/column in the DataFrame and use it to get a compact 2d representation of the epoch data across all 3 dimensions. I feel like this should be possible through some combination of functions like df.stack, df.unstack, df.pivot etc but I can't work out how to do it.

With numpy arrays I can use a 2d index into an array to do something like this

```<code>>>> arr = np.arange(30).reshape((10, 3))

>>> arr
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20],
       [21, 22, 23],
       [24, 25, 26],
       [27, 28, 29]])

>>> idx = np.array([[2, 5, 8],
                    [3, 6, 9]])

>>> np.concatenate(arr[idx].T).T
array([[ 6, 15, 24,  7, 16, 25,  8, 17, 26],
       [ 9, 18, 27, 10, 19, 28, 11, 20, 29]])
</code>```

Is there a nice way to do something similar in pandas to go from a dataframe like this

```<code>>>> df = pd.DataFrame(arr, columns=['X', 'Y', 'Z'])
>>> df.index = [NaN, NaN, 0, 0, NaN, 1, 1, NaN, 2, 2]
>>> df
      X   Y   Z
NaN   0   1   2
NaN   3   4   5
0     6   7   8
0     9  10  11
NaN  12  13  14
1    15  16  17
1    18  19  20
NaN  21  22  23
2    24  25  26
2    27  28  29
</code>```

To something like this?

```<code>   X           Y           Z
   0   1   2   0   1   2   0   1   2
0  6  15  24   7  16  25   8  17  26
1  9  18  27  10  19  28  11  20  29
</code>```

Of course, I could do all of the work with numpy and create a new DataFrame from the result, but it would be nice to have all of the index/column labels automatically sort themselves out.

Body:
Motivation:

I have 3-dimensional velocity data stored in an Nx3 DataFrame. I need to detect events in the data and extract fixed length epochs for further analysis. I would like to store the detected epochs as an additional index/column in the DataFrame and use it to get a compact 2d representation of the epoch data across all 3 dimensions. I feel like this should be possible through some combination of functions like df.stack, df.unstack, df.pivot etc but I can't work out how to do it.

With numpy arrays I can use a 2d index into an array to do something like this

>>> arr = np.arange(30).reshape((10, 3))

>>> arr
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20],
       [21, 22, 23],
       [24, 25, 26],
       [27, 28, 29]])

>>> idx = np.array([[2, 5, 8],
                    [3, 6, 9]])

>>> np.concatenate(arr[idx].T).T
array([[ 6, 15, 24,  7, 16, 25,  8, 17, 26],
       [ 9, 18, 27, 10, 19, 28, 11, 20, 29]])

Is there a nice way to do something similar in pandas to go from a dataframe like this

>>> df = pd.DataFrame(arr, columns=['X', 'Y', 'Z'])
>>> df.index = [NaN, NaN, 0, 0, NaN, 1, 1, NaN, 2, 2]
>>> df
      X   Y   Z
NaN   0   1   2
NaN   3   4   5
0     6   7   8
0     9  10  11
NaN  12  13  14
1    15  16  17
1    18  19  20
NaN  21  22  23
2    24  25  26
2    27  28  29

To something like this?

   X           Y           Z
   0   1   2   0   1   2   0   1   2
0  6  15  24   7  16  25   8  17  26
1  9  18  27  10  19  28  11  20  29

Of course, I could do all of the work with numpy and create a new DataFrame from the result, but it would be nice to have all of the index/column labels automatically sort themselves out.

Body:
Consider the following Pandas approach:

In [270]: x = df.loc[df.index.notnull()]

In [271]: x
Out[271]:
      X   Y   Z
0.0   6   7   8
0.0   9  10  11
1.0  15  16  17
1.0  18  19  20
2.0  24  25  26
2.0  27  28  29

In [278]: (x.set_index(np.arange(len(x)) // 2)
            .set_index(np.arange(len(x)) % 2, append=True)
            .unstack(0))
Out[278]:
   X           Y           Z
   0   1   2   0   1   2   0   1   2
0  6  15  24   7  16  25   8  17  26
1  9  18  27  10  19  28  11  20  29

or using multi-index:

In [305]: idx = pd.MultiIndex.from_product(([0,1,2],[0,1]))

In [306]: x.set_index(idx).unstack(0)
Out[306]:
   X           Y           Z
   0   1   2   0   1   2   0   1   2
0  6  15  24   7  16  25   8  17  26
1  9  18  27  10  19  28  11  20  29


问:
I am having difficulty in understanding a line in a decimal to binary conversion program
Alright, I know this is a silly question to ask as it is related to reverse for loop but I am struggling to understand this. I even tried to make a separate reverse for loop program to clear the context but I am still in trouble.

So here is my code

```<code>#include<iostream>
using namespace std;
int main()
{
    int i,d,j=0,b[100];
    cin>>d;
    while(d>0)
    {
        b[j]=d%2;
        d=d/2;
        j++;
    }
    //cout<<j;
    for(i=j-1;i>=0;i--)
    {
        cout<<b[i];
    }
}
</code>```

Now, please explain me the for-loop. Why it should be i=j-1;i>=0;i--? Can't it be i=j;i>0;i--?

When I am giving 109 as input and using i=j;i>0;i-- I am receiving 6946348110110 as output and if I am using i=j;i>=0;i-- then I am receiving 69463481101101

I am a novice. Please help!

答: The last time the 'while' loop is executed, b[j]=d%2 will add a value at, let's say, the position 4 (b[0,1,2,3,4]).  The variable 'j' will still be increased by one to end the loop, taking the value 5.  So, when starting your 'for' loop, you'll got a tab going to 4, but a 'j' value of 5, explaining the utility of using i=j-1.  Your loop will now check the values [4,3,2,1,0] instead of [5,4,3,2,1], which is not exact.

Body:
Alright, I know this is a silly question to ask as it is related to reverse for loop but I am struggling to understand this. I even tried to make a separate reverse for loop program to clear the context but I am still in trouble.

So here is my code

#include<iostream>
using namespace std;
int main()
{
    int i,d,j=0,b[100];
    cin>>d;
    while(d>0)
    {
        b[j]=d%2;
        d=d/2;
        j++;
    }
    //cout<<j;
    for(i=j-1;i>=0;i--)
    {
        cout<<b[i];
    }
}

Now, please explain me the for-loop. Why it should be i=j-1;i>=0;i--? Can't it be i=j;i>0;i--?

When I am giving 109 as input and using i=j;i>0;i-- I am receiving 6946348110110 as output and if I am using i=j;i>=0;i-- then I am receiving 69463481101101

I am a novice. Please help!


答:
This is a bit tricky, but you can use interpolate() (can only be used on Series):

```<code>df['value'] = df['value'].interpolate(method='slinear').interpolate(method='linear')
</code>```

The second interpolation is only needed to fill the last NaNs in the series.

Title: Fill missing values in a data frame with the nearest row

Body:
I have the following data frame:

df = pd.DataFrame({'id': {3002: 10001,
  3003: 10002,
  3004: 10003,
  3005: 10004,
  3006: 10005,
  3007: 10006,
  3008: 10007,
  3009: 10008,
  3010: 10009,
  3011: 10010,
  3012: 10011,
  3013: 10012,
  3014: 10013,
  3015: 10014,
  3016: 10015,
  3017: 10016,
  3018: 10017,
  3019: 10018,
  3020: 10019,
  3021: 10020},
 'value': {3002: 1669.0,
  3003: 1264.0,
  3004: nan,
  3005: 1411.0,
  3006: 1224.0,
  3007: 1316.0,
  3008: 1736.0,
  3009: nan,
  3010: 1276.0,
  3011: nan,
  3012: nan,
  3013: nan,
  3014: nan,
  3015: 1790.0,
  3016: nan,
  3017: nan,
  3018: nan,
  3019: 1726.0,
  3020: nan,
  3021: nan}})

And I want to fill the missing values with the one in the nearest id, in case of two values at the same distance then I want to use the average.

E.G.

id 10008 is NaN, then I want to fill the cell with the average of  10009 and 10007: (1736.0 + 1276.0)/2

for id 10015 the nearest value is at 10014 so I'll use that value directly: 1790.0

How can I accomplish this efficiently?

Body:
This is a bit tricky, but you can use interpolate() (can only be used on Series):

df['value'] = df['value'].interpolate(method='slinear').interpolate(method='linear')

The second interpolation is only needed to fill the last NaNs in the series.


问:
Sql MAX DateTime and if clause?
My 2nd Sql question on SO today - I need to brush up my Sql skills!!!!

I have the following three tables....

Diary, Entry, and EntryType

A Diary can have many Entry(ies), each Entry is of a particular EntryType.

Entry has a created DateTime
EntryType has an Id, and SomeOtherValue (int)

EDIT

Sorry Chaps.  Thanks for response so far but I didn't explain it well enough; the requirements have changed a bit.....

I would like the Id of any Diary where its latest Entry that is greater than @lastDateTime AND EntryType.someOthervalue != 0 has a EntryType.someOthervalue == @someValue

Or to put it another way....For all those Entry rows with a created Date time > @lastDateTime, ignore the someOtherValues that equal 0, and if the top 1 left over has a someOtherValue = @someValue, return the Id of the diary!!!!

Does that make sense???  I'm not sure what I should be putting my MAX, WHERE, and HAVING (if anything at all!)

Thanks,

ETFairfax.

答:
Another approach if you are using SQL Server 2005+</p>

```<code>With EntryDates As
    (
    Select E.DiaryId
        , Max(E.Created) Over ( Partition By E.DiaryId ) As LastCreateDate
    From Entry As E
        Join EntryType As ET
            On ET.Id = E.EntryTypeId
    Where ET.SomeOtherValue = @SomeValue
    )
Select DiaryId
From EntryDates
Where LastCreateDate > @lastDateTime
Group By DiaryId
</code>```

ContentLicense: CC BY-SA 2.5

Title: Sql MAX DateTime and if clause?

Body:
Another approach if you are using SQL Server 2005+

With EntryDates As
    (
    Select E.DiaryId
        , Max(E.Created) Over ( Partition By E.DiaryId ) As LastCreateDate
    From Entry As E
        Join EntryType As ET
            On ET.Id = E.EntryTypeId
    Where ET.SomeOtherValue = @SomeValue
    )
Select DiaryId
From EntryDates
Where LastCreateDate > @lastDateTime
Group By DiaryId


问:
How to format a string containing numbers and characters
I have the following string "2017-2" and I need to format it as "2017-02".

```<code>var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);
</code>```

periodFormatted returns "2017-2"

What is the correct syntax to get the period formatted as "2017-02"?

答:
string.Format won't know (or care) that your string contains numbers so you cannot directly format like that. You could split up the string and parse the last part as a number though. For example:

```<code>var period = "2017-2";
var parts = period.Split('-');;
var periodFormatted = $"{parts[0]}-{int.Parse(parts[1]):D2}";
</code>```

However, you should probably have the period value as a proper DateTime object (or a custom type representing the year and month values) in the first place, that would have made the formatting trivial.

Body:
I have the following string "2017-2" and I need to format it as "2017-02".

var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);

periodFormatted returns "2017-2"

What is the correct syntax to get the period formatted as "2017-02"?

Body:
string.Format won't know (or care) that your string contains numbers so you cannot directly format like that. You could split up the string and parse the last part as a number though. For example:

var period = "2017-2";
var parts = period.Split('-');;
var periodFormatted = $"{parts[0]}-{int.Parse(parts[1]):D2}";

However, you should probably have the period value as a proper DateTime object (or a custom type representing the year and month values) in the first place, that would have made the formatting trivial.


问:
if else to raise a ValueError
I am following this:

if else in a list comprehension

but the following small program is generating a syntax error:

```<code>def to_rna(dnasequences):
    xlate = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'}
    return ''.join(xlate[sequence] for sequence in dnasequences if sequence in xlate.keys() else raise ValueError)
</code>```

The else clause is generating the error.

If I remove the else clause it runs, however, I want to raise a ValueError for any input
that is NOT a key in my dictionary 'xlate'.

NOTE I am working on the rna-transcription problem from exercism.io.

I pass 5 unit tests but I fail the three unit tests requiring a ValueError for invalid input.

答:
You cannot do this in a comprehension. The conditional expression has the form:

```<code>expr if expr else expr
</code>```

(and, sub-note, it should be used in the beginning of the comprehension)

while raise ExceptionClass is a statement, not an expression. As such, a SyntaxError is raised.

In short, if you do want to use raise, you'll have to resort to a for loop.

Alternately, if you're just very passionate about comprehensions, you could define a function which you can then call in the else clause:

```<code>def raiser(exc_type):
    raise exc_type
</code>```

This is because function calls are expressions. Of course, this is quite ugly.

Title: if else to raise a ValueError

Body:
I am following this:

if else in a list comprehension

but the following small program is generating a syntax error:

def to_rna(dnasequences):
    xlate = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'}
    return ''.join(xlate[sequence] for sequence in dnasequences if sequence in xlate.keys() else raise ValueError)

The else clause is generating the error.

If I remove the else clause it runs, however, I want to raise a ValueError for any input
that is NOT a key in my dictionary 'xlate'.

NOTE I am working on the rna-transcription problem from exercism.io.

I pass 5 unit tests but I fail the three unit tests requiring a ValueError for invalid input.

Body:
You cannot do this in a comprehension. The conditional expression has the form:

expr if expr else expr

(and, sub-note, it should be used in the beginning of the comprehension)

while raise ExceptionClass is a statement, not an expression. As such, a SyntaxError is raised.

In short, if you do want to use raise, you'll have to resort to a for loop.

Alternately, if you're just very passionate about comprehensions, you could define a function which you can then call in the else clause:

def raiser(exc_type):
    raise exc_type

This is because function calls are expressions. Of course, this is quite ugly.


问:
What does the "RAILS_GEM_VERSION" setting do exactly?
What is the purpose of the RAILS_GEM_VERSION setting in config/environment.rb? Is it supposed to stop your app from running under an unexpected version of Rails?

I just keep Rails updated to the latest release on my laptop and in production. Since I do that, can I comment out RAILS_GEM_VERSION or should I set it for some reason?

答: Since you can have more than one version of Rails installed on your system (you can check with gem list rails), your application needs to know which version it is supposed to use. It won't be very clever just to "keep Rails updated to the latest release" and let the application use the newest version, since since new version of Rails could very easily break it (every new release means some changes to the API). This constant is irrelevant, however, if you "freeze" the version of Rails your app is build for, in the vendor folder. Btw. freezing Rails is a good practice, since your app is then more independent on the environment.</p>

OwnerDisplayName: Ethan

OwnerDisplayName: Milan Novota


问:
UIImagePicker and AVCaptureSession access camera simultaneously
I'm wondering if it's possible to have an instance of an AVCaptureSession and UIImagePicker both accessing the camera simultaneously.

I want to create an app that shows an ambient light meter/indicator as an overlay view of a UIImagePicker when the camera is active. I previously implemented this using UIGetScreenImage(), but Apple is now disallowing use of this private API in favor of AVCaptureSession. In my experimentation, AVCaptureSession seems to become suspended when UIImagePicker displays the camera view. Any ideas? Thanks!

答: I don't think so that they can not access the both thing simutaneoulsly, </p>


问:
How to delete nested column in mongodb with laravel?
I am using Laravel with Mongodb, i have the table structure as following,

```<code>  {
    "_id" : ObjectId("59323b092798db16b4006e33"),
    "contractorId" : "KT0004",
    "worktypeId" : 1,
    "contractorDetails" : [
      [
        "KT0004",
        1,
        "Air Conditioning",
        "Salim"
      ],
      [
        "KT0001",
        2,
        "Carpentry",
        "Ashok kumar"
      ]
    ]
  }
</code>```

I need to delete the first element from the "ContractorDetails" column, i tried with Laravel Delete, Unset, Destroy, but i did not got the solution, anyone suggest me pls?

答:
If you are using jenssegers' mongodb library for Laravel (https://github.com/jenssegers/laravel-mongodb) then you can pull that item to remove it from the array:

```<code>DB::collection('coll')->where('contractorId', 'KT0004')->pull('contractorDetails', $item);
</code>```

You may need to get that item first, as it is doesn't support removing by position.

Body:
I am using Laravel with Mongodb, i have the table structure as following,

  {
    "_id" : ObjectId("59323b092798db16b4006e33"),
    "contractorId" : "KT0004",
    "worktypeId" : 1,
    "contractorDetails" : [
      [
        "KT0004",
        1,
        "Air Conditioning",
        "Salim"
      ],
      [
        "KT0001",
        2,
        "Carpentry",
        "Ashok kumar"
      ]
    ]
  }

I need to delete the first element from the "ContractorDetails" column, i tried with Laravel Delete, Unset, Destroy, but i did not got the solution, anyone suggest me pls?

Body:
If you are using jenssegers' mongodb library for Laravel (https://github.com/jenssegers/laravel-mongodb) then you can pull that item to remove it from the array:

DB::collection('coll')->where('contractorId', 'KT0004')->pull('contractorDetails', $item);

You may need to get that item first, as it is doesn't support removing by position.


问:
Tensorflow batch_norm does not work properly when testing (is_training=False)
I am training the following model:

with slim.arg_scope(inception_arg_scope(is_training=True)):
    logits_v, endpoints_v = inception_v3(all_v, num_classes=25, is_training=True, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='vis')
    logits_p, endpoints_p = inception_v3(all_p, num_classes=25, is_training=True, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='pol')
    pol_features = endpoints_p['pol/features']
    vis_features = endpoints_v['vis/features']

eps = 1e-08
loss = tf.sqrt(tf.maximum(tf.reduce_sum(tf.square(pol_features - vis_features), axis=1, keep_dims=True), eps))

# rest of code
saver = tf.train.Saver(tf.global_variables())
```

<p>where</p>

<pre class="lang-py prettyprint-override"><code>def inception_arg_scope(weight_decay=0.00004,
                    batch_norm_decay=0.9997,
                    batch_norm_epsilon=0.001, is_training=True):
normalizer_params = {
    'decay': batch_norm_decay,
    'epsilon': batch_norm_epsilon,
    'is_training': is_training
}
normalizer_fn = tf.contrib.layers.batch_norm

# Set weight_decay for weights in Conv and FC layers.
with slim.arg_scope([slim.conv2d, slim.fully_connected],
                    weights_regularizer=slim.l2_regularizer(weight_decay)):
    with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training):
        with slim.arg_scope(
                [slim.conv2d],
                weights_initializer=slim.variance_scaling_initializer(),
                activation_fn=tf.nn.relu,
                normalizer_fn=normalizer_fn,
                normalizer_params=normalizer_params) as sc:
            return sc
</code>```

and inception_V3 is defined here.
My model trains very well and the loss goes from 60 to less than 1. But when I want to test the model in another file:

with slim.arg_scope(inception_arg_scope(is_training=False)):
    logits_v, endpoints_v = inception_v3(all_v, num_classes=25, is_training=False, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='vis')
    logits_p, endpoints_p = inception_v3(all_p, num_classes=25, is_training=False, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='pol')
```

it gives me none-sense results, or more precisely the loss is 1e-8 for all the train and test samples. When I change is_training=True it gives more logical results but still the loss is bigger than training phase (even when I am testing on the training data)
I have the same problem with VGG16. I have %100 accuracy on my test when I am using VGG without batch_norm and 0% when I use batch_norm.

What am I missing here?
Thank you,

答: I met the same problem and solved. When you use slim.batch_norm,be sure to use slim.learning.create_train_op instead of tf.train.GradientDecentOptimizer(lr).minimize(loss) or other optimizer. Try it to see if it works!

Body:
I am training the following model:

with slim.arg_scope(inception_arg_scope(is_training=True)):
    logits_v, endpoints_v = inception_v3(all_v, num_classes=25, is_training=True, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='vis')
    logits_p, endpoints_p = inception_v3(all_p, num_classes=25, is_training=True, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='pol')
    pol_features = endpoints_p['pol/features']
    vis_features = endpoints_v['vis/features']

eps = 1e-08
loss = tf.sqrt(tf.maximum(tf.reduce_sum(tf.square(pol_features - vis_features), axis=1, keep_dims=True), eps))

# rest of code
saver = tf.train.Saver(tf.global_variables())

where

def inception_arg_scope(weight_decay=0.00004,
                    batch_norm_decay=0.9997,
                    batch_norm_epsilon=0.001, is_training=True):
normalizer_params = {
    'decay': batch_norm_decay,
    'epsilon': batch_norm_epsilon,
    'is_training': is_training
}
normalizer_fn = tf.contrib.layers.batch_norm

# Set weight_decay for weights in Conv and FC layers.
with slim.arg_scope([slim.conv2d, slim.fully_connected],
                    weights_regularizer=slim.l2_regularizer(weight_decay)):
    with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training):
        with slim.arg_scope(
                [slim.conv2d],
                weights_initializer=slim.variance_scaling_initializer(),
                activation_fn=tf.nn.relu,
                normalizer_fn=normalizer_fn,
                normalizer_params=normalizer_params) as sc:
            return sc

and inception_V3 is defined here.
My model trains very well and the loss goes from 60 to less than 1. But when I want to test the model in another file:

with slim.arg_scope(inception_arg_scope(is_training=False)):
    logits_v, endpoints_v = inception_v3(all_v, num_classes=25, is_training=False, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='vis')
    logits_p, endpoints_p = inception_v3(all_p, num_classes=25, is_training=False, dropout_keep_prob=0.8,
                     spatial_squeeze=True, reuse=reuse_variables, scope='pol')

it gives me none-sense results, or more precisely the loss is 1e-8 for all the train and test samples. When I change is_training=True it gives more logical results but still the loss is bigger than training phase (even when I am testing on the training data)
I have the same problem with VGG16. I have %100 accuracy on my test when I am using VGG without batch_norm and 0% when I use batch_norm.

What am I missing here?
Thank you,


问:
Report viewer tag missing in toolbox Visual Studio 2015
I recently installed Visual Studio 2015 Community and now my toolbox does not have the report viewer tag, all my existing report viewers in my ASP.NET project show 'error creating Control'. I've checked all my references and they seem to be OK, when I Run the project the report appears fine in the browser. </p>

答:
Just a heads up for VS 2017. The control is no longer located in the "Toolbox" but is now instead a NuGet package. It can be installed via the Package Manager Console with the command:
Install-Package ReportViewerForMvc

See: https://reportviewerformvc.codeplex.com/wikipage?title=Installation%20%26%20configuration


问:
Can I serve my localhost from a different port other than 4200 in EmberJS?
Normally, when a user calls

ember serve

The local host is always 4200 by default. It would be nice if I could specify a different port so that I could have two ember web apps running. Is it possible to have a ember serve a different port?

The reason I care is that I'm using one of my web apps to help me build the other, and it would be convenient to have them both running at the same time so that I don't keep going back and forth with my builds.

答:
Yes, you can specify the ports for your ember apps: </p>

```<code>ember server --port 1234 --live-reload-port 1235
</code>```

Body:
Yes, you can specify the ports for your ember apps:

ember server --port 1234 --live-reload-port 1235


问:
user defined color palette in cognos 11 visualizations
How do we customize the color of a visualization by inserting RBG color code in the palette property? It seems Cognos 11 Analytics only accepts the pre-defined color combinations in palette property. The order of the coloring also cannot be changed.</p>

答:
Unfortunately not possible, even in the just released 11.0.8 update.

That is a long-standing request in the the analytics forum and RFE website. You can go there and vote for it to help make it higher priority:
https://www.ibm.com/developerworks/rfe/execute?use_case=viewRfe&CR_ID=111066

You will need an IBM ID in order to to see and vote on it, but since you are already using Cognos you probably already have one.


问:
Accessing a Google BigQuery dataset from a PHP script running on a Google Compute VM instance
I am attempting to access a BigQuery dataset from a PHP script running on a Google Compute VM instance - on which I have installed Bitnami's LAMP stack.

The dataset is owned by another party, but the party has given me a full ownership role to the dataset, using my email address. They have also given me a read role to another dataset, again using my email address.

My PHP script is intended to read data from the dataset tables to which I have been given read permission, massage that data, and write it to tables in the dataset to which I have been given the full ownership role.

I have spent many hours attempting to work out how to setup the correct authorisations, running everything under my email address as mentioned, but to date I am still getting errors of the "you do not have permission..." type either when trying to read data from one dataset or write it to the other.

The BigQuery datasets are not owned by me as mentioned, but I have been given both the Project ID and names of the datasets involved, and the owner of both has used my email address to set up the access permissions discussed above.

Has anyone a simple step-by-step guide as to how to achieve the above. Does the owner of the datasets need two do anything more than as already described? I am finding working through many pages of Google Help very confusing!

答:
You need service account key file, that comes with a different email address. The service account email should be given permission and not your email. Actually both, because one is used by you to work on the UI, the other is on the app you develop.

I've included a full PHP example for you.

You need to setup the service account default credentials see lines with putenv and useApplicationDefaultCredentials(). This is a working code I have using the library https://github.com/google/google-api-php-client

You need to obtain your service account key file from the console: https://console.cloud.google.com/iam-admin/serviceaccounts/

composer.json

```<code>{
    "require": {
        "google/cloud": "^0.13.0",
        "google/apiclient": "^2.0"
    }
}
</code>```

php file

```<code># Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;

$query="SELECT repository_url,
       repository_has_downloads
FROM   [publicdata:samples.github_timeline]
LIMIT  10";
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__) . '/.ssh/dummyname-7f0004z148e1.json');//this can be created with other ENV mode server side
$client->useApplicationDefaultCredentials();

$builder = new ServiceBuilder([
                'projectId' => 'edited',
        ]);

        $bigQuery = $builder->bigQuery();

        $job = $bigQuery->runQueryAsJob($query);
        $info=$job->info();
//      print_r($info);
//      exit;
        $queryResults = $job->queryResults();

        /*$queryResults = $bigQuery->runQuery(
            $query,
            ['useLegacySql' => true]);*/

        if ($queryResults->isComplete())
        {
            $i = 0;
            $rows = $queryResults->rows();

            foreach ($rows as $row)
            {
                $i++;

                $result[$i] = $row;
            }
        }
        else
        {
            throw new Exception('The query failed to complete');
        }

        print_r($result);
</code>```

Body:
You need service account key file, that comes with a different email address. The service account email should be given permission and not your email. Actually both, because one is used by you to work on the UI, the other is on the app you develop.

I've included a full PHP example for you.

You need to setup the service account default credentials see lines with putenv and useApplicationDefaultCredentials(). This is a working code I have using the library https://github.com/google/google-api-php-client

You need to obtain your service account key file from the console: https://console.cloud.google.com/iam-admin/serviceaccounts/

composer.json

{
    "require": {
        "google/cloud": "^0.13.0",
        "google/apiclient": "^2.0"
    }
}

php file

# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;

$query="SELECT repository_url,
       repository_has_downloads
FROM   [publicdata:samples.github_timeline]
LIMIT  10";
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__) . '/.ssh/dummyname-7f0004z148e1.json');//this can be created with other ENV mode server side
$client->useApplicationDefaultCredentials();

$builder = new ServiceBuilder([
                'projectId' => 'edited',
        ]);

        $bigQuery = $builder->bigQuery();

        $job = $bigQuery->runQueryAsJob($query);
        $info=$job->info();
//      print_r($info);
//      exit;
        $queryResults = $job->queryResults();

        /*$queryResults = $bigQuery->runQuery(
            $query,
            ['useLegacySql' => true]);*/

        if ($queryResults->isComplete())
        {
            $i = 0;
            $rows = $queryResults->rows();

            foreach ($rows as $row)
            {
                $i++;

                $result[$i] = $row;
            }
        }
        else
        {
            throw new Exception('The query failed to complete');
        }

        print_r($result);