问:
no result with mongoose .find() when looking into array of a single document
I know it's me improperly formatting the query but i cannot seem to get entries in a document from a nested array. What i am attempting to do is retrieve all of the objects in the array with a specific value in the menu field.

I am also using mongo-tenant so the Settings object is already limited to a single document within the collection as it's the only document in settings for that tenant. (req.params.db is referenced earlier in the url than the visible route)

so far i have tried, based on many googlings

.find({}) // returns entire object as below

.find({dropsDowns: { menu: { $eq: req.params.menu }}}) // returns []

.find({ dropsDowns: { menu: req.params.menu } }) // returns []

.find({'dropDowns.menu':req.params.menu}) // returns entire object

.find({ ['dropDowns.menu']: req.params.menu }) // returns entire object

I also tried to do a few forms of the aggregation methods with less than ideal results as that assumes i actually know how to find the right stuff to aggregate, which i obviously do not.

```<code>settingsRoute.route('/dropDowns/:menu').get(function(req, res) {
  const Settings = baseSettings.byTenant(req.params.db)
  Settings.find({}).exec(function(
    err,
    menu
  ) {
    if (err) {
      return res.status(400).json(err)
    }
    res.status(200).json(menu)
  })
})
</code>```

this returns the below to my browser

```<code>[
{
_id: "5cea1b835e13fb4180be2699",
dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a3",
menu: "meterIntervals",
text: "250",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a2",
menu: "meterIntervals",
text: "500",
value: 500,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269e",
menu: "transitionIntervals",
text: "Due at normal interval",
value: 0,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269d",
menu: "transitionIntervals",
text: "Offset by 25% of normal",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
}
],
tenantId: "maxx1",
siteSettings: {
siteTheme: "dark",
friendlyName: "No Name Set :(",
activeStatus: "transit",
previousStatus: "transit",
numBackupsToKeep: 10,
daysPerBackup: 7,
_id: "5cea1b835e13fb4180be26ad",
backups: [ ],
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
},
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z",
__v: 0
}
]
</code>```

What is the proper formatting to only have something like the below return if i were to hit the api with /dropDowns/frequencyOptions

```<code>dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
}
</code>```

I am still building the structure of the database so if there is a more efficient way to go about getting this kind of data together then i am open to recommendations as well.

Thanks for any help.

答:
Mongo doc is pretty well done: find()

find method returns a cursor. You need to call .toArray() to turn cursor as a json array.
You may use pagination if there is a lot of result, like with skip/limit.

For the rest model, I would return directly the array of dropDowns, no need to embed it in an object with a dropDowns property.

Body:
I know it's me improperly formatting the query but i cannot seem to get entries in a document from a nested array. What i am attempting to do is retrieve all of the objects in the array with a specific value in the menu field.

I am also using mongo-tenant so the Settings object is already limited to a single document within the collection as it's the only document in settings for that tenant. (req.params.db is referenced earlier in the url than the visible route)

so far i have tried, based on many googlings

.find({}) // returns entire object as below

.find({dropsDowns: { menu: { $eq: req.params.menu }}}) // returns []

.find({ dropsDowns: { menu: req.params.menu } }) // returns []

.find({'dropDowns.menu':req.params.menu}) // returns entire object

.find({ ['dropDowns.menu']: req.params.menu }) // returns entire object

I also tried to do a few forms of the aggregation methods with less than ideal results as that assumes i actually know how to find the right stuff to aggregate, which i obviously do not.

settingsRoute.route('/dropDowns/:menu').get(function(req, res) {
  const Settings = baseSettings.byTenant(req.params.db)
  Settings.find({}).exec(function(
    err,
    menu
  ) {
    if (err) {
      return res.status(400).json(err)
    }
    res.status(200).json(menu)
  })
})

this returns the below to my browser

[
{
_id: "5cea1b835e13fb4180be2699",
dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a3",
menu: "meterIntervals",
text: "250",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a2",
menu: "meterIntervals",
text: "500",
value: 500,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269e",
menu: "transitionIntervals",
text: "Due at normal interval",
value: 0,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269d",
menu: "transitionIntervals",
text: "Offset by 25% of normal",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
}
],
tenantId: "maxx1",
siteSettings: {
siteTheme: "dark",
friendlyName: "No Name Set :(",
activeStatus: "transit",
previousStatus: "transit",
numBackupsToKeep: 10,
daysPerBackup: 7,
_id: "5cea1b835e13fb4180be26ad",
backups: [ ],
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
},
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z",
__v: 0
}
]

What is the proper formatting to only have something like the below return if i were to hit the api with /dropDowns/frequencyOptions

dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
}

I am still building the structure of the database so if there is a more efficient way to go about getting this kind of data together then i am open to recommendations as well.

Thanks for any help.


来源: stackexchange

问:
Vue replaces HTML with comment when compiling with webpack
I am facing the problem that once I import vue, the wrapper element for vue (in my case #app) will be replaced with the following comment

```<code><!--function (e,n,r,o){return sn(t,e,n,r,o,!0)}-->
</code>```

There is no error in the console and webpack compiles fine, I do however get the console log from vue's mounted method.

My index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>some content</h1>
        {{test}}
    </div>
    <script src="dist/bundle.js"></script>
</body>
</html>
</code>```

webpack.config.js

```<code>const path = require('path');

module.exports = {
    entry: './src/app.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}
</code>```

src/app.js

```<code>import Vue from 'vue'

const app = new Vue({
    el: "#app",
    data: {
        test: "asdf"
    },
    mounted() {
        console.log('mounted')
    }
})
</code>```

答:
While Leonie's answer is functional, including the template compiler isn't generally required for production builds. I would say it is likely undesired, as there will likely be performance impacts from building templates dynamically, which I assume is the case in this answer. Furthermore, it looks like Leonie's answer includes the full development version of Vue in the production build, which should be discouraged because of all of the extra content included in this version. Instead, it is possible to pre-compile templates during the build step.

The easiest method of doing this is to use single-file components (SFCs), as described in the previous link:

[The] associated build setups automatically performs pre-compilation for
you, so the built code contains the already compiled render functions
instead of raw template strings.

Another method, which I needed to use for my own situation, is to define an explicit render function instead of a template for the component definition, so a compilation isn't required. I needed this because the Vue project I had generated at the time used SFCs for all of its components, except for the root "mounting" component, which was defined explicitly using the following object:

```<code>new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App />'
})
</code>```

This worked fine in development mode, but failed in production with the "function comment" issue you were experiencing. Taking the insight from Leonie's answer, I replaced the above snippet with the following:

```<code>new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  render: (h) => {
    return h(App)
  }
})
</code>```

This resolved the issue on my production version without requiring me to include the full development version of Vue.

ContentLicense: CC BY-SA 3.0

Body:
I am facing the problem that once I import vue, the wrapper element for vue (in my case #app) will be replaced with the following comment

There is no error in the console and webpack compiles fine, I do however get the console log from vue's mounted method.

My index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

some content

        {{test}}

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/app.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

src/app.js

import Vue from 'vue'

const app = new Vue({
    el: "#app",
    data: {
        test: "asdf"
    },
    mounted() {
        console.log('mounted')
    }
})

Body:
While Leonie's answer is functional, including the template compiler isn't generally required for production builds. I would say it is likely undesired, as there will likely be performance impacts from building templates dynamically, which I assume is the case in this answer. Furthermore, it looks like Leonie's answer includes the full development version of Vue in the production build, which should be discouraged because of all of the extra content included in this version. Instead, it is possible to pre-compile templates during the build step.

The easiest method of doing this is to use single-file components (SFCs), as described in the previous link:

[The] associated build setups automatically performs pre-compilation for
you, so the built code contains the already compiled render functions
instead of raw template strings.

Another method, which I needed to use for my own situation, is to define an explicit render function instead of a template for the component definition, so a compilation isn't required. I needed this because the Vue project I had generated at the time used SFCs for all of its components, except for the root "mounting" component, which was defined explicitly using the following object:

new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App />'
})

This worked fine in development mode, but failed in production with the "function comment" issue you were experiencing. Taking the insight from Leonie's answer, I replaced the above snippet with the following:

new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  render: (h) => {
    return h(App)
  }
})

This resolved the issue on my production version without requiring me to include the full development version of Vue.

ContentLicense: CC BY-SA 4.0


问:
ThreeJS Animate Object3D.lookAt oddity
I'm trying to animate the lookAt method of an Object3D to lookAt a target Vector3. My Tween function traces floating points as per the incrementing scalarMultiplyVal (0.0 - 1.0), but no matter what I try the Object3D is already looking at the target before the tween starts. Very odd. </p>

```<code>TweenMax.to( this, 5, {scalarMultiplyVal:1, onUpdate:function(){
            let targetVector = new THREE.Vector3( target.position.x, target.position.y, target.position.z ).multiplyScalar( scalarMultiplyVal );
            console.log( targetVector ) // logs "animating" x,y,z values as expected
            displayObject.lookAt( targetVector ); // does not animate. Already fulling looking at target.position ( scalarMultiplyVal = 1.0 )
        }});
</code>```

<p>Essentially I'm trying to have my Object3D animate/turn to look at a new vector3 periodically, but instead the Object3D is already fully looking at the target.position, and disregarding the vector multiplication. Very odd.  Any advice will be a great help! </p>

答:
Instead of performing an animation with Object3D.lookAt() I highly recommend to use Quaternion.rotateTowards(). The method is based on Unity's Quaternion.RotateTowards. It internally performs a slerp which is ideal for your use case. The following example demonstrate the usage of Quaternion.rotateTowards().

https://threejs.org/examples/webgl_math_orientation_transform

three.js R104

Title: ThreeJS Animate Object3D.lookAt oddity

Body:
I'm trying to animate the lookAt method of an Object3D to lookAt a target Vector3. My Tween function traces floating points as per the incrementing scalarMultiplyVal (0.0 - 1.0), but no matter what I try the Object3D is already looking at the target before the tween starts. Very odd.

TweenMax.to( this, 5, {scalarMultiplyVal:1, onUpdate:function(){
            let targetVector = new THREE.Vector3( target.position.x, target.position.y, target.position.z ).multiplyScalar( scalarMultiplyVal );
            console.log( targetVector ) // logs "animating" x,y,z values as expected
            displayObject.lookAt( targetVector ); // does not animate. Already fulling looking at target.position ( scalarMultiplyVal = 1.0 )
        }});

Essentially I'm trying to have my Object3D animate/turn to look at a new vector3 periodically, but instead the Object3D is already fully looking at the target.position, and disregarding the vector multiplication. Very odd.  Any advice will be a great help!


问:
How to display date correctly with Angular2+?
I'm using Angular2+ to make a Kanban board.

I've decided to add a deadline on tasks then to display it on the board with the format 'yyyy-MM-dd'.

I've made a form to edit the deadline, and when I use it, the displayed date change in real time because I use [(ngModel)] directive.

But the new date is displayed in this format: 'Thu Jul 25 00:00:00 GMT+0200'.
So I would like to find something to change that OR something to update the information without changing what the user sees.

答:
Rather than using a template-driven form, switching to a reactive form means you no longer need the ngModel directive. Angular Material then takes care of the rest, showing the chosen date by default.

If you then want to play around with how the date is displayed, you can either use one of the provided DateAdapters or create your own.

Alternatively, you can separate the DatePicker from the input, or even remove the input part altogether and simply display the chosen date with string interpolation.


问:
500 error when authenticating ALB + AWS Cognito
I am trying to authenticate Lambda via Aws ALB + Cognito. When I launch the DNS server, it redirects me to login page, I'm able to signup and verify the user. Also, I could see the user added to users in userpool. After sign in, it gives 500 Internal Server Error.
The default action forward to function is getting executed in the background, I could see in the logs.

Not sure why it is not redirecting/executing lambda after authenticating the user. Could you please provide some insight, what would I be missing in this setup.

I have set up the Lambda, ALB and Cognito in terraform.

```<code>resource "aws_cognito_user_pool" "pool" {
  name                       = "alb-test-userpool"
  alias_attributes = ["email", "preferred_username"]
  verification_message_template {
  default_email_option = "CONFIRM_WITH_CODE"
  }
  email_verification_subject = "Device Verification Code"
  email_verification_message = "Please use the following code {####}"
  sms_verification_message   = "{####} Baz"
  auto_verified_attributes   = ["email"]

  password_policy {
      minimum_length    = 8
      require_lowercase = false
      require_numbers   = false
      require_symbols   = false
      require_uppercase = false
    }
  tags {
    "Name"   = "alb pool"
    }
 schema {
  name                = "email"
  attribute_data_type = "String"
  mutable             = false
  required            = true
}
}

resource "aws_cognito_user_pool_client" "client" {
  name = "alb-test-user-client"
  user_pool_id = "${aws_cognito_user_pool.pool.id}"
  generate_secret = true
  allowed_oauth_flows_user_pool_client = true
  supported_identity_providers = ["COGNITO"]
  callback_urls = ["https://internal-****-****.us-west-2.elb.amazonaws.com/oauth2/idpresponse"]
  allowed_oauth_flows  = ["code"]
  allowed_oauth_scopes = ["openid"]
  explicit_auth_flows = ["ADMIN_NO_SRP_AUTH"]
  allowed_oauth_flows_user_pool_client = true
}

resource "aws_cognito_user_pool_domain" "pool_domain" {
  domain          = "${var.domain}"
  user_pool_id    = "${aws_cognito_user_pool.pool.id}"
}
</code>```

答:
The load balancer is unable to communicate with the IdP token endpoint or the IdP user info endpoint. Verify that the security groups for your load balancer and the network ACLs for your VPC allow outbound access to these endpoints. Verify that your VPC has internet access. If you have an internal-facing load balancer, use a NAT gateway to enable internet access.

AWS docs about 500 issues

Body:
I am trying to authenticate Lambda via Aws ALB + Cognito. When I launch the DNS server, it redirects me to login page, I'm able to signup and verify the user. Also, I could see the user added to users in userpool. After sign in, it gives 500 Internal Server Error.
The default action forward to function is getting executed in the background, I could see in the logs.

Not sure why it is not redirecting/executing lambda after authenticating the user. Could you please provide some insight, what would I be missing in this setup.

I have set up the Lambda, ALB and Cognito in terraform.

resource "aws_cognito_user_pool" "pool" {
  name                       = "alb-test-userpool"
  alias_attributes = ["email", "preferred_username"]
  verification_message_template {
  default_email_option = "CONFIRM_WITH_CODE"
  }
  email_verification_subject = "Device Verification Code"
  email_verification_message = "Please use the following code {####}"
  sms_verification_message   = "{####} Baz"
  auto_verified_attributes   = ["email"]

  password_policy {
      minimum_length    = 8
      require_lowercase = false
      require_numbers   = false
      require_symbols   = false
      require_uppercase = false
    }
  tags {
    "Name"   = "alb pool"
    }
 schema {
  name                = "email"
  attribute_data_type = "String"
  mutable             = false
  required            = true
}
}

resource "aws_cognito_user_pool_client" "client" {
  name = "alb-test-user-client"
  user_pool_id = "${aws_cognito_user_pool.pool.id}"
  generate_secret = true
  allowed_oauth_flows_user_pool_client = true
  supported_identity_providers = ["COGNITO"]
  callback_urls = ["https://internal-****-****.us-west-2.elb.amazonaws.com/oauth2/idpresponse"]
  allowed_oauth_flows  = ["code"]
  allowed_oauth_scopes = ["openid"]
  explicit_auth_flows = ["ADMIN_NO_SRP_AUTH"]
  allowed_oauth_flows_user_pool_client = true
}

resource "aws_cognito_user_pool_domain" "pool_domain" {
  domain          = "${var.domain}"
  user_pool_id    = "${aws_cognito_user_pool.pool.id}"
}


问:
How can I solve this javascript math problem?
I need help with this logic problem in Uri Online Judge site.

The submitted code starts in "var a" and ends in the last console.log, I used the var lines to work with an example of input

var lines = ["3.0", "4.0", "5.2"];
/**
 * Code your solution here
 */
var a = parseFloat(lines[0]);
var b = parseFloat(lines[1]);
var c = parseFloat(lines[2]);
var areatr = (a * c) / 2;
var areac = 3.14159 * (c * c);
var areat = ((a + b) * c) / 2;
var areaq = b * b;
var arear = a * b;

console.log("TRIANGULO: " + areatr.toFixed(3));
console.log("CIRCULO: " + areac.toFixed(3));
console.log("TRAPEZIO: " + areat.toFixed(3));
console.log("QUADRADO: " + areaq.toFixed(3));
console.log("RETANGULO: " + arear.toFixed(3));```

when I submit my code, the console shows: Wrong answer (30%)

答:
change how you process the input

from:
var lines = input.split('\n');

to:
var lines = input.split(' ');

Body:
I need help with this logic problem in Uri Online Judge site.

The submitted code starts in "var a" and ends in the last console.log, I used the var lines to work with an example of input

var lines = ["3.0", "4.0", "5.2"];
/**
 * Code your solution here
 */
var a = parseFloat(lines[0]);
var b = parseFloat(lines[1]);
var c = parseFloat(lines[2]);
var areatr = (a * c) / 2;
var areac = 3.14159 * (c * c);
var areat = ((a + b) * c) / 2;
var areaq = b * b;
var arear = a * b;

console.log("TRIANGULO: " + areatr.toFixed(3));
console.log("CIRCULO: " + areac.toFixed(3));
console.log("TRAPEZIO: " + areat.toFixed(3));
console.log("QUADRADO: " + areaq.toFixed(3));
console.log("RETANGULO: " + arear.toFixed(3));

when I submit my code, the console shows: Wrong answer (30%)


问:
The Mix manifest does not exist
i'm created simple laravel project with this Laravel-Vue SPA starter project template and im uploaded this project to ubuntu server. all settings corect but i run this project returns this error "The Mix manifest does not exist. (View: /var/www/html/project/resources/views/index.blade.php)".

please anyone help me. i'm new in laravel.

答:
You should create a symlink of storage/app/public</p>

```<code>php artisan storage:link
</code>```

Title: The Mix manifest does not exist

Body:
You should create a symlink of storage/app/public

php artisan storage:link


问:
mediaItems.search_next() returns 400
Unable to get all results of mediaItems.search:

photos = google.get_service(credentials, 'photoslibrary', 'v1')
request = photos.albums().list(pageSize=50)
while request is not None:
    result = request.execute()
    for album in result['albums']:
        request2 = photos.mediaItems().search(body={'albumId': album['id']})
        while request2 is not None:
            result2 = request2.execute()
            request2 = photos.mediaItems().search_next(request2, result2)
            print('nextpageToken' in result2, request2)
    request = photos.albums().list_next(request, result)
```

<p>Running this fails on the first search_next() call with</p>

```[...]
  File "/usr/local/lib/python3.7/dist-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/googleapiclient/http.py", line 851, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://photoslibrary.googleapis.com/v1/mediaItems:search?alt=json returned "Invalid JSON payload received. Unexpected end of string. Expected an object key or }.
```

That library isn't really supported it seems, so that might be the problem, or am I missing something here?

答:
The google-api-python-client is generic client for all the Google's discovery based APIs and as such it supports all the API based on this protocol including the Photos one.

The correct way to use the services is to invoke the build method and after that use the available methods of the services.

Beside this you always want to use list_next as search_next does not exists.

Here is an example of the photos API working on my laptop (python 3.6)

import os
import pickle

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/photoslibrary.readonly', ]

# we check if we save the credentials in the past and we reuse them
if not os.path.exists('credentials.dat'):

    # no credentials found, we run the standard auth flow
    flow = InstalledAppFlow.from_client_secrets_file('client_id.json', SCOPES)
    credentials = flow.run_local_server()

    with open('credentials.dat', 'wb') as credentials_dat:
        pickle.dump(credentials, credentials_dat)
else:
    with open('credentials.dat', 'rb') as credentials_dat:
        credentials = pickle.load(credentials_dat)

if credentials.expired:
    credentials.refresh(Request())

photos_sdk = build('photoslibrary', 'v1', credentials=credentials)

# photos API
photos_albums_api = photos_sdk.albums()
photos_mediaitems_api = photos_sdk.mediaItems()

albums_list_params = {
    'pageSize': 50,
}

# first request
albums_list_req = photos_albums_api.list(**albums_list_params)

while albums_list_req is not None:
    photos_albums_list = albums_list_req.execute()

    # print(photos_albums_list)

    for album in photos_albums_list['albums']:
        print(album['title'])

        mediaitems_search_req = photos_mediaitems_api.search(body={'albumId': album['id']})

        while mediaitems_search_req is not None:
            mediaitems_search = mediaitems_search_req.execute()

            print(mediaitems_search)

            # mediaItems pagination management
            mediaitems_search_req = photos_mediaitems_api.list_next(mediaitems_search_req, mediaitems_search)

    # albums pagination handling
    albums_list_req = photos_albums_api.list_next(albums_list_req, photos_albums_list)
```

Title: mediaItems.search_next() returns 400

Body:
Unable to get all results of mediaItems.search:

photos = google.get_service(credentials, 'photoslibrary', 'v1')
request = photos.albums().list(pageSize=50)
while request is not None:
    result = request.execute()
    for album in result['albums']:
        request2 = photos.mediaItems().search(body={'albumId': album['id']})
        while request2 is not None:
            result2 = request2.execute()
            request2 = photos.mediaItems().search_next(request2, result2)
            print('nextpageToken' in result2, request2)
    request = photos.albums().list_next(request, result)

Running this fails on the first search_next() call with

[...]
  File "/usr/local/lib/python3.7/dist-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/googleapiclient/http.py", line 851, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://photoslibrary.googleapis.com/v1/mediaItems:search?alt=json returned "Invalid JSON payload received. Unexpected end of string. Expected an object key or }.

That library isn't really supported it seems, so that might be the problem, or am I missing something here?


问:
Subplot of Subplots Matplotlib / Seaborn
I am trying to create a grid of subplots. each subplot will look like the one that is on this site.

https://python-graph-gallery.com/24-histogram-with-a-boxplot-on-top-seaborn/

If I have 10 different sets of this style of plot I want to make them into a 5x2 for example.

I have read through the documentation of Matplotlib and cannot seem to figure out how do it. I can loop the subplots and have each output but I cannot make it into the rows and columns

import pandas as pd
import numpy as np
import seaborn as sns

```<code>df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)),columns=list('ABCDEFGHIJ'))

for c in df :
    # Cut the window in 2 parts
    f, (ax_box,
        ax_hist) = plt.subplots(2,
                                sharex=True,
                                gridspec_kw={"height_ratios":(.15, .85)},
                                figsize = (10, 10))
    # Add a graph in each part
    sns.boxplot(df[c], ax=ax_box)
    ax_hist.hist(df[c])
    # Remove x axis name for the boxplot
plt.show()
</code>```

the results would just take this loop and put them into a set of rows and columns in this case 5x2

答:
You have 10 columns, each of which creates 2 subplots: a box plot and a histogram. So you need a total of 20 figures. You can do this by creating a grid of 2 rows and 10 columns

Complete answer: (Adjust the figsize and height_ratios as per taste)

```<code>import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

f, axes = plt.subplots(2, 10, sharex=True, gridspec_kw={"height_ratios":(.35, .35)},
                                    figsize = (12, 5))

df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)),columns=list('ABCDEFGHIJ'))

for i, c in enumerate(df):
    sns.boxplot(df[c], ax=axes[0,i])
    axes[1,i].hist(df[c])
plt.tight_layout()
plt.show()
</code>```

Body:
I am trying to create a grid of subplots. each subplot will look like the one that is on this site.

https://python-graph-gallery.com/24-histogram-with-a-boxplot-on-top-seaborn/

If I have 10 different sets of this style of plot I want to make them into a 5x2 for example.

I have read through the documentation of Matplotlib and cannot seem to figure out how do it. I can loop the subplots and have each output but I cannot make it into the rows and columns

import pandas as pd
import numpy as np
import seaborn as sns

df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)),columns=list('ABCDEFGHIJ'))

for c in df :
    # Cut the window in 2 parts
    f, (ax_box,
        ax_hist) = plt.subplots(2,
                                sharex=True,
                                gridspec_kw={"height_ratios":(.15, .85)},
                                figsize = (10, 10))
    # Add a graph in each part
    sns.boxplot(df[c], ax=ax_box)
    ax_hist.hist(df[c])
    # Remove x axis name for the boxplot
plt.show()

the results would just take this loop and put them into a set of rows and columns in this case 5x2

Body:
You have 10 columns, each of which creates 2 subplots: a box plot and a histogram. So you need a total of 20 figures. You can do this by creating a grid of 2 rows and 10 columns

Complete answer: (Adjust the figsize and height_ratios as per taste)

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

f, axes = plt.subplots(2, 10, sharex=True, gridspec_kw={"height_ratios":(.35, .35)},
                                    figsize = (12, 5))

df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)),columns=list('ABCDEFGHIJ'))

for i, c in enumerate(df):
    sns.boxplot(df[c], ax=axes[0,i])
    axes[1,i].hist(df[c])
plt.tight_layout()
plt.show()


问:
display files and dir in linux as graphic mode
how to display the directories and files in graphic way

I forget the command in linux but some linux command can displayed from root directories the recursive directories like this

root

```<code>|
</code>```

sbin  etc   var ...

```<code>|   |     |

dir dir dir dir ........

|   |   |   |
|   |   |   |
</code>```

答:
You may use this :

```<code>ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
</code>```

Pay attention, this command will recursively list all files in the current directory, so don't run this command from the root directory ;)

Body:
how to display the directories and files in graphic way

I forget the command in linux but some linux command can displayed from root directories the recursive directories like this

root

|

sbin  etc   var ...

|   |     |

dir dir dir dir ........

|   |   |   |
|   |   |   |

Body:
You may use this :

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'

Pay attention, this command will recursively list all files in the current directory, so don't run this command from the root directory ;)


问:
Read Access Violation opening file from proc LUA
I program in SAS and want to write a create an xml file using LUA

So first, I start proc LUA and pass the file name
;

```<code>%let file = \\ourCompany\ourTeam\ourProject\myFile.xml;

proc lua restart;
submit;
    local file_name = sas.symget("file")
    print (file_name)
</code>```

--Next, I open the file for writing, write something and close it

```<code>    print('DEBUG: before opening')
    file = io.open (file_name, "w")
    print('DEBUG: after opening, before writing')
    file:write ("<test/>", "\n")
    print('DEBUG: after writing, before closing')
    file:close()
    print('DEBUG: after closing')
</code>```

-- and of course stop LUA

```<code>endsubmit;
run;
</code>```

/*This works: the file is created with this content

```<code><test/>
</code>```

But it results in the following messages in the log

```<code>NOTE: Lua initialized.
\\ourCompany\ourTeam\ourProject\myFile.xml
DEBUG: before opening
DEBUG: after opening, before writing
DEBUG: after writing, before closing

ERROR:  An exception has been encountered.
Please contact technical support and provide them with the following traceback information:

The SAS task name is [LUA (2)]
ERROR:  Read Access Violation LUA (2)
Exception occurred at (89400CB7)
Task Traceback
Address   Frame     (DBGHELP API Version 4.0 rev 5)
00007FFD89400CB7  000000000862F1F0  ntdll:RtlAllocateHeap+0x27
00000000084D2ACD  000000000862F1F8  sasplua:tkvercn1+0x81A8D
00000000084D0E7F  000000000862F250  sasplua:tkvercn1+0x7FE3F
00000000084D0D17  000000000862F280  sasplua:tkvercn1+0x7FCD7
00000000084CF711  000000000862F2B0  sasplua:tkvercn1+0x7E6D1
0000000008462609  000000000862F300  sasplua:tkvercn1+0x115C9
0000000008474A7D  000000000862F410  sasplua:tkvercn1+0x23A3D
0000000008485C7E  000000000862F530  sasplua:tkvercn1+0x34C3E
0000000008474349  000000000862F570  sasplua:tkvercn1+0x23309
00000000084788A4  000000000862F8D0  sasplua:tkvercn1+0x27864
0000000008478A9D  000000000862F940  sasplua:tkvercn1+0x27A5D
0000000008469746  000000000862F9A0  sasplua:tkvercn1+0x18706
00000000084523A2  000000000862F9F0  sasplua:tkvercn1+0x1362
000000000845224E  000000000862FB10  sasplua:tkvercn1+0x120E
00000000084529F4  000000000862FBF0  sasplua:tkvercn1+0x19B4
0000000001A489DB  000000000862FBF8  sashost:Main+0x10EBB
0000000001A4E61D  000000000862FF50  sashost:Main+0x16AFD
00007FFD875613F2  000000000862FF58  KERNEL32:BaseThreadInitThunk+0x22
00007FFD893E54F4  000000000862FFD0  ntdll:RtlUserThreadStart+0x34

NOTE: The SAS System stopped processing this step because of errors.
</code>```

I have no idea if this is a pure LUA issue, or something related to proc LUA in SAS.

As the last DEBUG message is not printed, the problem seems to occur while closing the file. I tried a few different options for the open command and I tried removing the io.write, but that did not help.

答:
Your code worked fine for me (on SYSVLONG=9.04.01M3P062415, SYSSCP=LIN X64).

Perhaps try the following, slightly different approach?

```<code>%let file = %sysfunc(pathname(work))/new.xml;

proc lua restart;
submit;
    local file_name = sas.symget("file")
    print (file_name)
    file = io.open (file_name, "w")
    io.output(file) -- sets default output
    io.write ("<test>", "\n")
    io.write ("write to file", "\n")
    io.write ("</test>", "\n")
    io.close(file)
endsubmit;
run;
</code>```

Body:
I program in SAS and want to write a create an xml file using LUA

So first, I start proc LUA and pass the file name
;

%let file = \\ourCompany\ourTeam\ourProject\myFile.xml;

proc lua restart;
submit;
    local file_name = sas.symget("file")
    print (file_name)

--Next, I open the file for writing, write something and close it

    print('DEBUG: before opening')
    file = io.open (file_name, "w")
    print('DEBUG: after opening, before writing')
    file:write ("<test/>", "\n")
    print('DEBUG: after writing, before closing')
    file:close()
    print('DEBUG: after closing')

-- and of course stop LUA

endsubmit;
run;

/*This works: the file is created with this content

<test/>

But it results in the following messages in the log

NOTE: Lua initialized.
\\ourCompany\ourTeam\ourProject\myFile.xml
DEBUG: before opening
DEBUG: after opening, before writing
DEBUG: after writing, before closing

ERROR:  An exception has been encountered.
Please contact technical support and provide them with the following traceback information:

The SAS task name is [LUA (2)]
ERROR:  Read Access Violation LUA (2)
Exception occurred at (89400CB7)
Task Traceback
Address   Frame     (DBGHELP API Version 4.0 rev 5)
00007FFD89400CB7  000000000862F1F0  ntdll:RtlAllocateHeap+0x27
00000000084D2ACD  000000000862F1F8  sasplua:tkvercn1+0x81A8D
00000000084D0E7F  000000000862F250  sasplua:tkvercn1+0x7FE3F
00000000084D0D17  000000000862F280  sasplua:tkvercn1+0x7FCD7
00000000084CF711  000000000862F2B0  sasplua:tkvercn1+0x7E6D1
0000000008462609  000000000862F300  sasplua:tkvercn1+0x115C9
0000000008474A7D  000000000862F410  sasplua:tkvercn1+0x23A3D
0000000008485C7E  000000000862F530  sasplua:tkvercn1+0x34C3E
0000000008474349  000000000862F570  sasplua:tkvercn1+0x23309
00000000084788A4  000000000862F8D0  sasplua:tkvercn1+0x27864
0000000008478A9D  000000000862F940  sasplua:tkvercn1+0x27A5D
0000000008469746  000000000862F9A0  sasplua:tkvercn1+0x18706
00000000084523A2  000000000862F9F0  sasplua:tkvercn1+0x1362
000000000845224E  000000000862FB10  sasplua:tkvercn1+0x120E
00000000084529F4  000000000862FBF0  sasplua:tkvercn1+0x19B4
0000000001A489DB  000000000862FBF8  sashost:Main+0x10EBB
0000000001A4E61D  000000000862FF50  sashost:Main+0x16AFD
00007FFD875613F2  000000000862FF58  KERNEL32:BaseThreadInitThunk+0x22
00007FFD893E54F4  000000000862FFD0  ntdll:RtlUserThreadStart+0x34

NOTE: The SAS System stopped processing this step because of errors.

I have no idea if this is a pure LUA issue, or something related to proc LUA in SAS.

As the last DEBUG message is not printed, the problem seems to occur while closing the file. I tried a few different options for the open command and I tried removing the io.write, but that did not help.

Body:
Your code worked fine for me (on SYSVLONG=9.04.01M3P062415, SYSSCP=LIN X64).

Perhaps try the following, slightly different approach?

%let file = %sysfunc(pathname(work))/new.xml;

proc lua restart;
submit;
    local file_name = sas.symget("file")
    print (file_name)
    file = io.open (file_name, "w")
    io.output(file) -- sets default output
    io.write ("<test>", "\n")
    io.write ("write to file", "\n")
    io.write ("</test>", "\n")
    io.close(file)
endsubmit;
run;


问:
Use multiple Heroku apps for load balancing Nginx
I need to design one system requiring:

1 Node.js Server is used for reversed proxy for load balancing by using Nginx.

4 Node.js Server is used for RESTful APIs. All of them need to be connected to the server above.

I found out that no solution for specifying in case of using multiple heroku apps for load balancing. What should I configure nginx.conf.erb file in the first server to connect 4 Heroku server in the right way? I try implementing like this link http://nginx.org/en/docs/http/load_balancing.html but I just only receive 400 base request.

答:
Heroku Round-Robin Load Balancing</p>

```<code>server {
    listen 80 default_server;
    server_name _;
    location / {
        set_formatted_local_time $upstream "%S";
        if ($upstream ~ 00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15) {
            set $backend_url http://phpmyadmin-heroku.herokuapp.com;
            set $backend_host phpmyadmin-heroku.herokuapp.com;
        }
        if ($upstream ~ 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30) {
            set $backend_url https://helloenvoy.herokuapp.com;
            set $backend_host helloenvoy.herokuapp.com;
        }
        if ($upstream ~ 31|32|33|34|35|36|37|38|39|40|41|42|43|44|45) {
            set $backend_url http://powr.herokuapp.com;
            set $backend_host powr.herokuapp.com;
        }
        if ($upstream ~ 46|47|48|49|50|51|52|53|54|55|56|57|58|59) {
            set $backend_url https://blog.heroku.com;
            set $backend_host blog.heroku.com;
        }
        proxy_pass $backend_url;
        proxy_set_header Host $backend_host;
    }
    location /load_balancing_heroku_resolver1 {
        proxy_pass http://phpmyadmin-heroku.herokuapp.com;
    }
    location /load_balancing_heroku_resolver2 {
        proxy_pass https://helloenvoy.herokuapp.com;
    }
    location /load_balancing_heroku_resolver3 {
        proxy_pass http://powr.herokuapp.com;
    }
    location /load_balancing_heroku_resolver4 {
        proxy_pass https://blog.heroku.com;
    }
}
</code>```

Body:
Heroku Round-Robin Load Balancing

server {
    listen 80 default_server;
    server_name _;
    location / {
        set_formatted_local_time $upstream "%S";
        if ($upstream ~ 00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15) {
            set $backend_url http://phpmyadmin-heroku.herokuapp.com;
            set $backend_host phpmyadmin-heroku.herokuapp.com;
        }
        if ($upstream ~ 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30) {
            set $backend_url https://helloenvoy.herokuapp.com;
            set $backend_host helloenvoy.herokuapp.com;
        }
        if ($upstream ~ 31|32|33|34|35|36|37|38|39|40|41|42|43|44|45) {
            set $backend_url http://powr.herokuapp.com;
            set $backend_host powr.herokuapp.com;
        }
        if ($upstream ~ 46|47|48|49|50|51|52|53|54|55|56|57|58|59) {
            set $backend_url https://blog.heroku.com;
            set $backend_host blog.heroku.com;
        }
        proxy_pass $backend_url;
        proxy_set_header Host $backend_host;
    }
    location /load_balancing_heroku_resolver1 {
        proxy_pass http://phpmyadmin-heroku.herokuapp.com;
    }
    location /load_balancing_heroku_resolver2 {
        proxy_pass https://helloenvoy.herokuapp.com;
    }
    location /load_balancing_heroku_resolver3 {
        proxy_pass http://powr.herokuapp.com;
    }
    location /load_balancing_heroku_resolver4 {
        proxy_pass https://blog.heroku.com;
    }
}


问:
PostgreSQL 11 UNNEST function does not exist
I am trying to run the very last example from Table 7.49 in section 9.18. Array Functions and Operators 1:

```<code>SELECT unnest(ARRAY[1,2],ARRAY['foo','bar','baz']);
</code>```

and it throws this error:

[42883] ERROR: function unnest(integer[], text[]) does not exist

Hint: No function matches the given name and argument types. You might
  need to add explicit type casts.

According to the results columns in table 7.49, it should give me:

```<code>--------------
| 1    | foo |
--------------
| 2    | bar |
--------------
| NULL | baz |
--------------
</code>```

Is there something I missed in my configuration setup to cause this?

答:
You should use FROM clause:

```<code>SELECT * FROM unnest(ARRAY[1,2],ARRAY['foo','bar','baz']);
</code>```

db<>fiddle demo

Body:
I am trying to run the very last example from Table 7.49 in section 9.18. Array Functions and Operators 1:

SELECT unnest(ARRAY[1,2],ARRAY['foo','bar','baz']);

and it throws this error:

[42883] ERROR: function unnest(integer[], text[]) does not exist

Hint: No function matches the given name and argument types. You might
  need to add explicit type casts.

According to the results columns in table 7.49, it should give me:

--------------
| 1    | foo |
--------------
| 2    | bar |
--------------
| NULL | baz |
--------------

Is there something I missed in my configuration setup to cause this?

Body:
You should use FROM clause:

SELECT * FROM unnest(ARRAY[1,2],ARRAY['foo','bar','baz']);

db<>fiddle demo


问:
Executing unix shell commands using PHP
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

答:
exec?

system?

shell_exec?

passthru?

Backticks?

Pfah!

Real developers use proc_open!  It has the major and distinct advantage of giving you three PHP streams to feed data into the process, and read both stdout and stderr.  This is something that the other process execution functions simply don't do well.

It comes at the small cost of some boilerplate code, so it's a bit more verbose.  I consider the trade-off to be excellent.

Oh, and running arbitrary commands from your users is perhaps one of the greatest security risks that you could ever conceive of, but I kind of assume you know this by now.

Title: Executing unix shell commands using PHP


问:
Calling multiple functions from within function
I am trying to call a function from within a function, and the former calls more functions etc.

```<code>import ROOT as root
import sys, math

class SFs():
    def __init__(self):
        self.get_EfficiencyData = None
        self.get_EfficiencyMC = None
        self.get_ScaleFactor = None
        self.eff_dataH = None
        self.eff_mcH = None
        self.get_ScaleFactor = None
        self.get_EfficiencyMC = None

    def ScaleFactor(self,inputRootFile):
        self.eff_dataH = root.std.map("string", root.TGraphAsymmErrors)()
        self.eff_mcH = root.std.map("string", root.TGraphAsymmErrors)()
        EtaBins=["Lt0p9", "0p9to1p2","1p2to2p1","Gt2p1"]

        fileIn = root.TFile(inputRootFile,"read")
        HistoBaseName = "Label"
        etaBinsH = fileIn.Get("Bins")
        # etaLabel, GraphName
        nEtaBins = int(etaBinsH.GetNbinsX())
        for iBin in range (0, nEtaBins):
            etaLabel = EtaBins[iBin]
            GraphName = HistoBaseName+etaLabel+"_Data"
        print GraphName,etaLabel

        self.eff_dataH[etaLabel]=fileIn.Get(str(GraphName))
        self.eff_mcH[etaLabel]=fileIn.Get("histo")

        print self.eff_mcH[etaLabel].GetXaxis().GetNbins()
        print self.eff_mcH[etaLabel].GetX()[5]
        self.get_ScaleFactor(46.8,2.0)

    def get_ScaleFactor(self,pt, eta):

        efficiency_mc = get_EfficiencyMC(pt, eta)
        if  efficiency_mc != 0.:
            SF = 1/float(efficiency_mc)
        else:
            SF=1.

        return SF

    def get_EfficiencyMC(self,pt, eta):

        label = FindEtaLabel(eta,"mc")
        # label= "Lt0p9"
        binNumber = etaBinsH.GetXaxis().FindFixBin(eta)
        label = etaBinsH.GetXaxis().GetBinLabel(binNumber)
        ptbin = FindPtBin(eff_mcH, label, pt)
        Eta = math.fabs(eta)
        print "eff_mcH ==================",eff_mcH,binNumber,label,ptbin
        # ptbin=10
        if ptbin == -99: eff =1
        else: eff= eff_mcH[label].GetY()[ptbin-1]

        if eff > 1.: eff = -1
        if eff < 0: eff = 0.
        print "inside eff_mc",eff
        return eff

    sf = SFs()
    sf.ScaleFactor("Muon_IsoMu27.root")
</code>```

I want to call the get_ScaleFactor() which in turn calls the get_EfficiencyMC() etc, but I once trying calling the former, I get TypeError: 'NoneType' object is not callable

答:
in your class init you define:

self.get_EfficiencyMC = None

and later define a function (i.e. class method)
def get_EfficiencyMC(self,pt, eta):

when you create an instance of the class, the init part is executed shadowing the class method.  Just either remove it from the init, or change the method name.

Body:
I am trying to call a function from within a function, and the former calls more functions etc.

import ROOT as root
import sys, math

class SFs():
    def __init__(self):
        self.get_EfficiencyData = None
        self.get_EfficiencyMC = None
        self.get_ScaleFactor = None
        self.eff_dataH = None
        self.eff_mcH = None
        self.get_ScaleFactor = None
        self.get_EfficiencyMC = None

    def ScaleFactor(self,inputRootFile):
        self.eff_dataH = root.std.map("string", root.TGraphAsymmErrors)()
        self.eff_mcH = root.std.map("string", root.TGraphAsymmErrors)()
        EtaBins=["Lt0p9", "0p9to1p2","1p2to2p1","Gt2p1"]

        fileIn = root.TFile(inputRootFile,"read")
        HistoBaseName = "Label"
        etaBinsH = fileIn.Get("Bins")
        # etaLabel, GraphName
        nEtaBins = int(etaBinsH.GetNbinsX())
        for iBin in range (0, nEtaBins):
            etaLabel = EtaBins[iBin]
            GraphName = HistoBaseName+etaLabel+"_Data"
        print GraphName,etaLabel

        self.eff_dataH[etaLabel]=fileIn.Get(str(GraphName))
        self.eff_mcH[etaLabel]=fileIn.Get("histo")

        print self.eff_mcH[etaLabel].GetXaxis().GetNbins()
        print self.eff_mcH[etaLabel].GetX()[5]
        self.get_ScaleFactor(46.8,2.0)

    def get_ScaleFactor(self,pt, eta):

        efficiency_mc = get_EfficiencyMC(pt, eta)
        if  efficiency_mc != 0.:
            SF = 1/float(efficiency_mc)
        else:
            SF=1.

        return SF

    def get_EfficiencyMC(self,pt, eta):

        label = FindEtaLabel(eta,"mc")
        # label= "Lt0p9"
        binNumber = etaBinsH.GetXaxis().FindFixBin(eta)
        label = etaBinsH.GetXaxis().GetBinLabel(binNumber)
        ptbin = FindPtBin(eff_mcH, label, pt)
        Eta = math.fabs(eta)
        print "eff_mcH ==================",eff_mcH,binNumber,label,ptbin
        # ptbin=10
        if ptbin == -99: eff =1
        else: eff= eff_mcH[label].GetY()[ptbin-1]

        if eff > 1.: eff = -1
        if eff < 0: eff = 0.
        print "inside eff_mc",eff
        return eff

    sf = SFs()
    sf.ScaleFactor("Muon_IsoMu27.root")

I want to call the get_ScaleFactor() which in turn calls the get_EfficiencyMC() etc, but I once trying calling the former, I get TypeError: 'NoneType' object is not callable


问:
Vim: Macro to insert a column at current cursor position
I have a variety of files that I would like to convert to comma separated variable (CSV) format.

For example:

```<code>      DATE     V1  COLOR SNOW FALL TEMPERATURE
2019-01-03 3.1415    red     33 mm          -2
2019-01-04 2.7182 orange     35 mm          -3
2019-01-05 1.6180 yellow     44 mm           2
2019-01-06 4.6692  green    120 mm           1
2019-01-07 1.4142   blue     51 mm         -10
</code>```

would become:

```<code>      DATE,     V1,  COLOR, SNOW FALL, TEMPERATURE
2019-01-03, 3.1415,    red,     33 mm,          -2
2019-01-04, 2.7182, orange,     35 mm,          -3
2019-01-05, 1.6180, yellow,     44 mm,           2
2019-01-06, 4.6692,  green,    120 mm,           1
2019-01-07, 1.4142,   blue,     51 mm,         -10
</code>```

I am able to manually do this in the vim command mode with the following:

:%s/\%[column number]c/,/

Where "[column number]" in my example would be 11 to insert a "," after the "E" in "DATE" on all lines of the file.

What I would like is to use a macro (preferably in my ".vimrc") so I could just place my cursor at a particular column and execute the macro rather than enter command mode. I am having trouble seeing how to get the cursor's current column value.

答:
So as far as I understand you want something like this:</p>

```<code>nnoremap <silent><F12> :execute '%s/\%' . col('.') . 'c/,/'<CR>
</code>```

Body:
I have a variety of files that I would like to convert to comma separated variable (CSV) format.

For example:

      DATE     V1  COLOR SNOW FALL TEMPERATURE
2019-01-03 3.1415    red     33 mm          -2
2019-01-04 2.7182 orange     35 mm          -3
2019-01-05 1.6180 yellow     44 mm           2
2019-01-06 4.6692  green    120 mm           1
2019-01-07 1.4142   blue     51 mm         -10

would become:

      DATE,     V1,  COLOR, SNOW FALL, TEMPERATURE
2019-01-03, 3.1415,    red,     33 mm,          -2
2019-01-04, 2.7182, orange,     35 mm,          -3
2019-01-05, 1.6180, yellow,     44 mm,           2
2019-01-06, 4.6692,  green,    120 mm,           1
2019-01-07, 1.4142,   blue,     51 mm,         -10

I am able to manually do this in the vim command mode with the following:

:%s/\%[column number]c/,/

Where "[column number]" in my example would be 11 to insert a "," after the "E" in "DATE" on all lines of the file.

What I would like is to use a macro (preferably in my ".vimrc") so I could just place my cursor at a particular column and execute the macro rather than enter command mode. I am having trouble seeing how to get the cursor's current column value.

Body:
So as far as I understand you want something like this:

nnoremap <silent><F12> :execute '%s/\%' . col('.') . 'c/,/'<CR>


问:
Refactoring problem from class to function with hooks
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

```<code>//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts
</code>```

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

答:
By default, the function passed to use Effect will be executed after each render of the component.

As you are updating a state variable inside your effect, it will trigger a re-render of your component, then the effect will be executed another time, basically you have an  an infinite loop.

If you pass an empty array to useEffect, you will execute the effect only once as it will be re-executed only if one value in the array has changed.

The following code should solve the problem

```<code>useEffect( () => {
  Api.getPosts()
    .then( response => {
      const [errata, data] = response
      if (errata) {
        setIsLoaded(true)
        setPosts([])
        setError(data)
      } else {
        setIsLoaded(true)
        setPosts(data)
      }
  })
}, [])
</code>```

Body:
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

Body:
By default, the function passed to use Effect will be executed after each render of the component.

As you are updating a state variable inside your effect, it will trigger a re-render of your component, then the effect will be executed another time, basically you have an  an infinite loop.

If you pass an empty array to useEffect, you will execute the effect only once as it will be re-executed only if one value in the array has changed.

The following code should solve the problem

useEffect( () => {
  Api.getPosts()
    .then( response => {
      const [errata, data] = response
      if (errata) {
        setIsLoaded(true)
        setPosts([])
        setError(data)
      } else {
        setIsLoaded(true)
        setPosts(data)
      }
  })
}, [])


问:
How to accelerate and decelerate an object in all 4 directions in tkinter?
I am trying to make a cube able to accelerate and decelerate in all 4 directions using the arrow keys. I was able to solve it for 1 direction (up), but I cannot figure out how to do it in the other 3. Basically I just need it to do what my current code does, just in all 4 directions.</p>

```<code>from tkinter import *

SPEED = 1

def handle_key(event):
    sym = event.keysym
    print(sym)
    cdx, cdy = 0, 0
    if sym == 'Up':
        dy.set(dy.get()-SPEED)
    elif sym == 'Down':
        dy.set(SPEED)
    elif sym == 'Right':
        cdx = SPEED
    elif sym == 'Left':
        cdx = -SPEED
    dx.set(cdx)

def animate():
    canvas.move(player, dx.get(), dy.get())
    if dy.get() < 0:
        dy.set(min(dy.get() + .12, 0))
    canvas.after(1, animate)

root = Tk()
dx = DoubleVar()
dy = DoubleVar()

canvas = Canvas(root, width=800, height=600)
canvas.pack()

player = canvas.create_rectangle(395, 590, 405, 600, fill='red')

canvas.bind('<Key>', handle_key)
canvas.focus_set()
animate()
root.mainloop()
</code>```

答:
Your code have few issues like function animate() will run continuously even if there is no key press event. Also the code can be a lot better like you can use <KeyPress> to accelerate and <KeyRelease> to decelerate. I created an example of what you're trying to do.

I used after(1,..) to accelerate and decelerate smoothly as continuous key presses have some noticeable delay.

```<code>from tkinter import *

root = Tk()
root.geometry('1200x50+50+0')

speed = DoubleVar(value=1)    #  Speed of the item
multiplier = DoubleVar(value=0.05)  #  Increase / Decrease rate
acc_id = None    # after id for acceleration
des_id = None    # after id for deceleration

canvas = Canvas(root, bg='pink')
canvas.pack(expand=1, fill='both')

#  Player item
player = canvas.create_rectangle(10,10,40,40, fill='grey', outline='black')

def direction(key):
    """Moves the item according to the arrow keys"""
    if key == 'Left': canvas.move(player, -speed.get()*multiplier.get(), 0)
    if key == 'Right': canvas.move(player, speed.get()*multiplier.get(), 0)
    # if key == 'Up': canvas.move(player, 0, -speed.get()*multiplier.get())
    # if key == 'Down': canvas.move(player, 0, speed.get()*multiplier.get())

def accelerate(evt=None):
    """Increase the speed."""
    global des_id, acc_id
    # set the values according to your needs
    multiplier.set( multiplier.get() + 0.05 )
    direction(evt.keysym)
    if des_id: canvas.after_cancel(des_id)
    acc_id = canvas.after(1, accelerate, evt)

def decelerate(evt=None):
    """Decrease the speed."""
    global des_id, acc_id
    if acc_id: canvas.after_cancel(acc_id)
    # set the values according to your needs
    multiplier.set( multiplier.get() - 0.05 )
    if multiplier.get() >= 0:
        direction(evt.keysym)
        des_id = canvas.after(1, decelerate, evt)

root.bind('<KeyPress>', accelerate)
root.bind('<KeyRelease>', decelerate)

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

Body:
I am trying to make a cube able to accelerate and decelerate in all 4 directions using the arrow keys. I was able to solve it for 1 direction (up), but I cannot figure out how to do it in the other 3. Basically I just need it to do what my current code does, just in all 4 directions.

from tkinter import *

SPEED = 1

def handle_key(event):
    sym = event.keysym
    print(sym)
    cdx, cdy = 0, 0
    if sym == 'Up':
        dy.set(dy.get()-SPEED)
    elif sym == 'Down':
        dy.set(SPEED)
    elif sym == 'Right':
        cdx = SPEED
    elif sym == 'Left':
        cdx = -SPEED
    dx.set(cdx)

def animate():
    canvas.move(player, dx.get(), dy.get())
    if dy.get() < 0:
        dy.set(min(dy.get() + .12, 0))
    canvas.after(1, animate)

root = Tk()
dx = DoubleVar()
dy = DoubleVar()

canvas = Canvas(root, width=800, height=600)
canvas.pack()

player = canvas.create_rectangle(395, 590, 405, 600, fill='red')

canvas.bind('<Key>', handle_key)
canvas.focus_set()
animate()
root.mainloop()

Body:
Your code have few issues like function animate() will run continuously even if there is no key press event. Also the code can be a lot better like you can use <KeyPress> to accelerate and <KeyRelease> to decelerate. I created an example of what you're trying to do.

I used after(1,..) to accelerate and decelerate smoothly as continuous key presses have some noticeable delay.

from tkinter import *

root = Tk()
root.geometry('1200x50+50+0')

speed = DoubleVar(value=1)    #  Speed of the item
multiplier = DoubleVar(value=0.05)  #  Increase / Decrease rate
acc_id = None    # after id for acceleration
des_id = None    # after id for deceleration

canvas = Canvas(root, bg='pink')
canvas.pack(expand=1, fill='both')

#  Player item
player = canvas.create_rectangle(10,10,40,40, fill='grey', outline='black')

def direction(key):
    """Moves the item according to the arrow keys"""
    if key == 'Left': canvas.move(player, -speed.get()*multiplier.get(), 0)
    if key == 'Right': canvas.move(player, speed.get()*multiplier.get(), 0)
    # if key == 'Up': canvas.move(player, 0, -speed.get()*multiplier.get())
    # if key == 'Down': canvas.move(player, 0, speed.get()*multiplier.get())

def accelerate(evt=None):
    """Increase the speed."""
    global des_id, acc_id
    # set the values according to your needs
    multiplier.set( multiplier.get() + 0.05 )
    direction(evt.keysym)
    if des_id: canvas.after_cancel(des_id)
    acc_id = canvas.after(1, accelerate, evt)

def decelerate(evt=None):
    """Decrease the speed."""
    global des_id, acc_id
    if acc_id: canvas.after_cancel(acc_id)
    # set the values according to your needs
    multiplier.set( multiplier.get() - 0.05 )
    if multiplier.get() >= 0:
        direction(evt.keysym)
        des_id = canvas.after(1, decelerate, evt)

root.bind('<KeyPress>', accelerate)
root.bind('<KeyRelease>', decelerate)

root.mainloop()


问:
Retrieve index of a List<> item based in C# using Linq
It is a pretty simple question, I have a list of an object that has a Field Named "ID".

How can I retrieve the Index of an object in the list if I know the ID?

Example:

```<code>CUSTOM_OBJECTS test = new CUSTOM_OBJECTS{ID=50};
List<CUSTOM_OBJECTS> List = new List<CUSTOM_OBJECTS>();
List.Add(test);
</code>```

I would like to retrieve the index of the object with ID = 50 in the list, which would be 0 in this example.

答:
```<code>var index = List.FindIndex(x=>x.ID==50);
</code>```

Body:
It is a pretty simple question, I have a list of an object that has a Field Named "ID".

How can I retrieve the Index of an object in the list if I know the ID?

Example:

CUSTOM_OBJECTS test = new CUSTOM_OBJECTS{ID=50};
List<CUSTOM_OBJECTS> List = new List<CUSTOM_OBJECTS>();
List.Add(test);

I would like to retrieve the index of the object with ID = 50 in the list, which would be 0 in this example.


问:
Is train_test_split necessary for binary classification? And why are there 4 outcomes?
Why are there 4 outcomes to train_test_split in sklearn? Why is there y_test, if the testing data has no y_data?</p>

答:
Looking into the documentation, you can see that the first parameter is
*arrays, which means you can put as many arrays as you want there. Now, what does it returns?

```<code>Returns:    splitting : list, length=2 * len(arrays)
</code>```

Which means it returns twice the amount of arrays passed in the train_test_split function.

So, if you already have a training and a testing set, it only makes sense to split the training set, so you can have a validation set to check the model performance.

Eg.:

```<code>train_data, validation_data, train_label, validation_label= train_test_split(original_train_data, original_train_label)
</code>```

Note that you also must split the labels in the case you have the data and the label in separated vectors.

Body:
Looking into the documentation, you can see that the first parameter is
*arrays, which means you can put as many arrays as you want there. Now, what does it returns?

Returns:    splitting : list, length=2 * len(arrays)

Which means it returns twice the amount of arrays passed in the train_test_split function.

So, if you already have a training and a testing set, it only makes sense to split the training set, so you can have a validation set to check the model performance.

Eg.:

train_data, validation_data, train_label, validation_label= train_test_split(original_train_data, original_train_label)

Note that you also must split the labels in the case you have the data and the label in separated vectors.


问:
removing spaces in DataFrame using SCALA. (I have loaded CSV file into RDD then trying to remove spaces from it
I have data with un-wanted spaces & Null values in my CSV file. I have loaded this file into spark RDD till here no problem. Now I have to remove spaces and null values from this RDD. How to do that can anyone help me pls?

```<code>object Oracle {def main(args: Array[String]): Unit = {
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
System.setProperty("hadoop.home.dir","D:\\hadoop\\");
val spark = SparkSession.builder().appName("Schema").master("local[*]").getOrCreate()

import spark.implicits._
import org.apache.spark.sql.functions._
val inpp = spark.read.csv("file:///C:/Users/user/Desktop/xyz.csv")
inpp.show()

val df = inpp.toDF("name")

inpp.select(
    col("name"),
    regexp_replace(col("name"), "\\s+$", ""),
    rtrim(col("name")),
    length(col("name"))
    ).show() }}
</code>```

Here is my data with un-wanted spaces and  null values.

答:
You can do like this:

```<code>scala> val someDFWithName = Seq((1, "anu rag"), (2,"raj u"),(3, "  ram   "), (4, null), (5, "")).toDF("id", "name")
</code>```

Now Filter the empty or null values and apply the regex to remove the extra space:

```<code>scala> someDFWithName.filter(col("name") !== "").select(
 |     col("name"),
 |     regexp_replace(col("name"), " ", ""),
 |     length(col("name"))
 |     ).show()
</code>```

Output will be:

```<code>+--------+-------------------------+------------+
|    name|regexp_replace(name,  , )|length(name)|
+--------+-------------------------+------------+
| anu rag|                   anurag|           7|
|   raj u|                     raju|           5|
|  ram   |                      ram|           8|
+--------+-------------------------+------------+
</code>```

Thanks.

Body:
I have data with un-wanted spaces & Null values in my CSV file. I have loaded this file into spark RDD till here no problem. Now I have to remove spaces and null values from this RDD. How to do that can anyone help me pls?

object Oracle {def main(args: Array[String]): Unit = {
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
System.setProperty("hadoop.home.dir","D:\\hadoop\\");
val spark = SparkSession.builder().appName("Schema").master("local[*]").getOrCreate()

import spark.implicits._
import org.apache.spark.sql.functions._
val inpp = spark.read.csv("file:///C:/Users/user/Desktop/xyz.csv")
inpp.show()

val df = inpp.toDF("name")

inpp.select(
    col("name"),
    regexp_replace(col("name"), "\\s+$", ""),
    rtrim(col("name")),
    length(col("name"))
    ).show() }}

Here is my data with un-wanted spaces and  null values.

Body:
You can do like this:

scala> val someDFWithName = Seq((1, "anu rag"), (2,"raj u"),(3, "  ram   "), (4, null), (5, "")).toDF("id", "name")

Now Filter the empty or null values and apply the regex to remove the extra space:

scala> someDFWithName.filter(col("name") !== "").select(
 |     col("name"),
 |     regexp_replace(col("name"), " ", ""),
 |     length(col("name"))
 |     ).show()

Output will be:

+--------+-------------------------+------------+
|    name|regexp_replace(name,  , )|length(name)|
+--------+-------------------------+------------+
| anu rag|                   anurag|           7|
|   raj u|                     raju|           5|
|  ram   |                      ram|           8|
+--------+-------------------------+------------+

Thanks.


问:
Quill Editor - Focus
Whenever I create another instance of the editor (in my case, through an onkeypress event), I lose focus on the editor I was typing on when the new editor is created. How can I prevent all editors from losing focus on any event?</p>

答:
Quill has a method called focus() for this.

```<code>var quill = new Quill('#editor', {
  theme: 'snow'
});

// This will focus the instance of quill editor
quill.focus()
</code>```

Title: Quill Editor - Focus

Body:
Quill has a method called focus() for this.

var quill = new Quill('#editor', {
  theme: 'snow'
});

// This will focus the instance of quill editor
quill.focus()


问:
What is an indirect goto statement?
In Clang API, there is a GotoStmt and an IndirectGotoStmt. There is very little explanation on the difference between these two kinds of goto statments. I know what a goto label; statement is. But what is an indirect goto statement? I want to know what that is in the context of C/C++ code, not necessarily just Clang. What does it mean syntactically to have an indirect goto statement? Can you provide a code example?

Edit: The following question is interesting.

Can you make a computed goto in C++

答:
There is a GNU extension that allows taking an address of a label, storing it for later use, then goto that address at a later point. See https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html for details. Example:

```<code>    void *ptr;

    if(...)
        ptr = &&foo;
    else
        ptr = &&bar;

    /* ... */
    goto *ptr;

foo:
    /* ... */

bar:
    /* ... */
</code>```

Clang supports that too, as it aims at being compatible with GCC.

The use of the above might be, for example, in implementing state machines.

Title: What is an indirect goto statement?

Body:
There is a GNU extension that allows taking an address of a label, storing it for later use, then goto that address at a later point. See https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html for details. Example:

    void *ptr;

    if(...)
        ptr = &&foo;
    else
        ptr = &&bar;

    /* ... */
    goto *ptr;

foo:
    /* ... */

bar:
    /* ... */

Clang supports that too, as it aims at being compatible with GCC.

The use of the above might be, for example, in implementing state machines.


问:
Setup reversed proxy on heroku to heroku app
I have a backend server running nodejs on heroku for example app1.herokuapp.com
I have a balancer server running nginx on heroku for example balancer.herokuapp.com with such nginx config

```<code>upstream heroku {
    server app1.herokuapp.com;
    # server app2.herokuapp.com;
    # etc..
}

server {
    listen <%= ENV['PORT']%>;
    server_name _;
    keepalive_timeout 5;

    location / {
        proxy_pass http://heroku;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}
</code>```

the problem is, when after deploying balancer app i'm trying to access my backed through proxy i'm getting such error from heroku

No such app (There's nothing here, yet.)

When i'm running backend server and balancer on localhost everything seems fine

答:
Heroku Round-Robin Load Balancing</p>

```<code>server {
    listen 80 default_server;
    server_name _;
    location / {
        set_formatted_local_time $upstream "%S";
        if ($upstream ~ 00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15) {
            set $backend_url http://phpmyadmin-heroku.herokuapp.com;
            set $backend_host phpmyadmin-heroku.herokuapp.com;
        }
        if ($upstream ~ 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30) {
            set $backend_url https://helloenvoy.herokuapp.com;
            set $backend_host helloenvoy.herokuapp.com;
        }
        if ($upstream ~ 31|32|33|34|35|36|37|38|39|40|41|42|43|44|45) {
            set $backend_url http://powr.herokuapp.com;
            set $backend_host powr.herokuapp.com;
        }
        if ($upstream ~ 46|47|48|49|50|51|52|53|54|55|56|57|58|59) {
            set $backend_url https://blog.heroku.com;
            set $backend_host blog.heroku.com;
        }
        proxy_pass $backend_url;
        proxy_set_header Host $backend_host;
    }
    location /this_is_ip_resolver_just_ignore_it_1 {
        proxy_pass http://phpmyadmin-heroku.herokuapp.com;
    }
    location /this_is_ip_resolver_just_ignore_it_2 {
        proxy_pass https://helloenvoy.herokuapp.com;
    }
    location /this_is_ip_resolver_just_ignore_it_3 {
        proxy_pass http://powr.herokuapp.com;
    }
    location /this_is_ip_resolver_just_ignore_it_4 {
        proxy_pass https://blog.heroku.com;
    }
}
</code>```

Body:
I have a backend server running nodejs on heroku for example app1.herokuapp.com
I have a balancer server running nginx on heroku for example balancer.herokuapp.com with such nginx config

upstream heroku {
    server app1.herokuapp.com;
    # server app2.herokuapp.com;
    # etc..
}

server {
    listen <%= ENV['PORT']%>;
    server_name _;
    keepalive_timeout 5;

    location / {
        proxy_pass http://heroku;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

the problem is, when after deploying balancer app i'm trying to access my backed through proxy i'm getting such error from heroku

No such app (There's nothing here, yet.)

When i'm running backend server and balancer on localhost everything seems fine

Body:
Heroku Round-Robin Load Balancing

server {
    listen 80 default_server;
    server_name _;
    location / {
        set_formatted_local_time $upstream "%S";
        if ($upstream ~ 00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15) {
            set $backend_url http://phpmyadmin-heroku.herokuapp.com;
            set $backend_host phpmyadmin-heroku.herokuapp.com;
        }
        if ($upstream ~ 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30) {
            set $backend_url https://helloenvoy.herokuapp.com;
            set $backend_host helloenvoy.herokuapp.com;
        }
        if ($upstream ~ 31|32|33|34|35|36|37|38|39|40|41|42|43|44|45) {
            set $backend_url http://powr.herokuapp.com;
            set $backend_host powr.herokuapp.com;
        }
        if ($upstream ~ 46|47|48|49|50|51|52|53|54|55|56|57|58|59) {
            set $backend_url https://blog.heroku.com;
            set $backend_host blog.heroku.com;
        }
        proxy_pass $backend_url;
        proxy_set_header Host $backend_host;
    }
    location /this_is_ip_resolver_just_ignore_it_1 {
        proxy_pass http://phpmyadmin-heroku.herokuapp.com;
    }
    location /this_is_ip_resolver_just_ignore_it_2 {
        proxy_pass https://helloenvoy.herokuapp.com;
    }
    location /this_is_ip_resolver_just_ignore_it_3 {
        proxy_pass http://powr.herokuapp.com;
    }
    location /this_is_ip_resolver_just_ignore_it_4 {
        proxy_pass https://blog.heroku.com;
    }
}


答:
Like most others (including me), you probably don't really care about the explanation, so I'll show you the answer first and the explanation afterwards.

Here's you answer:

#apple {
  fill: green;
}

#apple:hover {
  fill: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="47" height="57" viewBox="0 0 46.2 56.8">
    <path id="apple" d="M38.6,30.1c0.1,8.6,7.5,11.4,7.6,11.5c-0.1,0.2-1.2,4.1-3.9,8.1c-2.4,3.5-4.8,6.9-8.7,7
    c-3.8,0.1-5-2.3-9.4-2.3c-4.3,0-5.7,2.2-9.3,2.3c-3.7,0.1-6.6-3.7-9-7.2c-4.9-7-8.6-19.9-3.6-28.6c2.5-4.3,6.9-7,11.7-7.1
    c3.7-0.1,7.1,2.5,9.4,2.5c2.2,0,6.4-3,10.9-2.6c1.9,0.1,7,0.7,10.4,5.6C44.5,19.5,38.5,23,38.6,30.1 M31.5,9.1c2-2.4,3.3-5.7,3-9.1
    c-2.9,0.1-6.3,1.9-8.4,4.3c-1.8,2.1-3.4,5.5-3,8.8C26.2,13.3,29.5,11.5,31.5,9.1"/>
  </svg>
</body>
</html></code>```

Here's your explanation:

```<code><svg viewBox="0 0 46.2 56.8" width="47" height="57">
    <use xlink:href="#apple"/>
</svg>
</code>```

The problem was basically just, <use xlink:href="#apple"/>. You could've also just selected the svg or use element, but assuming you wanted to select that specific path, your best option is ^^.

Title: Why is the :hover selector not working on this SVG element?

Body:
When I use the selector #apple:hover to select an SVG element, the hover doesn't seem to be working. Why is this not working?

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" display="none">
 <defs>

  <path id="apple" d="M38.6,30.1c0.1,8.6,7.5,11.4,7.6,11.5c-0.1,0.2-1.2,4.1-3.9,8.1c-2.4,3.5-4.8,6.9-8.7,7
  c-3.8,0.1-5-2.3-9.4-2.3c-4.3,0-5.7,2.2-9.3,2.3c-3.7,0.1-6.6-3.7-9-7.2c-4.9-7-8.6-19.9-3.6-28.6c2.5-4.3,6.9-7,11.7-7.1
  c3.7-0.1,7.1,2.5,9.4,2.5c2.2,0,6.4-3,10.9-2.6c1.9,0.1,7,0.7,10.4,5.6C44.5,19.5,38.5,23,38.6,30.1 M31.5,9.1c2-2.4,3.3-5.7,3-9.1
  c-2.9,0.1-6.3,1.9-8.4,4.3c-1.8,2.1-3.4,5.5-3,8.8C26.2,13.3,29.5,11.5,31.5,9.1"/>
 </defs>
 </svg>
 <svg viewBox="0 0 46.2 56.8" width="47" height="57">
  <use xlink:href="#apple"/>
 </svg>

Body:
Like most others (including me), you probably don't really care about the explanation, so I'll show you the answer first and the explanation afterwards.

Here's you answer:

#apple {
  fill: green;
}

#apple:hover {
  fill: red;
}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="47" height="57" viewBox="0 0 46.2 56.8">
    <path id="apple" d="M38.6,30.1c0.1,8.6,7.5,11.4,7.6,11.5c-0.1,0.2-1.2,4.1-3.9,8.1c-2.4,3.5-4.8,6.9-8.7,7
    c-3.8,0.1-5-2.3-9.4-2.3c-4.3,0-5.7,2.2-9.3,2.3c-3.7,0.1-6.6-3.7-9-7.2c-4.9-7-8.6-19.9-3.6-28.6c2.5-4.3,6.9-7,11.7-7.1
    c3.7-0.1,7.1,2.5,9.4,2.5c2.2,0,6.4-3,10.9-2.6c1.9,0.1,7,0.7,10.4,5.6C44.5,19.5,38.5,23,38.6,30.1 M31.5,9.1c2-2.4,3.3-5.7,3-9.1
    c-2.9,0.1-6.3,1.9-8.4,4.3c-1.8,2.1-3.4,5.5-3,8.8C26.2,13.3,29.5,11.5,31.5,9.1"/>
  </svg>
</body>
</html>

Here's your explanation:

<svg viewBox="0 0 46.2 56.8" width="47" height="57">
    <use xlink:href="#apple"/>
</svg>

The problem was basically just, <use xlink:href="#apple"/>. You could've also just selected the svg or use element, but assuming you wanted to select that specific path, your best option is ^^.


问:
How to authenticate an insert or return error
im implementing a simple API CRUD using Django + Django rest and have a doubt.
I have two models:

```<code>class Shoe(models.Model):
    _id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=100, null=False, blank=False)
    provider = models.CharField(max_length=100, null=False, blank=False)
    type = models.CharField(max_length=2, choices=TIPO_CHOICES, null=False, blank=False)
    cost_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Custo',
            null=False, blank=False
            )
    sale_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Venda',
            null=False, blank=False
            )

class Stock(models.Model):
    _id = models.AutoField(primary_key=True)
    id_shoe = models.ForeignKey(
            Shoe, on_delete = models.CASCADE, verbose_name = 'shoe', related_name = 'stock')
    size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False)
    amount = models.IntegerField(null=False, default=0)
</code>```

What I am wanting is, when someone tries to make an insertion of stock of a size (of a certain shoe) that already exists it returns error. I can not just be 'unique' in the parameters of size. Any suggestions on how to do this?

答:
if you are using Django 2.2 you can use UniqueConstraint instead of unique_together like this:

```<code>class Meta:
    constraints = [
        models.UniqueConstraint(fields=['shoe', 'size'], name='give_it_some_name')
    ]
</code>```

As the docs state:

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

Body:
im implementing a simple API CRUD using Django + Django rest and have a doubt.
I have two models:

class Shoe(models.Model):
    _id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=100, null=False, blank=False)
    provider = models.CharField(max_length=100, null=False, blank=False)
    type = models.CharField(max_length=2, choices=TIPO_CHOICES, null=False, blank=False)
    cost_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Custo',
            null=False, blank=False
            )
    sale_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Venda',
            null=False, blank=False
            )

class Stock(models.Model):
    _id = models.AutoField(primary_key=True)
    id_shoe = models.ForeignKey(
            Shoe, on_delete = models.CASCADE, verbose_name = 'shoe', related_name = 'stock')
    size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False)
    amount = models.IntegerField(null=False, default=0)

What I am wanting is, when someone tries to make an insertion of stock of a size (of a certain shoe) that already exists it returns error. I can not just be 'unique' in the parameters of size. Any suggestions on how to do this?

Body:
if you are using Django 2.2 you can use UniqueConstraint instead of unique_together like this:

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['shoe', 'size'], name='give_it_some_name')
    ]

As the docs state:

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.


问:
Format Repeating Decimal as a Fraction
I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

```<code>string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0)
{
    return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
    numerator /= 2;
    denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}
</code>```

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

OwnerDisplayName: Tim Lentine

ContentLicense: CC BY-SA 2.5

Title: Format Repeating Decimal as a Fraction

Body:
I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0)
{
    return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
    numerator /= 2;
    denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

Body:
The technique I learned in middle school:

x = 0.33333
10 x = 3.33333

10x - x = 3.3333 - .3333

9x = 3

x = 3 / 9

Reduce 3/9 to 1/3.

OwnerDisplayName: abelenky


问:
Restricting number of continuous comma in a textbox
how to limit the number of continuous 'comma' in a textbox?...ex it should not allow user to enter more than 2 comma continuously  </p>

答:
```<code>private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyChar == ',')
    {
       if(TextBox.Text.Contains(",,"))
       {
           e.Handled = true;
       }
    }
}
</code>```


问:
Nuxt Layout update data on every route
I am new to Nuxt/Vue and am getting confused about how data works between different pages. I want to display a light or dark logo depending on if I am on the index page or not. When navigating between pages the data doesn't update the route name so the logo doesnt change: Layout page below.

```<code><template>
  <main>
    <img v-if="page != 'index'" src="~/assets/img/logo-white.svg">
    <img v-else src="~/assets/img/logo-dark.svg">
    <nuxt />
  </main>
</template>

<script>
  export default {
    data () {
      return {
         page: this.$route.name
      }
    }
  }
</script>
</code>```

Any help would be great.
Thanks,
Jamie

答:
Use a computed property instead of data,  $route is reactive and will trigger a computed update.

```<code>computed: {
  page() {
    return this.$route.name
  }
}
</code>```

You could also just access $route in your template.

```<code><img v-if="$route.name != 'index'" src="~/assets/img/logo-white.svg">
</code>```

Title: Nuxt Layout update data on every route

Body:
I am new to Nuxt/Vue and am getting confused about how data works between different pages. I want to display a light or dark logo depending on if I am on the index page or not. When navigating between pages the data doesn't update the route name so the logo doesnt change: Layout page below.

<template>

    <nuxt />

</template>

Any help would be great.
Thanks,
Jamie

Body:
Use a computed property instead of data,  $route is reactive and will trigger a computed update.

computed: {
  page() {
    return this.$route.name
  }
}

You could also just access $route in your template.

<img v-if="$route.name != 'index'" src="~/assets/img/logo-white.svg">


问:
my asmx service works fine on my local machine's iis which is win10. but does not work on windows server 2008 r2
I have a asmx web service which is just calls a method below KayitKontrol(). That method is using a com object. It works on my local machine but when it try it on server 2008 it stops at creating com object class Kernel.I have same settings on both iis. I couldn't figure out for a week. I profiled it with fiddler it just doesn't respond giving 504 response.

I didn't install application server. Is it something about it?

```<code>private void KayitKontrol()
        {
            using (SqlConnection conn = new SqlConnection("server=" + serverName + ";initial catalog=" +
                                                          dataBase + ";integrated security=false;uid=" +
                                                          sqlUser + ";password=" + sqlPass + ";"))
            {
                try
                {
                    foreach (var el in kasalist)
                        {
                            try
                            {
                                LogYaz("Kasa Kayıt Atılıyor.");
                                Kernel kernel = new Kernel();//stops right here which is com object.
                                Sirket sirket = default(Sirket);
                                Kasa kasa = default(Kasa);
                                sirket = kernel.yeniSirket(TVTTipi.vtMSSQL,
                                    el.Sirket,
                                    "TEMELSET",
                                    "",
                                    netUser,
                                    netPass,
                                    0);
                                kasa = kernel.yeniKasa(sirket);
                                kasa.KsMas_Kod = el.KasaKodu; //Kasa Kodu
                                kasa.IO = "C";
                                kasa.Tip = "C";
                                kasa.Kod = el.CariKodu; //Cari Kodu
                                kasa.Fisno = el.Fisno;
                                kasa.CariHareketAciklama = "Avans ödemesi(e-flow)";
                                kasa.Aciklama = el.Aciklama;
                                kasa.Tutar = el.TlTutar;
                                kasa.Plasiyer_Kodu = "3500";
                                kasa.Tarih = el.Tarih;
                                kasa.DovizTut = el.DovTutar;
                                kasa.DovizTipi = el.Dovtipi;
                                kasa.Islem(TKasaIslem.tkCariOdeme);
                                Marshal.ReleaseComObject(kasa);
                                Marshal.ReleaseComObject(sirket);
                                kernel.FreeNetsisLibrary();
                                Marshal.ReleaseComObject(kernel);
                            }
                            catch (Exception exception)
                            {
                                LogYaz(exception.ToString());
                            }
                            finally
                            {
                                LogYaz("1 kasa kaydı atıldı.");
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    LogYaz(exception.ToString());
                }
}
</code>```

答: I found the problem. It was about the identity account in iis application pool settings. I set an administrator account there and it is working now. I am a newbie.</p>

Body:
I have a asmx web service which is just calls a method below KayitKontrol(). That method is using a com object. It works on my local machine but when it try it on server 2008 it stops at creating com object class Kernel.I have same settings on both iis. I couldn't figure out for a week. I profiled it with fiddler it just doesn't respond giving 504 response.

I didn't install application server. Is it something about it?

private void KayitKontrol()
        {
            using (SqlConnection conn = new SqlConnection("server=" + serverName + ";initial catalog=" +
                                                          dataBase + ";integrated security=false;uid=" +
                                                          sqlUser + ";password=" + sqlPass + ";"))
            {
                try
                {
                    foreach (var el in kasalist)
                        {
                            try
                            {
                                LogYaz("Kasa Kayıt Atılıyor.");
                                Kernel kernel = new Kernel();//stops right here which is com object.
                                Sirket sirket = default(Sirket);
                                Kasa kasa = default(Kasa);
                                sirket = kernel.yeniSirket(TVTTipi.vtMSSQL,
                                    el.Sirket,
                                    "TEMELSET",
                                    "",
                                    netUser,
                                    netPass,
                                    0);
                                kasa = kernel.yeniKasa(sirket);
                                kasa.KsMas_Kod = el.KasaKodu; //Kasa Kodu
                                kasa.IO = "C";
                                kasa.Tip = "C";
                                kasa.Kod = el.CariKodu; //Cari Kodu
                                kasa.Fisno = el.Fisno;
                                kasa.CariHareketAciklama = "Avans ödemesi(e-flow)";
                                kasa.Aciklama = el.Aciklama;
                                kasa.Tutar = el.TlTutar;
                                kasa.Plasiyer_Kodu = "3500";
                                kasa.Tarih = el.Tarih;
                                kasa.DovizTut = el.DovTutar;
                                kasa.DovizTipi = el.Dovtipi;
                                kasa.Islem(TKasaIslem.tkCariOdeme);
                                Marshal.ReleaseComObject(kasa);
                                Marshal.ReleaseComObject(sirket);
                                kernel.FreeNetsisLibrary();
                                Marshal.ReleaseComObject(kernel);
                            }
                            catch (Exception exception)
                            {
                                LogYaz(exception.ToString());
                            }
                            finally
                            {
                                LogYaz("1 kasa kaydı atıldı.");
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    LogYaz(exception.ToString());
                }
}