问:
How to query AWS to get ELB names and attached instances to that using python boto3 modules?
I cant find code with boto3. I'm able to get elb name and InstanceID separately but cant link them together to find attached instances to ELB names.</p>

答:
This is my solution which I got it to work. Thank you John.</p>

```<code>elbList = boto3.client('elb')
ec2 = boto3.resource('ec2')

bals = elbList.describe_load_balancers()
for elb in bals['LoadBalancerDescriptions']:
    print 'ELB DNS Name : ' + elb['DNSName']
    for ec2Id in elb['Instances']:
        running_instances = \
            ec2.instances.filter(Filters=[{'Name': 'instance-state-name'
                                 , 'Values': ['running']},
                                 {'Name': 'instance-id',
                                 'Values': [ec2Id['InstanceId']]}])
        for instance in running_instances:
            print("              Instance : " + instance.public_dns_name);
</code>```

Body:
This is my solution which I got it to work. Thank you John.

elbList = boto3.client('elb')
ec2 = boto3.resource('ec2')

bals = elbList.describe_load_balancers()
for elb in bals['LoadBalancerDescriptions']:
    print 'ELB DNS Name : ' + elb['DNSName']
    for ec2Id in elb['Instances']:
        running_instances = \
            ec2.instances.filter(Filters=[{'Name': 'instance-state-name'
                                 , 'Values': ['running']},
                                 {'Name': 'instance-id',
                                 'Values': [ec2Id['InstanceId']]}])
        for instance in running_instances:
            print("              Instance : " + instance.public_dns_name);


来源: stackexchange

问:
Pass property to component
I have simple footerTab where I would like to show badge if there is notifications.

```<code><Button active={ this.props.ui.selectedTab === 'notifications' ? true : false }
        onPress={ () => this.selectedTab('notifications') }
        { ...this.props.ui.notifications ? badge : null }
>
        { this.props.ui.notifications ?
          <Badge><Text style={{ color:'white' }}>{this.props.ui.notifications}</Text></Badge> : null
        }
        <Icon name='md-notifications' />
</Button>
</code>```

With this code I'm getting 'badge is not defined'

How I can pass that badge property for Button ?

答:
After a while I realised that property badge was boolean with default true. So working version was like this.</p>

```<code>    <Button active={ this.props.ui.selectedTab === 'notifications' ? true : false }
        onPress={ () => this.selectedTab('notifications') }
        badge={ this.props.ui.notifications ? true : false }
    >
        { this.props.ui.notifications ?
          <Badge><Text style={{ color:'white' }}>
       {this.props.ui.notifications}</Text></Badge> : null
        }
        <Icon name='md-notifications' />
    </Button>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pass property to component

Body:
I have simple footerTab where I would like to show badge if there is notifications.

<Button active={ this.props.ui.selectedTab === 'notifications' ? true : false }
        onPress={ () => this.selectedTab('notifications') }
        { ...this.props.ui.notifications ? badge : null }
>
        { this.props.ui.notifications ?
          <Badge><Text style={{ color:'white' }}>{this.props.ui.notifications}</Text></Badge> : null
        }
        <Icon name='md-notifications' />
</Button>

With this code I'm getting 'badge is not defined'

How I can pass that badge property for Button ?

Body:
After a while I realised that property badge was boolean with default true. So working version was like this.

    <Button active={ this.props.ui.selectedTab === 'notifications' ? true : false }
        onPress={ () => this.selectedTab('notifications') }
        badge={ this.props.ui.notifications ? true : false }
    >
        { this.props.ui.notifications ?
          <Badge><Text style={{ color:'white' }}>
       {this.props.ui.notifications}</Text></Badge> : null
        }
        <Icon name='md-notifications' />
    </Button>


问:
PHP mail() funciton: replace sendmail using python or php script to support SMTP
It seemed the default php mail() function is not easy to configure, and it just call the OS configured sendmail function to send an email.

Though installing an alternative sendmail do the trick, but configuring such a program also depends on the OS and the its self version, hard to control about.

So I think if there is a way to write a lightweight script of python or php, and make it as an executable, then replace the sendmail path in php.ini

```<code>; For Unix only.  You may supply arguments as well (default: "sendmail -t -
; http://php.net/sendmail-path
sendmail_path = /some/script/pymail.py
</code>```

And it supports setting any SMTP account on it.

Sending mail using python is not difficult, but is there a way to adapt the input parameters to the same or compatible with the sendmail command?

Is it possible or some exisiting work on this approach?

答:
I also work out a simple script by myself:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
from sys import stdin
from email.mime.text import MIMEText
import email

s = smtplib.SMTP_SSL('smtp.mydomain.com:465')
s.login('myaccount@mydomain.com','my_password')
mail = email.message_from_string(stdin.read())
s.sendmail(
    mail['from'] or 'myaccount@mydomain.com',
    mail['to'] or mail['bcc'],
    mail.as_string()
)
s.quit()
</code>```

Just put the above script into /usr/sbin/sendmail or the actual place by which sendmail, make it executable chmod +x /usr/sbin/sendmail then test:

```<code><?php
mail(
  "target@somemail.com",
  "Email Title",
  "Email Content",
  "Content-type: text/plain; charset=utf-8;\n"
);
</code>```

Simple enough!! And just requires python to be installed.

If it is nessesary (i.e. you want to sent through TLS port 587 or direct port 25), just change some the config referencing python smtplib

Body:
It seemed the default php mail() function is not easy to configure, and it just call the OS configured sendmail function to send an email.

Though installing an alternative sendmail do the trick, but configuring such a program also depends on the OS and the its self version, hard to control about.

So I think if there is a way to write a lightweight script of python or php, and make it as an executable, then replace the sendmail path in php.ini

; For Unix only.  You may supply arguments as well (default: "sendmail -t -
; http://php.net/sendmail-path
sendmail_path = /some/script/pymail.py

And it supports setting any SMTP account on it.

Sending mail using python is not difficult, but is there a way to adapt the input parameters to the same or compatible with the sendmail command?

Is it possible or some exisiting work on this approach?

Body:
I also work out a simple script by myself:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
from sys import stdin
from email.mime.text import MIMEText
import email

s = smtplib.SMTP_SSL('smtp.mydomain.com:465')
s.login('myaccount@mydomain.com','my_password')
mail = email.message_from_string(stdin.read())
s.sendmail(
    mail['from'] or 'myaccount@mydomain.com',
    mail['to'] or mail['bcc'],
    mail.as_string()
)
s.quit()

Just put the above script into /usr/sbin/sendmail or the actual place by which sendmail, make it executable chmod +x /usr/sbin/sendmail then test:

<?php
mail(
  "target@somemail.com",
  "Email Title",
  "Email Content",
  "Content-type: text/plain; charset=utf-8;\n"
);

Simple enough!! And just requires python to be installed.

If it is nessesary (i.e. you want to sent through TLS port 587 or direct port 25), just change some the config referencing python smtplib


问:
ResNet50 nan loss with Keras 2
Since upgrading to Keras 2 I'm seeing nan loss when trying to fine tune ResNet50. Loss and accuracy look ok if I use a single convolutional layer (commented out below) instead of resnet. Am I missing something that changed with Keras 2?

from keras.applications.resnet50 import ResNet50
from keras.layers import Flatten, Dense, Input, Conv2D, Activation, Flatten
from keras.layers.pooling import MaxPooling2D
from keras.models import Model
from keras.optimizers import SGD
import numpy as np

inp = Input(batch_shape=(32, 224, 224, 3), name='input_image')

### resnet
modelres = ResNet50(weights="imagenet", include_top=False, input_tensor=inp)
x = modelres.output
x = Flatten()(x)

### single convolutional layer
#x = Conv2D(32, (3,3))(inp)
#x = Activation('relu')(x)
#x = MaxPooling2D(pool_size=(3,3))(x)
#x = Flatten()(x)
#x = Dense(units=32)(x)
predictions = Dense(units=2, kernel_initializer="he_normal", activation="softmax")(x)

model = Model(inputs=inp, outputs=predictions)
model.compile(SGD(lr=.001, momentum=0.9), "categorical_crossentropy", metrics=["accuracy"])

# generate images of all ones with the same label
def gen():
    while True:
        x_data = np.ones((32,224,224,3)).astype('float32')
        y_data = np.zeros((32,2)).astype('float32')
        y_data[:,1]=1.0
        yield x_data, y_data

model.fit_generator(gen(), 10, validation_data=gen(), validation_steps=1)
```

<p>The beginning and end of <code>model.summary()</code> looks like:</p>

```____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_image (InputLayer)         (32, 224, 224, 3)     0
____________________________________________________________________________________________________
zero_padding2d_1 (ZeroPadding2D) (32, 230, 230, 3)     0
____________________________________________________________________________________________________
conv1 (Conv2D)                   (32, 112, 112, 64)    9472

...

avg_pool (AveragePooling2D)      (32, 1, 1, 2048)      0
____________________________________________________________________________________________________
flatten_1 (Flatten)              (32, 2048)            0
____________________________________________________________________________________________________
dense_1 (Dense)                  (32, 2)               4098
====================================================================================================
```

<p>Training output is:</p>

```Epoch 1/1
10/10 [==============================] - 30s - loss: nan - acc: 0.0000e+00 - val_loss: nan - val_acc: 0.0000e+00
```

答: Everything works fine when I switch the backend to tensorflow instead of theano. Looks like something about the theano implementation broke in keras 2.</p>

Title: ResNet50 nan loss with Keras 2

Body:
Since upgrading to Keras 2 I'm seeing nan loss when trying to fine tune ResNet50. Loss and accuracy look ok if I use a single convolutional layer (commented out below) instead of resnet. Am I missing something that changed with Keras 2?

from keras.applications.resnet50 import ResNet50
from keras.layers import Flatten, Dense, Input, Conv2D, Activation, Flatten
from keras.layers.pooling import MaxPooling2D
from keras.models import Model
from keras.optimizers import SGD
import numpy as np

inp = Input(batch_shape=(32, 224, 224, 3), name='input_image')

### resnet
modelres = ResNet50(weights="imagenet", include_top=False, input_tensor=inp)
x = modelres.output
x = Flatten()(x)

### single convolutional layer
#x = Conv2D(32, (3,3))(inp)
#x = Activation('relu')(x)
#x = MaxPooling2D(pool_size=(3,3))(x)
#x = Flatten()(x)
#x = Dense(units=32)(x)
predictions = Dense(units=2, kernel_initializer="he_normal", activation="softmax")(x)

model = Model(inputs=inp, outputs=predictions)
model.compile(SGD(lr=.001, momentum=0.9), "categorical_crossentropy", metrics=["accuracy"])

# generate images of all ones with the same label
def gen():
    while True:
        x_data = np.ones((32,224,224,3)).astype('float32')
        y_data = np.zeros((32,2)).astype('float32')
        y_data[:,1]=1.0
        yield x_data, y_data

model.fit_generator(gen(), 10, validation_data=gen(), validation_steps=1)

The beginning and end of model.summary() looks like:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_image (InputLayer)         (32, 224, 224, 3)     0
____________________________________________________________________________________________________
zero_padding2d_1 (ZeroPadding2D) (32, 230, 230, 3)     0
____________________________________________________________________________________________________
conv1 (Conv2D)                   (32, 112, 112, 64)    9472

...

avg_pool (AveragePooling2D)      (32, 1, 1, 2048)      0
____________________________________________________________________________________________________
flatten_1 (Flatten)              (32, 2048)            0
____________________________________________________________________________________________________
dense_1 (Dense)                  (32, 2)               4098
====================================================================================================

Training output is:

Epoch 1/1
10/10 [==============================] - 30s - loss: nan - acc: 0.0000e+00 - val_loss: nan - val_acc: 0.0000e+00


问:
async / await with Polymer 2.0
can we use async / await with Polymer 2.0 ?

https://developers.google.com/web/fundamentals/getting-started/primers/async-functions  , As soon as I use it in my code it throws errors on hydrolysis / analysis. Any sample code will be helpful too if there is a any special guidance on this.

Regards,
S

答:
I am also interested in the subject and from what I can understand now it is not supported out of the box. Async functions are part of ES2017 and are in Draft state now. So if you want to use it you should either use transpiler like Babel or use TypeScript. In either case you need to transpile async/await to ES6 or ES5. Polymer 2.0 is going to suport TypeScript at some point, but it does not support it yet.

Check out the tutorial on how you could integrate BabelJS Build an ES2015/ES6 app with the Polymer Starter Kit

When you have transpiler in place you can use async/await everywhere where promises are supported by Polymer.

Title: async / await with Polymer 2.0


问:
Java-Abstract method not overridden
Can you help with one of the true/false questions asked in my test today:

If an abstract method is inherited by a subclass but is not overridden the whole subclass becomes abstract. Would this be true or false?

答:
If an abstract method is inherited by a subclass but is not overridden
  the whole subclass becomes abstract.

The answer is false because the class doesn't automatically or magically become abstract, rather you need to mark it as abstract if you are not overriding the one or more abstract methods.

The same concept applies even for interface as well i.e., if you are not implementing (overriding) one or more abstract methods from the interface then you need to mark the class as abstract.

So, correcting your sentence is that if an abstract method is inherited by a subclass but is not overridden, the whole subclass needs to be marked as abstract (this is true)

Title: Java-Abstract method not overridden


问:
Make notes global?
I have a client who wants to use notes and have them global across all users. It would be easiest to just remove the user dependency to display to all users. The other option is to add message_follower_ids upon creation to add a "general" channel as a follower but I'm clueless as to what the values would be.

Any thoughts, ideas, advice is greatly appreciated.

答:
You can achieve using two methods.

You can inactive record rule of note.

```<code><record id="note.note_note_rule_global" model="ir.rule">
    <field name="name">Only followers can access a sticky notes</field>
    <field name="model_id" ref="note.model_note_note"/>
    <field name="active" eval="False"/>
    <field name="domain_force">['|', ('user_id', '=', user.id), ('message_partner_ids', '=', user.partner_id.id)]</field>
    <field name="global" eval="True"/>
    <field name="perm_create" eval="False"/>
    <field name="perm_unlink" eval="False"/>
</record>
</code>```

If you inactive above record rule then odoo will visible notes to all users.

Add followers inside note.

If you hide some notes for some users then you must not inactive record rule and just add followers.

This may help you.

Title: Make notes global?

Body:
You can achieve using two methods.

You can inactive record rule of note.

<record id="note.note_note_rule_global" model="ir.rule">
    <field name="name">Only followers can access a sticky notes</field>
    <field name="model_id" ref="note.model_note_note"/>
    <field name="active" eval="False"/>
    <field name="domain_force">['|', ('user_id', '=', user.id), ('message_partner_ids', '=', user.partner_id.id)]</field>
    <field name="global" eval="True"/>
    <field name="perm_create" eval="False"/>
    <field name="perm_unlink" eval="False"/>
</record>

If you inactive above record rule then odoo will visible notes to all users.

Add followers inside note.

If you hide some notes for some users then you must not inactive record rule and just add followers.

This may help you.


问:
Distance between lat/long points using the haversine formula
I am trying to find the distance between two longitude and latitude points.  I am trying ot use the great circle distance.  This is the formula:

I am not sure why but my program is not working.  This is the result I am getting:

```<code>Change Angle: 0.00016244370761414
Earth Radius: 6371

RESULTS:
Correct  Distance: 24.883 km
Computed Distance: 1.0349288612097
</code>```

Source:

```<code>$latStart = 44.638;
$longStart = -63.587;

$latFinish = 44.644;
$longFinish = -63.597;

# Convert Input to Radians
$latStart = deg2Rad($latStart);
$longStart = deg2Rad($longStart);

$latFinish = deg2Rad($latFinish);
$longFinish = deg2Rad($longFinish);

# Because the Earth is not perfectly spherical, no single value serves as its
# natural radius. Distances from points on the surface to the center range from
# 6,353 km to 6,384 km (≈3,947–3,968 mi). Several different ways of modeling the
# Earth as a sphere each yield a convenient mean radius of 6371 km (≈3,959 mi).
# http://en.wikipedia.org/wiki/Earth_radius
$earthRadius = 6371;

# difference in Long/Lat
$latChange = $latFinish - $latStart;
$longChange = $longFinish - $longStart;

# haversine formula
# numerically stable for small distances
# http://en.wikipedia.org/wiki/Great-circle_distance
$changeAngle = 2 * asin(
                sqrt(
                        pow(sin($latChange/2),2) +
                        cos($latStart) * cos($latFinish) * pow(sin($longChange/2),2)
                )
        );

echo "Change Angle: $changeAngle\n";
echo "Earth Radius: $earthRadius\n";
</code>```

答:
Your formula looks different to my implementation. However mine's in .NET but I've unit tested it and it works well.

It's a slightly rewritten version of this: http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/

```<code>/// <summary>
/// Implementation of the Haversine formula
/// For calculating the distance between 2 points on a sphere
/// http://en.wikipedia.org/wiki/Haversine_formula
/// </summary>
public class Haversine
{
    /// <summary>
    /// Calculate the distance between 2 points in miles or kilometers
    /// http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/
    ///
    /// This assumes sea level
    /// </summary>
    public double Distance(LatLon pos1, LatLon pos2, DistanceType type)
    {
        const double RADIUS_OF_EARTH_IN_MILES = 3963.1676;
        const double RADIUS_OF_EARTH_IN_KILOMETERS = 6378.1;

        //radius of the earth
        double R = (type == DistanceType.Miles) ? RADIUS_OF_EARTH_IN_MILES : RADIUS_OF_EARTH_IN_KILOMETERS;

        //Deltas
        double dLat = ToRadian(pos2.Lat - pos1.Lat);
        double dLon = ToRadian(pos2.Lon - pos1.Lon);

        double a = Math.Sin(dLat/2)*Math.Sin(dLat/2) + Math.Cos(ToRadian(pos1.Lat))*Math.Cos(ToRadian(pos2.Lat)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
        double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));

        double d = R*c;
        return d;
    }

    /// <summary>
    /// Convert to Radians.
    /// </summary>
    private double ToRadian(double val)
    {
        return (Math.PI / 180) * val;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to find the distance between two longitude and latitude points.  I am trying ot use the great circle distance.  This is the formula:

I am not sure why but my program is not working.  This is the result I am getting:

Change Angle: 0.00016244370761414
Earth Radius: 6371

RESULTS:
Correct  Distance: 24.883 km
Computed Distance: 1.0349288612097

Source:

$latStart = 44.638;
$longStart = -63.587;

$latFinish = 44.644;
$longFinish = -63.597;

# Convert Input to Radians
$latStart = deg2Rad($latStart);
$longStart = deg2Rad($longStart);

$latFinish = deg2Rad($latFinish);
$longFinish = deg2Rad($longFinish);

# Because the Earth is not perfectly spherical, no single value serves as its
# natural radius. Distances from points on the surface to the center range from
# 6,353 km to 6,384 km (≈3,947–3,968 mi). Several different ways of modeling the
# Earth as a sphere each yield a convenient mean radius of 6371 km (≈3,959 mi).
# http://en.wikipedia.org/wiki/Earth_radius
$earthRadius = 6371;

# difference in Long/Lat
$latChange = $latFinish - $latStart;
$longChange = $longFinish - $longStart;

# haversine formula
# numerically stable for small distances
# http://en.wikipedia.org/wiki/Great-circle_distance
$changeAngle = 2 * asin(
                sqrt(
                        pow(sin($latChange/2),2) +
                        cos($latStart) * cos($latFinish) * pow(sin($longChange/2),2)
                )
        );

echo "Change Angle: $changeAngle\n";
echo "Earth Radius: $earthRadius\n";

Body:
Your formula looks different to my implementation. However mine's in .NET but I've unit tested it and it works well.

It's a slightly rewritten version of this: http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/

/// <summary>
/// Implementation of the Haversine formula
/// For calculating the distance between 2 points on a sphere
/// http://en.wikipedia.org/wiki/Haversine_formula
/// </summary>
public class Haversine
{
    /// <summary>
    /// Calculate the distance between 2 points in miles or kilometers
    /// http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/
    ///
    /// This assumes sea level
    /// </summary>
    public double Distance(LatLon pos1, LatLon pos2, DistanceType type)
    {
        const double RADIUS_OF_EARTH_IN_MILES = 3963.1676;
        const double RADIUS_OF_EARTH_IN_KILOMETERS = 6378.1;

        //radius of the earth
        double R = (type == DistanceType.Miles) ? RADIUS_OF_EARTH_IN_MILES : RADIUS_OF_EARTH_IN_KILOMETERS;

        //Deltas
        double dLat = ToRadian(pos2.Lat - pos1.Lat);
        double dLon = ToRadian(pos2.Lon - pos1.Lon);

        double a = Math.Sin(dLat/2)*Math.Sin(dLat/2) + Math.Cos(ToRadian(pos1.Lat))*Math.Cos(ToRadian(pos2.Lat)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
        double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));

        double d = R*c;
        return d;
    }

    /// <summary>
    /// Convert to Radians.
    /// </summary>
    private double ToRadian(double val)
    {
        return (Math.PI / 180) * val;
    }
}


问:
Cannot save today's date in mySQL column
This is a simple solution, but I cannot get it to work even after reading many similar posts on the topic.

I am able to define a php variable to hold the current date because I can echo it properly:

```<code>$_date_today = date('Y-d-m');
echo $_date_today;

2017-31-03
</code>```

But when I try to use that php variable to insert the date value into mySQL table, the value inserted is 0000-00-00. My date_order column in the table is defined as DATE.

答:
try to change the date format cause mysql format is Y-m-d and you are entering Y-d-m

try use this $_date_today = date('Y-m-d'); insted of $_date_today = date('Y-d-m');

Body:
This is a simple solution, but I cannot get it to work even after reading many similar posts on the topic.

I am able to define a php variable to hold the current date because I can echo it properly:

$_date_today = date('Y-d-m');
echo $_date_today;

2017-31-03

But when I try to use that php variable to insert the date value into mySQL table, the value inserted is 0000-00-00. My date_order column in the table is defined as DATE.


问:
Issue with JSON request - rails/faraday
I have an issue with rails and faraday when I try to receive access token which should be included in a JSON response from the external Api.

What I want to do is user authentication based on external API.
I assume that the User already has valid credentials (in this case email as username and password).

Now when he connects to my Api, I send JSON request to the external Api to verify whether this user is valid and wait for access token.

Once the access token is sent in a response, user authentication is successful and I have access to the other endpoints

This is my controller

```<code>module Api
  class AuthenticationController < ApplicationController
    def create
      client = XXX::AuthClient.new

      response = client.authenticate(
        email: params[:email],
        password: params[:password]
      )

      api_client = XXX::Client.new(response[:access_token])

      if response[:access_token]
        api_user = api_client.get_user()

        if api_user["id"]
          db_user = User.create(xxx_id: api_user["id"], xxx_access_token: response[:access_token])
        end
      end

      render json: { access_token: db_user.access_token }
    end
  end
end
</code>```

And this is my AuthClient service

```<code>class AuthClient
    def initialize
      @http_client = Faraday.new('https://auth.xxx.com/')
    end

    def authenticate(email:, password:)
      headers = {
        'Content-Type': 'application/json'
      }.to_json

      body = {
        grant_type: "password",
        username: email,
        password: password,
        client_id: "particularclientid",
        client_secret: "particularclientsecret"
      }.to_json

      api_response = http_client.post("/oauth2/token", body)
      response = JSON.parse(api_response.body)

      if response["access_token"]
        { access_token: access_token }
      else
        { error: "autentication error" }
      end

    end

    private

    attr_reader :http_client
  end
end
</code>```

What I know is that curl in the following format is correct and I can see User's access token, refresh token etc.

```<code>curl -X POST -H "Content-Type: application/json" -d '{
"grant_type": "password",
"username": "test+user@example.com",
"password": "examplepassword",
"client_id": "particularclientid",
"client_secret": "particularclientsecret"
}' "https://auth.xxx.com/oauth2/token"
</code>```

But when I run my curl

```<code>curl -X POST -d 'email=test+user@example.com&password=examplepassword' "http://localhost:3000/api/auth"
</code>```

I see that my request is not correct. But I have no clue where is the problem because header and body are formatted to JSON (I have entered puts headers, puts body and puts response to verify that).

```<code>Started POST "/api/auth" for 127.0.0.1 at 2017-03-31 16:42:26 +0200
Processing by Api::AuthenticationController#create as */*
  Parameters: {"email"=>"test user@example.com", "password"=>"[FILTERED]"}
{"Content-Type":"application/json"}
{"grant_type":"password","username":"test user@example.com","password":"examplepassword","client_id":"particularclientid","client_secret":"particularclientsecret"}
{"error"=>"invalid_request", "error_description"=>"The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed."}
Completed 500 Internal Server Error in 610ms (ActiveRecord: 0.0ms)

NoMethodError (undefined method `access_token' for nil:NilClass):

app/controllers/api/authentication_controller.rb:21:in `create'
</code>```

Is my request incorrect or the problem exists somewhere else?
I am not experienced developer. Just trying to learn enough to start as a Junior RoR. I tried to find a solution on stack and on different sites but I am stucked. Even faraday docs does not help me much

答:
When URIs are escaped, a + is used as a replacement for whitespace. As such, when your controller un-escapes the URI, the + is changed back into a space. If you want to send a space, use %2B instead.

For your first problem, the error message indicates that db_user is nil when you try to do db_user.access_token. So, either response[:access_token] is nil, api_user["id"] is nil, or User.create failed.

You'll need to put in some debugging to find out where your problem is.

Title: Issue with JSON request - rails/faraday

Body:
I have an issue with rails and faraday when I try to receive access token which should be included in a JSON response from the external Api.

What I want to do is user authentication based on external API.
I assume that the User already has valid credentials (in this case email as username and password).

Now when he connects to my Api, I send JSON request to the external Api to verify whether this user is valid and wait for access token.

Once the access token is sent in a response, user authentication is successful and I have access to the other endpoints

This is my controller

module Api
  class AuthenticationController < ApplicationController
    def create
      client = XXX::AuthClient.new

      response = client.authenticate(
        email: params[:email],
        password: params[:password]
      )

      api_client = XXX::Client.new(response[:access_token])

      if response[:access_token]
        api_user = api_client.get_user()

        if api_user["id"]
          db_user = User.create(xxx_id: api_user["id"], xxx_access_token: response[:access_token])
        end
      end

      render json: { access_token: db_user.access_token }
    end
  end
end

And this is my AuthClient service

class AuthClient
    def initialize
      @http_client = Faraday.new('https://auth.xxx.com/')
    end

    def authenticate(email:, password:)
      headers = {
        'Content-Type': 'application/json'
      }.to_json

      body = {
        grant_type: "password",
        username: email,
        password: password,
        client_id: "particularclientid",
        client_secret: "particularclientsecret"
      }.to_json

      api_response = http_client.post("/oauth2/token", body)
      response = JSON.parse(api_response.body)

      if response["access_token"]
        { access_token: access_token }
      else
        { error: "autentication error" }
      end

    end

    private

    attr_reader :http_client
  end
end

What I know is that curl in the following format is correct and I can see User's access token, refresh token etc.

curl -X POST -H "Content-Type: application/json" -d '{
"grant_type": "password",
"username": "test+user@example.com",
"password": "examplepassword",
"client_id": "particularclientid",
"client_secret": "particularclientsecret"
}' "https://auth.xxx.com/oauth2/token"

But when I run my curl

curl -X POST -d 'email=test+user@example.com&password=examplepassword' "http://localhost:3000/api/auth"

I see that my request is not correct. But I have no clue where is the problem because header and body are formatted to JSON (I have entered puts headers, puts body and puts response to verify that).

Started POST "/api/auth" for 127.0.0.1 at 2017-03-31 16:42:26 +0200
Processing by Api::AuthenticationController#create as */*
  Parameters: {"email"=>"test user@example.com", "password"=>"[FILTERED]"}
{"Content-Type":"application/json"}
{"grant_type":"password","username":"test user@example.com","password":"examplepassword","client_id":"particularclientid","client_secret":"particularclientsecret"}
{"error"=>"invalid_request", "error_description"=>"The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed."}
Completed 500 Internal Server Error in 610ms (ActiveRecord: 0.0ms)

NoMethodError (undefined method `access_token' for nil:NilClass):

app/controllers/api/authentication_controller.rb:21:in `create'

Is my request incorrect or the problem exists somewhere else?
I am not experienced developer. Just trying to learn enough to start as a Junior RoR. I tried to find a solution on stack and on different sites but I am stucked. Even faraday docs does not help me much


问:
Resize image before displaying it in ImageView
I'm working on a fragment that should load an image from the internet, resize it and then display it to the user. The goal is to use the image for a GridView later on. But I can't seem to get the resizing working at all. I've been stuck for a couple of hours trying different methods without any luck.

Here's my code:

VaultFragment.cs:

```<code>using Android.OS;
using Android.Views;
using SupportFragment = Android.Support.V4.App.Fragment;
using Android.Support.V4.Widget;
using System.Collections.Generic;
using Android.Widget;
using System.Net;
using System;
using System.IO;
using Android.Graphics;

namespace Test_android.Fragments
{
    public class VaultFragment : SupportFragment
    {
        // Global variables
        private SwipeRefreshLayout gSwipeRefreshLayout;
        ImageView imageview;

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // return our custom view for this fragment
            View view = inflater.Inflate(Resource.Layout.Vault, container, false);

            // Add SwipeRefreshLayout
            gSwipeRefreshLayout = view.FindViewById<SwipeRefreshLayout>(Resource.Id.swipeLayout);

            imageview = new ImageView(view.Context);
            DownloadRemoteImageFile();

            return view;

        }

        private async void DownloadRemoteImageFile()
        {
            WebClient webClient = new WebClient();
            var url = new Uri("https://logo.clearbit.com/cnn.com");
            byte[] bytes = null;
            try
            {
                bytes = await webClient.DownloadDataTaskAsync(url);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());

                return;
            }

            MemoryStream ms = new MemoryStream(bytes);

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = false;
            int sampleSize = options.OutWidth / 100;
            options.OutWidth = 57;
            options.OutHeight = 57;

            Bitmap bitmap = BitmapFactory.DecodeStream(ms, null, options);
            //imageview.LayoutParameters = new LinearLayout.LayoutParams(57,57);

            var f = imageview.LayoutParameters;
            imageview.SetImageBitmap(bitmap);
            gSwipeRefreshLayout.AddView(imageview);

        }

    }
}
</code>```

Vault.axml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.widget.SwipeRefreshLayout>
</code>```

This is what it looks like when I run it filling up the whole screen:

答:
try this

```<code> Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
</code>```

or

```<code>public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);

// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
    bm, 0, 0, width, height, matrix, false);
bm.recycle();
    return resizedBitmap;
}
</code>```

Work for me android studio  (java) I don't know where I get C#

Body:
I'm working on a fragment that should load an image from the internet, resize it and then display it to the user. The goal is to use the image for a GridView later on. But I can't seem to get the resizing working at all. I've been stuck for a couple of hours trying different methods without any luck.

Here's my code:

VaultFragment.cs:

using Android.OS;
using Android.Views;
using SupportFragment = Android.Support.V4.App.Fragment;
using Android.Support.V4.Widget;
using System.Collections.Generic;
using Android.Widget;
using System.Net;
using System;
using System.IO;
using Android.Graphics;

namespace Test_android.Fragments
{
    public class VaultFragment : SupportFragment
    {
        // Global variables
        private SwipeRefreshLayout gSwipeRefreshLayout;
        ImageView imageview;

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // return our custom view for this fragment
            View view = inflater.Inflate(Resource.Layout.Vault, container, false);

            // Add SwipeRefreshLayout
            gSwipeRefreshLayout = view.FindViewById<SwipeRefreshLayout>(Resource.Id.swipeLayout);

            imageview = new ImageView(view.Context);
            DownloadRemoteImageFile();

            return view;

        }

        private async void DownloadRemoteImageFile()
        {
            WebClient webClient = new WebClient();
            var url = new Uri("https://logo.clearbit.com/cnn.com");
            byte[] bytes = null;
            try
            {
                bytes = await webClient.DownloadDataTaskAsync(url);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());

                return;
            }

            MemoryStream ms = new MemoryStream(bytes);

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = false;
            int sampleSize = options.OutWidth / 100;
            options.OutWidth = 57;
            options.OutHeight = 57;

            Bitmap bitmap = BitmapFactory.DecodeStream(ms, null, options);
            //imageview.LayoutParameters = new LinearLayout.LayoutParams(57,57);

            var f = imageview.LayoutParameters;
            imageview.SetImageBitmap(bitmap);
            gSwipeRefreshLayout.AddView(imageview);

        }

    }
}

Vault.axml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.widget.SwipeRefreshLayout>

This is what it looks like when I run it filling up the whole screen:

Body:
try this

 Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));

or

public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);

// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
    bm, 0, 0, width, height, matrix, false);
bm.recycle();
    return resizedBitmap;
}

Work for me android studio  (java) I don't know where I get C#


问:
ManagementObject Class not showing up in System.Management namespace
I'm trying to write some WMI in my windows form and the ManagementObject is givin me the

"The type or namespace name 'ManagementObject' could not be found" Error

Here is my un-complete code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Security.Policy;
using System.Management;
using System.Management.Instrumentation;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"");
</code>```

答:
Make sure your project isn't set up to compile against the .NET 4 Framework Client Profile.

Please see Namespace not recognized (even though it is there) for more details.

Body:
I'm trying to write some WMI in my windows form and the ManagementObject is givin me the

"The type or namespace name 'ManagementObject' could not be found" Error

Here is my un-complete code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Security.Policy;
using System.Management;
using System.Management.Instrumentation;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"");


问:
React Test Renderer Simulating Clicks on Elements
I'm testing a React component using Jest v16.0.1, react-test-renderer v15.4.0 and react-addons-test-utils v15.4.0.

The component has rendered a button:

```<code><button
    type="button"
    className="btn btn-lg btn-primary btn-danger"
    disabled={this.state.cancelButtonDisabled}
    onClick={() => this.handleCancel()}
    ref="cancelButton"
>Cancel</button>);
</code>```

And in my test I'm rendering the component like so:

```<code>const component = renderer.create(
    <MyComponent />
);

const instance = component.getInstance();
// This works but is ugly
component.toJSON().children[1].children[0].props.onClick();
// This doesn't work
ReactTestUtils.Simulate.click(instance.refs.cancelButton);

let tree = component.toJSON();
expect(tree).toMatchSnapshot();
</code>```

What is the recommended way to simulate a click on this button? You can traverse the JSON representation of the component but it seems like their should be a better way.

Before when I was using ReactTestUtils.renderIntoDocument you could pass in a reference to the component using refs to ReactTestUtils.Simulate.click

I've seen this question - How to interact with components rendered by ReactTestRenderer / Jest but I assume the API has changed as my component instance has no find() method.

答:
Maybe it's too late but find is an API from enzyme. The answer on the question you referred to assumed enzyme is used as mentioned on the comment.

Something like this should work.

MyComponent.jsx

```<code>import React from 'react';

class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      cancelButtonDisabled: false,
    };
  }
  handleCancel() {
    this.props.cancelAction();
  }
  render() {
    return (
      <button
        type="button"
        className="btn btn-lg btn-primary btn-danger"
        disabled={this.state.cancelButtonDisabled}
        onClick={() => this.handleCancel()}
        ref="cancelButton"
      >
        Cancel
      </button>
    );
  }
}

export default MyComponent;
</code>```

MyComponent.test.jsx

```<code>import React from 'react';
import {mount} from 'enzyme';
import MyComponent from './MyComponent';

describe('Test MyComponent', () => {
  it('should be able to click the button', () => {
    const mockFunction = jest.fn();
    const element = mount(<MyComponent cancelAction={mockFunction} />);
    element.find('button').simulate('click');
    expect(mockFunction).toHaveBeenCalled();
  });
});
</code>```

without enzyme, it would look like this.

MyComponentWithoutEnzyme.test.jsx

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import MyComponent from './MyComponent';

describe('Test MyComponent', () => {
  it('should be able to click the button', () => {
    const mockFunction = jest.fn();
    const element = ReactTestUtils.renderIntoDocument(
      <MyComponent cancelAction={mockFunction} />,
    );
    const button = ReactDOM.findDOMNode(element);
    ReactTestUtils.Simulate.click(button);
    expect(mockFunction).toHaveBeenCalled();
  });
});
</code>```

Body:
I'm testing a React component using Jest v16.0.1, react-test-renderer v15.4.0 and react-addons-test-utils v15.4.0.

The component has rendered a button:

<button
    type="button"
    className="btn btn-lg btn-primary btn-danger"
    disabled={this.state.cancelButtonDisabled}
    onClick={() => this.handleCancel()}
    ref="cancelButton"
>Cancel</button>);

And in my test I'm rendering the component like so:

const component = renderer.create(
    <MyComponent />
);

const instance = component.getInstance();
// This works but is ugly
component.toJSON().children[1].children[0].props.onClick();
// This doesn't work
ReactTestUtils.Simulate.click(instance.refs.cancelButton);

let tree = component.toJSON();
expect(tree).toMatchSnapshot();

What is the recommended way to simulate a click on this button? You can traverse the JSON representation of the component but it seems like their should be a better way.

Before when I was using ReactTestUtils.renderIntoDocument you could pass in a reference to the component using refs to ReactTestUtils.Simulate.click

I've seen this question - How to interact with components rendered by ReactTestRenderer / Jest but I assume the API has changed as my component instance has no find() method.

Body:
Maybe it's too late but find is an API from enzyme. The answer on the question you referred to assumed enzyme is used as mentioned on the comment.

Something like this should work.

MyComponent.jsx

import React from 'react';

class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      cancelButtonDisabled: false,
    };
  }
  handleCancel() {
    this.props.cancelAction();
  }
  render() {
    return (
      <button
        type="button"
        className="btn btn-lg btn-primary btn-danger"
        disabled={this.state.cancelButtonDisabled}
        onClick={() => this.handleCancel()}
        ref="cancelButton"
      >
        Cancel
      </button>
    );
  }
}

export default MyComponent;

MyComponent.test.jsx

import React from 'react';
import {mount} from 'enzyme';
import MyComponent from './MyComponent';

describe('Test MyComponent', () => {
  it('should be able to click the button', () => {
    const mockFunction = jest.fn();
    const element = mount(<MyComponent cancelAction={mockFunction} />);
    element.find('button').simulate('click');
    expect(mockFunction).toHaveBeenCalled();
  });
});

without enzyme, it would look like this.

MyComponentWithoutEnzyme.test.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import MyComponent from './MyComponent';

describe('Test MyComponent', () => {
  it('should be able to click the button', () => {
    const mockFunction = jest.fn();
    const element = ReactTestUtils.renderIntoDocument(
      <MyComponent cancelAction={mockFunction} />,
    );
    const button = ReactDOM.findDOMNode(element);
    ReactTestUtils.Simulate.click(button);
    expect(mockFunction).toHaveBeenCalled();
  });
});


问:
Constructing XML-Like Mark-Up in ForEach Loop with PHP
I have an array

```<code>[0] => 0101010101-0101010101
[1] => 1212121212-1212121212
[2] => 2323232323-2323232323
[3] => 3434343434-3434343434
</code>```

in a variable defined as $legacyorderid

I'm trying to create another variable called $orderid which, constructed in my foreach loop, will output like this:

```<code><OrderId>0101010101-0101010101</OrderID><OrderId>1212121212-1212121212</OrderID><OrderId>2323232323-2323232323</OrderID><OrderId>3434343434-3434343434</OrderID>
</code>```

I'm using concatenation in my foreach loop, but it's still not working

```<code>foreach ($legacyorderid as $num => $orderid2) {
    $orderid .= '<OrderID>' . $orderid2 . '</OrderID>';
}
</code>```

All this is outputting in an echo of orderid is:

```<code>0101010101-01010101011212121212-12121212122323232323-23232323233434343434-3434343434
</code>```

How do I get my <OrderID> and </OrderID> into my $orderid variable like the desired output above?

答: You're viewing the file as HTML, not XML...  If you open inspect/view source, you will see the tags.</p>

Body:
I have an array

[0] => 0101010101-0101010101
[1] => 1212121212-1212121212
[2] => 2323232323-2323232323
[3] => 3434343434-3434343434

in a variable defined as $legacyorderid

I'm trying to create another variable called $orderid which, constructed in my foreach loop, will output like this:

<OrderId>0101010101-0101010101</OrderID><OrderId>1212121212-1212121212</OrderID><OrderId>2323232323-2323232323</OrderID><OrderId>3434343434-3434343434</OrderID>

I'm using concatenation in my foreach loop, but it's still not working

foreach ($legacyorderid as $num => $orderid2) {
    $orderid .= '<OrderID>' . $orderid2 . '</OrderID>';
}

All this is outputting in an echo of orderid is:

0101010101-01010101011212121212-12121212122323232323-23232323233434343434-3434343434

How do I get my <OrderID> and </OrderID> into my $orderid variable like the desired output above?


问:
How to change gamestates in LibGdx using stacks
I am making a game in android like flappy bird and I am able to go from the menu state to the playState but when the game is over and when I try to get the menu state back it just gives me the background or sometimes a white screen.

```<code>public class FlappyDemo extends ApplicationAdapter {//ApplicatoonListener

public static final int width=480;
public static final int height=800;
public static final String title="Flappy Bird";
public GameStateManager gsm;
/*private*/public SpriteBatch spriteBatch;
public void create () {
    spriteBatch=new SpriteBatch();
    gsm=new GameStateManager();
    gsm.push(new MenuState(gsm));

    Gdx.gl.glClearColor(1,1,1,1);

}

@Override
public void render () {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    gsm.update(Gdx.graphics.getDeltaTime());
    gsm.render(spriteBatch);

}
</code>```

}

```<code>public abstract class State {
OrthographicCamera cam;
Vector3 mouse;
GameStateManager gsm;
public State(GameStateManager gsm){
    this.gsm=gsm;
    mouse=new Vector3();

    cam = new OrthographicCamera();
}
public abstract void handleInput();
public abstract void update(float dt);
public abstract void render(SpriteBatch sb);
public abstract void dispose();
</code>```

}

```<code>public class GameStateManager {

private Stack<State> states;

public GameStateManager(){
    states=new Stack<State>();
}
public void push(State state){
    states.push(state);

    }
public void pop(){
    states.pop();
}

public void set(State state){
    states.pop().dispose();
    states.push(state);

}

public void update(float dt){
    states.peek().update(dt);

}
public void render(SpriteBatch sb){
    states.peek().render(sb);
}
</code>```

}

```<code>public class MenuState extends State {

Texture background;
Texture playBtn;
public MenuState(GameStateManager gsm) {
    super(gsm);
    background=new Texture("bg.png");
    playBtn=new Texture("buttonflappy.jpg");
}

@Override
public void handleInput() {
    if(Gdx.input.isTouched()) {
        gsm.push(new PlayState(gsm));
    }

}

@Override
public void update(float dt) {
    handleInput();
}

@Override
public void render(SpriteBatch sb) {
    sb.begin();
    sb.draw(background,0,0, 1100,1800);
    sb.draw(playBtn,1100/2, 1800/2);
    sb.end();
}

@Override
public void dispose() {
    playBtn.dispose();
    background.dispose();

}
</code>```

}

so first I call the push method and pass it the MENUSTATE and than in the menustate I call the push method and pass it the PlayState to start the game and in the PLayState I have got the gameplay, cameras,viewports. Now when I say that if the bird hits the tube or the ground the menustate should be called again all I get is a green screen which is the background of the playstate.

```<code>  if (tube.collide(bird.getBirdBound())) {

                gsm.set(new MenuState(gsm));

            }
            if (bird.getPosition().y <= ground.getHeight() + offset) {

                gsm.set(new MenuState(gsm));

            }
</code>```

this is the calling method to the gamestate manager when the game ends and the menustate should be called.
So can anyone tell me how can I get the menustate back instead of getting the background color i.e green.
Really appreciate if anyone could help.

答: I finally got it the problem was that I was not changing the camera position. SO what I did was that in the menustate I used the camera and set its position cam.setToOrtho(false,1100,1800) the position where I had drawn the background and updated the camera so now when in the playstate I poped the current state and went back to to the menustate my camera was pointing at the menustate insted of the green color.</p>

Body:
I am making a game in android like flappy bird and I am able to go from the menu state to the playState but when the game is over and when I try to get the menu state back it just gives me the background or sometimes a white screen.

public class FlappyDemo extends ApplicationAdapter {//ApplicatoonListener

public static final int width=480;
public static final int height=800;
public static final String title="Flappy Bird";
public GameStateManager gsm;
/*private*/public SpriteBatch spriteBatch;
public void create () {
    spriteBatch=new SpriteBatch();
    gsm=new GameStateManager();
    gsm.push(new MenuState(gsm));

    Gdx.gl.glClearColor(1,1,1,1);

}

@Override
public void render () {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    gsm.update(Gdx.graphics.getDeltaTime());
    gsm.render(spriteBatch);

}

}

public abstract class State {
OrthographicCamera cam;
Vector3 mouse;
GameStateManager gsm;
public State(GameStateManager gsm){
    this.gsm=gsm;
    mouse=new Vector3();

    cam = new OrthographicCamera();
}
public abstract void handleInput();
public abstract void update(float dt);
public abstract void render(SpriteBatch sb);
public abstract void dispose();

}

public class GameStateManager {

private Stack<State> states;

public GameStateManager(){
    states=new Stack<State>();
}
public void push(State state){
    states.push(state);

    }
public void pop(){
    states.pop();
}

public void set(State state){
    states.pop().dispose();
    states.push(state);

}

public void update(float dt){
    states.peek().update(dt);

}
public void render(SpriteBatch sb){
    states.peek().render(sb);
}

}

public class MenuState extends State {

Texture background;
Texture playBtn;
public MenuState(GameStateManager gsm) {
    super(gsm);
    background=new Texture("bg.png");
    playBtn=new Texture("buttonflappy.jpg");
}

@Override
public void handleInput() {
    if(Gdx.input.isTouched()) {
        gsm.push(new PlayState(gsm));
    }

}

@Override
public void update(float dt) {
    handleInput();
}

@Override
public void render(SpriteBatch sb) {
    sb.begin();
    sb.draw(background,0,0, 1100,1800);
    sb.draw(playBtn,1100/2, 1800/2);
    sb.end();
}

@Override
public void dispose() {
    playBtn.dispose();
    background.dispose();

}

}

so first I call the push method and pass it the MENUSTATE and than in the menustate I call the push method and pass it the PlayState to start the game and in the PLayState I have got the gameplay, cameras,viewports. Now when I say that if the bird hits the tube or the ground the menustate should be called again all I get is a green screen which is the background of the playstate.

  if (tube.collide(bird.getBirdBound())) {

                gsm.set(new MenuState(gsm));

            }
            if (bird.getPosition().y <= ground.getHeight() + offset) {

                gsm.set(new MenuState(gsm));

            }

this is the calling method to the gamestate manager when the game ends and the menustate should be called.
So can anyone tell me how can I get the menustate back instead of getting the background color i.e green.
Really appreciate if anyone could help.


问:
enum combination - vb.net
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Enum for storing and processing tasks As :

```<code>Public Enum TaskStatus
    none = 0
    completed = 2
    executing = 4
    executed = 8
    errors = 16
    uploaded = 32
    incomplete = 64
    all =-1
End Enum

Private Function Manage()
    Dim ts As TaskStatus = TaskStatus.none
    '' Task Performed with Error
    ts = TaskStatus.errors Or TaskStatus.executed
    '' Task Uploading
    ts = ts Or TaskStatus.uploaded
    ts = ts Or TaskStatus.completed
    CheckStatus(ts)
End Function

Private Function CheckStatus(ByVal ts As TaskStatus)
    '' Now i have to check for two or More Enums
    '' ts have current values := Error , Executed, Uploaded , Completed

    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' It is not working
    End If
    If ts = (TaskStatus.executed Or TaskStatus.uploaded Or TaskStatus.completed) Then
        '' It is not working
    End If
    If ts And (TaskStatus.uploaded Or TaskStatus.executed) Then
       '' Working, But Not Sure is it correct way ?
    End If
    If (ts And TaskStatus.completed) = TaskStatus.completed Then
        '' Completed
    End If
End Function
</code>```

Since ts have current values := Error Or Executed Or  Uploaded Or  Completed.

I can not use HasFlag due to framework 3.5.

How to compare If enum contains two or more specific values in it, as described in code ?

答:
To check for two flags while ignoring any other flags, perhaps something like:

```<code>If (ts And (TaskStatus.uploaded Or TaskStatus.errors)) =
        (TaskStatus.uploaded Or TaskStatus.errors) Then
    ' ...
End If
</code>```

which is pretty ugly.  A helper method would make things a bit better:

```<code>Function HasFlags(value As TaskStatus, flags As TaskStatus) As Boolean
    Return (value And flags) = flags
End Function

If HasFlags(ts, TaskStatus.uploaded Or TaskStatus.errors) Then
    ' ...
End If
</code>```

You can pass in as many flags as you want to check for.

Title: enum combination - vb.net

Body:
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Enum for storing and processing tasks As :

Public Enum TaskStatus
    none = 0
    completed = 2
    executing = 4
    executed = 8
    errors = 16
    uploaded = 32
    incomplete = 64
    all =-1
End Enum

Private Function Manage()
    Dim ts As TaskStatus = TaskStatus.none
    '' Task Performed with Error
    ts = TaskStatus.errors Or TaskStatus.executed
    '' Task Uploading
    ts = ts Or TaskStatus.uploaded
    ts = ts Or TaskStatus.completed
    CheckStatus(ts)
End Function

Private Function CheckStatus(ByVal ts As TaskStatus)
    '' Now i have to check for two or More Enums
    '' ts have current values := Error , Executed, Uploaded , Completed

    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' It is not working
    End If
    If ts = (TaskStatus.executed Or TaskStatus.uploaded Or TaskStatus.completed) Then
        '' It is not working
    End If
    If ts And (TaskStatus.uploaded Or TaskStatus.executed) Then
       '' Working, But Not Sure is it correct way ?
    End If
    If (ts And TaskStatus.completed) = TaskStatus.completed Then
        '' Completed
    End If
End Function

Since ts have current values := Error Or Executed Or  Uploaded Or  Completed.

I can not use HasFlag due to framework 3.5.

How to compare If enum contains two or more specific values in it, as described in code ?

Body:
To check for two flags while ignoring any other flags, perhaps something like:

If (ts And (TaskStatus.uploaded Or TaskStatus.errors)) =
        (TaskStatus.uploaded Or TaskStatus.errors) Then
    ' ...
End If

which is pretty ugly.  A helper method would make things a bit better:

Function HasFlags(value As TaskStatus, flags As TaskStatus) As Boolean
    Return (value And flags) = flags
End Function

If HasFlags(ts, TaskStatus.uploaded Or TaskStatus.errors) Then
    ' ...
End If

You can pass in as many flags as you want to check for.


问:
Customizing "More" Tab Bar
I am using a tab bar (UITabBarController) on my app and I wish to customize the appearance of the table that appears when you click the more button.

My app customized with a background image on every page. But image is not displaying when i click more button.

Any ideas?

答:
It sounds like you have a UINavigationController as the main VC of your app, and a UITabBarController as one of the VC's on its stack.

I believe Apple actively discourages people from doing this in their apps, and so do I. It is never done in the iOS itself, and I have never seen it in any third-party apps either, so users will probably be confused.

I think you should embed the UINavigationController inside the UITabBarController instead of the other way around, or you could just choose to use another way of showing what you want to show.

see UITabBarController's 'More' navigation controller disappears under UINavigationController

Title: Customizing "More" Tab Bar


问:
Test zoom levels of page on browsers in selenium webdriver
To zoom in webpage on browser I searched solution and used following ways but I am receiving either an error or no zoom effect. Can someone please help me to identify where is the mistake or what's wrong with the code. Browser I am using is Chrome.

First method:

```<code>element = driver.findElement(By.tagName("html"));
element.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
</code>```

Error received on this: Exception in thread "main"
  org.openqa.selenium.WebDriverException: unknown error: cannot focus
  element

To solve above error I tried:

```<code>element = driver.findElement(By.tagname("html"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys(Keys.CONTROL, Keys.ADD);
actions.build().perform();
</code>```

Error received: unknown error: Failed to execute 'getComputedStyle' on
  'Window': parameter 1 is not of type 'Element'.

Also I tried to replace element html with body but zoom not worked

Third way:

```<code>JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom='80%'");
</code>```

答:
I have tested third way in chrome and IE browser, it was working fine.

```<code>    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("document.body.style.zoom='200%'");
</code>```

zoom is not implemented in Firefox.

The "replacement" is transform from CSS3: https://developer.mozilla.org/En/transform

Below is the code for firefox browser:

```<code>    WebDriver driver;
    driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("document.body.style.MozTransform = 'scale(2)';");
</code>```

Reference: object.Style.Zoom property not working in Firefox

Let me know if you have any queries

Body:
To zoom in webpage on browser I searched solution and used following ways but I am receiving either an error or no zoom effect. Can someone please help me to identify where is the mistake or what's wrong with the code. Browser I am using is Chrome.

First method:

element = driver.findElement(By.tagName("html"));
element.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));

Error received on this: Exception in thread "main"
  org.openqa.selenium.WebDriverException: unknown error: cannot focus
  element

To solve above error I tried:

element = driver.findElement(By.tagname("html"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys(Keys.CONTROL, Keys.ADD);
actions.build().perform();

Error received: unknown error: Failed to execute 'getComputedStyle' on
  'Window': parameter 1 is not of type 'Element'.

Also I tried to replace element html with body but zoom not worked

Third way:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom='80%'");

Body:
I have tested third way in chrome and IE browser, it was working fine.

    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("document.body.style.zoom='200%'");

zoom is not implemented in Firefox.

The "replacement" is transform from CSS3: https://developer.mozilla.org/En/transform

Below is the code for firefox browser:

    WebDriver driver;
    driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("document.body.style.MozTransform = 'scale(2)';");

Reference: object.Style.Zoom property not working in Firefox

Let me know if you have any queries


答: Have you added a reference to the System.Management assembly?</p>

Title: ManagementObject Class not showing up in System.Management namespace


问:
SQL QUERY to count repeats with 2 conditions

To find repeated items only when when it satisfies two conditions. In this example count repeats of item type for each customer_id only when it has order size "Big" and its corresponding date is before other instances. This first condition and repeats can be achieved by using this code.

```<code>Select Customer_id, Item_Type, COUNT(*)
from table
group by Customer_id, Item_Type
having count(*) > 1 and sum(case when Order_Size = 'Big' then 1 else 0 end) > 0;
</code>```

how do I include date aspect as well to this?

答:
I believe you could use a window function in a subquery to decide which rows to count, then count them in your main query. Something like:

```<code>Select
    customer_id, item_type, sum(count_pass) as Count
FROM
    (
        Select Customer_id,
            Item_Type,
            CASE
                WHEN Order_Size = 'Big' THEN 0
                WHEN MIN(Order_Size) OVER (PARTITION BY Customer_ID, Item_Type ORDER BY DateField ASC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) = 'BIG' THEN 1
                ELSE 0
                END as count_pass
        FROM table
    ) subqry
GROUP BY 1,2
</code>```

That big case statement breaks down like:

If this record is 'Big' then ignore it

If you order all the records by date for each group of customer_id/item_type and look at all the records that precede this record, and the min(order_size) in that group of records (sorted lexicographically) is 'Big' then you have a preceding date with big and can count this record

Otherwise... you can't count it. Which would just be records with order_size='small' without a preceding 'big'.

Body:
To find repeated items only when when it satisfies two conditions. In this example count repeats of item type for each customer_id only when it has order size "Big" and its corresponding date is before other instances. This first condition and repeats can be achieved by using this code.

Select Customer_id, Item_Type, COUNT(*)
from table
group by Customer_id, Item_Type
having count(*) > 1 and sum(case when Order_Size = 'Big' then 1 else 0 end) > 0;

how do I include date aspect as well to this?

Body:
I believe you could use a window function in a subquery to decide which rows to count, then count them in your main query. Something like:

Select
    customer_id, item_type, sum(count_pass) as Count
FROM
    (
        Select Customer_id,
            Item_Type,
            CASE
                WHEN Order_Size = 'Big' THEN 0
                WHEN MIN(Order_Size) OVER (PARTITION BY Customer_ID, Item_Type ORDER BY DateField ASC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) = 'BIG' THEN 1
                ELSE 0
                END as count_pass
        FROM table
    ) subqry
GROUP BY 1,2

That big case statement breaks down like:

If this record is 'Big' then ignore it

If you order all the records by date for each group of customer_id/item_type and look at all the records that precede this record, and the min(order_size) in that group of records (sorted lexicographically) is 'Big' then you have a preceding date with big and can count this record

Otherwise... you can't count it. Which would just be records with order_size='small' without a preceding 'big'.


问:
Trying to get iframe to toggle via button
I have an image comparison slider which I am trying to toggle by user input.  To start I Just want to do it with a simple button, but it won't work, and I can't figure out why.

This is the code I am using:

```<code><iframe frameborder="0" class="iframe1" width="300" height="300" src="https://cdn.knightlab.com/libs/juxtapose/latest/embed/index.html?uid=019dc5e8-1631-11e7-9577-0edaf8f81e27"></iframe>
 <button class="button1">toggle slider</button>
</code>```

.

```<code>function hideToggle(button, elem) {

  $(button).toggle(
   function () {
      $(elem).hide();
   },
    function () {
      $(elem).show();
    }
  );
}

hideToggle(".button1", ".iframe1");
</code>```

Fiddle

答:
I've noticed your JSFiddle didn't have jQuery, try using the toggle function in your iframe element, maybe:

```<code>function hideToggle(button, elem) {
  $(button).click(function() {
    $(elem).toggle();
  });
}

hideToggle(".button1", ".iframe1");
</code>```

Here you can check if is what you're trying to do.

function hideToggle(button, elem) {
  $(button).click(function() { $(elem).toggle('show'); });
}
hideToggle(".button1", ".iframe1");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<iframe frameborder="0" class="iframe1" width="300" height="300" src="https://cdn.knightlab.com/libs/juxtapose/latest/embed/index.html?uid=019dc5e8-1631-11e7-9577-0edaf8f81e27"></iframe>
<button class="button1">toggle slider</button></code>```

Body:
I have an image comparison slider which I am trying to toggle by user input.  To start I Just want to do it with a simple button, but it won't work, and I can't figure out why.

This is the code I am using:

 <button class="button1">toggle slider</button>

.

function hideToggle(button, elem) {

  $(button).toggle(
   function () {
      $(elem).hide();
   },
    function () {
      $(elem).show();
    }
  );
}

hideToggle(".button1", ".iframe1");

Fiddle

Body:
I've noticed your JSFiddle didn't have jQuery, try using the toggle function in your iframe element, maybe:

function hideToggle(button, elem) {
  $(button).click(function() {
    $(elem).toggle();
  });
}

hideToggle(".button1", ".iframe1");

Here you can check if is what you're trying to do.

function hideToggle(button, elem) {
  $(button).click(function() { $(elem).toggle('show'); });
}
hideToggle(".button1", ".iframe1");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<iframe frameborder="0" class="iframe1" width="300" height="300" src="https://cdn.knightlab.com/libs/juxtapose/latest/embed/index.html?uid=019dc5e8-1631-11e7-9577-0edaf8f81e27"></iframe>
<button class="button1">toggle slider</button>


问:
Numpy and line intersections
How would I use numpy to calculate the intersection between two line segments?

In the code I have segment1 = ((x1,y1),(x2,y2)) and segment2 = ((x1,y1),(x2,y2)).  Note segment1 does not equal segment2.  So in my code I've also been calculating the slope and y-intercept, it would be nice if that could be avoided but I don't know of a way how.

I've been using Cramer's rule with a function I wrote up in Python but I'd like to find a faster way of doing this.

答:
Here's a (bit forced) one-liner:

```<code>import numpy as np
from scipy.interpolate import interp1d

x = np.array([0, 1])
segment1 = np.array([0, 1])
segment2 = np.array([-1, 2])

x_intersection = interp1d(segment1 - segment2, x)(0)
# if you need it:
y_intersection = interp1d(x, segment1)(x_intersection)
</code>```

Interpolate the difference (default is linear), and find a 0 of the inverse.

Cheers!

ContentLicense: CC BY-SA 4.0

Title: Numpy and line intersections

Body:
Here's a (bit forced) one-liner:

import numpy as np
from scipy.interpolate import interp1d

x = np.array([0, 1])
segment1 = np.array([0, 1])
segment2 = np.array([-1, 2])

x_intersection = interp1d(segment1 - segment2, x)(0)
# if you need it:
y_intersection = interp1d(x, segment1)(x_intersection)

Interpolate the difference (default is linear), and find a 0 of the inverse.

Cheers!


问:
Parallel.ForEach() not getting expected results
Inside my web api controller I'm looping over a list with Parallel.ForEach(). I have a counter that I increment in the Parallel.ForEach code. I'm noticing that counter is a variable number each time I run it and it's never as high as the list I'm looping over with Parallel.ForEach(). It seems like Parallel.ForEach() isn't waiting to come back before it's finished with looping over all elements.

```<code>// get all the new records from the csv
var newData = csv.GetRecords<MyEFTable>().ToArray();
int count = 0;
Parallel.ForEach(newData, (d) => {
  count++});
</code>```

newData has 6588 items and count generally is around 3400 or so items but again it's variable each time. This is very strange.

答:
You're getting into a race condition.  You need to use var newCount = Interlocked.Increment(ref count); to safely increment a variable in a multithreaded environment.  The newCount variable is the incremented counter.

The reason this happens is because count++ is not atomic.  It's actually three operations: getting the value, adding 1, then storing it back.  If you have those three things happening concurrently, stuff gets out of order and wonky.

When dealing with threads, its vital to ensure each thread isn't manipulating the same data, or they will squash each other.

Body:
Inside my web api controller I'm looping over a list with Parallel.ForEach(). I have a counter that I increment in the Parallel.ForEach code. I'm noticing that counter is a variable number each time I run it and it's never as high as the list I'm looping over with Parallel.ForEach(). It seems like Parallel.ForEach() isn't waiting to come back before it's finished with looping over all elements.

// get all the new records from the csv
var newData = csv.GetRecords<MyEFTable>().ToArray();
int count = 0;
Parallel.ForEach(newData, (d) => {
  count++});

newData has 6588 items and count generally is around 3400 or so items but again it's variable each time. This is very strange.


问:
Localization does not work for string array in android application
I have defined a string array in my values folder in this way for default English language

```<code><string-array name="movie">
        <item>11001#Action#1</item>
        <item>11002#Animation#1</item>
        <item>11003#Comedy#1</item>
        <item>11004#Documentary#1</item>
        <item>11005#Family#1</item>
        <item> 11006#Film-Noir#1</item>
        <item>11007#Horror#1</item>
        <item>11008#Musical#1</item>
        <item>11009#Romance#1</item>
    </string-array>
</code>```

My applicaiton is suported for many language like chainese simplified thats why i have defined another string-array in values-zh-rCN/string.xml for chainese simplified langue like this way

```<code><string-array name="movie">
        <item>11001#动作片#1</item>
        <item>11002#动画片#1</item>
        <item>11003#喜剧#1</item>
        <item>11004#记录片#1</item>
        <item>11005#家庭#1</item>
        <item> 11006#黑色电影#1</item>
        <item>11007#恐怖片#1</item>
        <item>11008#音乐剧#1</item>
        <item>11009#爱情片#1</item>
    </string-array>
</code>```

when my app is running and seleted Default english langue shown the array data but when i have seleted phone language in chainese simplified or other langue instead of english the array data does not shown. what are the possible solutionn for these problem ?

答:
```<code><string name="abcd">喜剧</string>
<string name="efgh">记录片</string>

<array name="array_abcd">
     <item>@string/abcd</item>
     <item>@string/efgh</item>
</array>
</code>```

Body:
I have defined a string array in my values folder in this way for default English language

<string-array name="movie">
        <item>11001#Action#1</item>
        <item>11002#Animation#1</item>
        <item>11003#Comedy#1</item>
        <item>11004#Documentary#1</item>
        <item>11005#Family#1</item>
        <item> 11006#Film-Noir#1</item>
        <item>11007#Horror#1</item>
        <item>11008#Musical#1</item>
        <item>11009#Romance#1</item>
    </string-array>

My applicaiton is suported for many language like chainese simplified thats why i have defined another string-array in values-zh-rCN/string.xml for chainese simplified langue like this way

<string-array name="movie">
        <item>11001#动作片#1</item>
        <item>11002#动画片#1</item>
        <item>11003#喜剧#1</item>
        <item>11004#记录片#1</item>
        <item>11005#家庭#1</item>
        <item> 11006#黑色电影#1</item>
        <item>11007#恐怖片#1</item>
        <item>11008#音乐剧#1</item>
        <item>11009#爱情片#1</item>
    </string-array>

when my app is running and seleted Default english langue shown the array data but when i have seleted phone language in chainese simplified or other langue instead of english the array data does not shown. what are the possible solutionn for these problem ?


问:
Change placeholder when browser is resized
Im looking to add a placeholder to a textbox when the browser has a smaller width than 800 and im not sure where im going wrong.

```<code><form class="info">
            <script>add();</script>
            <label>Name</label> <input type="text" class="box" name="name" placeholder="" size="40"><br><br>
</form>
</code>```

And the JS

```<code><script>
function add(){
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (w < 800) {
    document.getElementsByName('name')[0].placeholder='Name';
} else
{
}}
</script>
</code>```

答:
In case you hadn't considered it, you can use CSS media queries to simply hide the placeholder text on larger browsers, without doing anything with JavaScript:

HTML:

```<code><form class="info">
<label>Name</label>
<input type="text" class="box" name="name" placeholder="Name" size="40">
</form>
</code>```

CSS:

```<code>input::placeholder {color:transparent;}
@media (max-width:800px) {
    input::placeholder {color:gray;}
}
</code>```

note: the CSS should have the proper vendor-prefixes for placeholder, which I did not add in just for simplicity here.  please see https://css-tricks.com/almanac/selectors/p/placeholder/

Body:
Im looking to add a placeholder to a textbox when the browser has a smaller width than 800 and im not sure where im going wrong.

<form class="info">

            Name <input type="text" class="box" name="name" placeholder="" size="40">

</form>

And the JS

Body:
In case you hadn't considered it, you can use CSS media queries to simply hide the placeholder text on larger browsers, without doing anything with JavaScript:

HTML:

<form class="info">
<label>Name</label>
<input type="text" class="box" name="name" placeholder="Name" size="40">
</form>

CSS:

input::placeholder {color:transparent;}
@media (max-width:800px) {
    input::placeholder {color:gray;}
}

note: the CSS should have the proper vendor-prefixes for placeholder, which I did not add in just for simplicity here.  please see https://css-tricks.com/almanac/selectors/p/placeholder/


问:
numpy array of zeros or empty
I am writing code and efficiency is very important.
Actually I need 2d array, that I am filling with 0 and 1 in for loop. What is better and why?

Make empty array and fill it with "0" and "1". It's pseudocode, my array will be much bigger.

Make array filled by zeros and make if() and if not zero - put one.

So I need information what is more efficiency:
1. Put every element "0" and "1" to empty array
or
2. Make if() (efficiency of 'if') and then put only "1" element.

答:
```<code>Ae = np.empty(10000)
A0 = np.zeros((10000)
</code>```

differ slightly in how memory is initially allocated.  But any differences in time will be minor if you go on and do something like

```<code>for i in range(10000):
    Ae[i] = <some calc>
</code>```

or

```<code>for i in range(10000):
    val = <some calc>
    if val>0:
       A0[i] = val
</code>```

If I had to loop like this, I'd go ahead and use np.zeros, and also use the unconditional assignment.   It keeps the code simpler, and compared to everything else that is going on, the time differences will be minor.

Sample times:

```<code>In [33]: def foo0(N):
    ...:     A = np.empty(N,int)
    ...:     for i in range(N):
    ...:         A[i] = np.random.randint(0,2)
    ...:     return A
    ...:
In [34]: def foo1(N):
    ...:     A = np.zeros(N,int)
    ...:     for i in range(N):
    ...:         val = np.random.randint(0,2)
    ...:         if val:
    ...:             A[i] = val
    ...:     return A
    ...:
</code>```

3 ways of assigning 10 0/1 values

```<code>In [35]: foo0(10)
Out[35]: array([0, 0, 1, 0, 0, 1, 0, 1, 1, 0])
In [36]: foo1(10)
Out[36]: array([0, 1, 1, 1, 1, 1, 1, 1, 0, 0])
In [37]: np.random.randint(0,2,10)
Out[37]: array([0, 1, 1, 0, 1, 1, 1, 0, 0, 1])
</code>```

times:

```<code>In [38]: timeit foo0(1000)
100 loops, best of 3: 4.06 ms per loop
In [39]: timeit foo1(1000)
100 loops, best of 3: 3.95 ms per loop
In [40]: timeit np.random.randint(0,2,1000)
... cached.
100000 loops, best of 3: 13.6 µs per loop
</code>```

The 2 loop times are nearly the same.

Title: numpy array of zeros or empty

Body:
Ae = np.empty(10000)
A0 = np.zeros((10000)

differ slightly in how memory is initially allocated.  But any differences in time will be minor if you go on and do something like

for i in range(10000):
    Ae[i] = <some calc>

or

for i in range(10000):
    val = <some calc>
    if val>0:
       A0[i] = val

If I had to loop like this, I'd go ahead and use np.zeros, and also use the unconditional assignment.   It keeps the code simpler, and compared to everything else that is going on, the time differences will be minor.

Sample times:

In [33]: def foo0(N):
    ...:     A = np.empty(N,int)
    ...:     for i in range(N):
    ...:         A[i] = np.random.randint(0,2)
    ...:     return A
    ...:
In [34]: def foo1(N):
    ...:     A = np.zeros(N,int)
    ...:     for i in range(N):
    ...:         val = np.random.randint(0,2)
    ...:         if val:
    ...:             A[i] = val
    ...:     return A
    ...:

3 ways of assigning 10 0/1 values

In [35]: foo0(10)
Out[35]: array([0, 0, 1, 0, 0, 1, 0, 1, 1, 0])
In [36]: foo1(10)
Out[36]: array([0, 1, 1, 1, 1, 1, 1, 1, 0, 0])
In [37]: np.random.randint(0,2,10)
Out[37]: array([0, 1, 1, 0, 1, 1, 1, 0, 0, 1])

times:

In [38]: timeit foo0(1000)
100 loops, best of 3: 4.06 ms per loop
In [39]: timeit foo1(1000)
100 loops, best of 3: 3.95 ms per loop
In [40]: timeit np.random.randint(0,2,1000)
... cached.
100000 loops, best of 3: 13.6 µs per loop

The 2 loop times are nearly the same.


问:
get median on groups of pandas dataframe
I want to be able to calculate median on group of columns in a dataframe. I have the following example dataframe. For my actual dataframe, number of columns, names of columns and groups are dynamic as it depends on the user input.

```<code>raw_data= {'a':['g1','g2','g3','g4','g5'],'b':[10,11,12,13,14],'c':[5,6,7,8,9],'d':[112,1,0,9,8],'e':[6,7,8,0,9],'f':[0,1,6,7,8],'g':[9,8,6,5,4]}
mydf= pd.DataFrame(raw_data)
newdf= mydf.set_index('a')
</code>```

I have another dictionary where I store group information for my columns

```<code>gp_dict= {'gp1':['b','c','d'],'gp2':['e','f','g']}
</code>```

Current dataframe:

```<code>     b  c    d  e  f  g
a
g1  10  5  112  6  0  9
g2  11  6    1  7  1  8
g3  12  7    0  8  6  6
g4  13  8    9  0  7  5
g5  14  9    8  9  8  4
</code>```

My code should get median for each group and keep rows if Median greater than 8 for any of the groups.

Desired output:

```<code>     b  c    d  e  f  g
g1  10  5  112  6  0  9
g4  13  8    9  0  7  5
g5  14  9    8  9  8  4
</code>```

Obviously, intermediate step should be to calcuate median on both groups:

```<code>     b  c    d  e  f  g Median_gp1 Median_gp2
g1  10  5  112  6  0  9    10         6
g2  11  6    1  7  1  8    6          7
g3  12  7    0  8  6  6    7          6
g4  13  8    9  0  7  5    9          5
g5  14  9    8  9  8  4    9          8
</code>```

答:
You can use groupby by swapped dict by columns, aggregate median and compare with any for at least one True per row. Last filter by boolean indexing:

```<code>#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d = {k: oldk for oldk, oldv in gp_dict.items() for k in oldv}
mask = newdf.groupby(d, axis=1).median().gt(8).any(1)
#same as
#mask = (newdf.groupby(d, axis=1).median() > 8).any(1)
print (newdf[mask])
     b  c    d  e  f  g
a
g1  10  5  112  6  0  9
g4  13  8    9  0  7  5
g5  14  9    8  9  8  4
</code>```

Body:
I want to be able to calculate median on group of columns in a dataframe. I have the following example dataframe. For my actual dataframe, number of columns, names of columns and groups are dynamic as it depends on the user input.

raw_data= {'a':['g1','g2','g3','g4','g5'],'b':[10,11,12,13,14],'c':[5,6,7,8,9],'d':[112,1,0,9,8],'e':[6,7,8,0,9],'f':[0,1,6,7,8],'g':[9,8,6,5,4]}
mydf= pd.DataFrame(raw_data)
newdf= mydf.set_index('a')

I have another dictionary where I store group information for my columns

gp_dict= {'gp1':['b','c','d'],'gp2':['e','f','g']}

Current dataframe:

     b  c    d  e  f  g
a
g1  10  5  112  6  0  9
g2  11  6    1  7  1  8
g3  12  7    0  8  6  6
g4  13  8    9  0  7  5
g5  14  9    8  9  8  4

My code should get median for each group and keep rows if Median greater than 8 for any of the groups.

Desired output:

     b  c    d  e  f  g
g1  10  5  112  6  0  9
g4  13  8    9  0  7  5
g5  14  9    8  9  8  4

Obviously, intermediate step should be to calcuate median on both groups:

     b  c    d  e  f  g Median_gp1 Median_gp2
g1  10  5  112  6  0  9    10         6
g2  11  6    1  7  1  8    6          7
g3  12  7    0  8  6  6    7          6
g4  13  8    9  0  7  5    9          5
g5  14  9    8  9  8  4    9          8

Body:
You can use groupby by swapped dict by columns, aggregate median and compare with any for at least one True per row. Last filter by boolean indexing:

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d = {k: oldk for oldk, oldv in gp_dict.items() for k in oldv}
mask = newdf.groupby(d, axis=1).median().gt(8).any(1)
#same as
#mask = (newdf.groupby(d, axis=1).median() > 8).any(1)
print (newdf[mask])
     b  c    d  e  f  g
a
g1  10  5  112  6  0  9
g4  13  8    9  0  7  5
g5  14  9    8  9  8  4


问:
Align button to the right
I know this must be really simple but I'm trying to set a button to the right of the window using only bootstrap 4 classes. It must be in the same row as the text.

```<code><html>
<head>
</head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <body>
        <div class="row">
            <h3 class="one">Text</h3>
            <button class="btn btn-secondary pull-right">Button</button>
        </div>
    </body>
</html>
</code>```

The code is in here

答:
```<code><div class="container-fluid">
  <div class="row">
    <h3 class="one">Text</h3>
    <button class="btn btn-secondary ml-auto">Button</button>
  </div>
</div>
</code>```

.ml-auto is Bootstraph 4's non-flexbox way of aligning things.

Title: Align button to the right

Body:
I know this must be really simple but I'm trying to set a button to the right of the window using only bootstrap 4 classes. It must be in the same row as the text.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Text

            <button class="btn btn-secondary pull-right">Button</button>

The code is in here

Body:
<div class="container-fluid">
  <div class="row">
    <h3 class="one">Text</h3>
    <button class="btn btn-secondary ml-auto">Button</button>
  </div>
</div>

.ml-auto is Bootstraph 4's non-flexbox way of aligning things.


答:
Taking a swing without testing, as I think the desired result is still unclear.

First, find the "first messages" of a conversation:

```<code>select m1.id
      ,m.sender_id
      ,m.recipient_id
      ,m.Created_at
from messages m1
inner join (
    select m.sender_id
          ,m.recipient_id
          ,Min(m.Created_at) as first_message
    from messages m
    group by m.sender_id
            ,m.recipient_id
    ) m2
   on m1.sender_id = m2.sender_id
   and m1.m.recipient_id = m2m.recipient_id
   and m1.Created_at = m2.first_message
</code>```

If these are properly "first messages", then find any replies in 24 hours

```<code>select distinct m3.sender_id
from messages m3
inner join (
     <the above first message select statement>
     ) fm
   on m3.sender_id = fm.recipient_id
   and m3.recipient_id = fm.sender_id
   and m3.Created_at < DATEADD (HH , 24 , fm.Created_at)
where m3.Created_at > fm.Created_at
</code>```

Title: Get users who replied the first message of the conversation within 24hours

Body:
I need to find the users who replied the first message of the conversation (one to one conversation) within 24hours. I have a messages table where all data are stored.

Table: messages

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01
5  | 1002      | 500          | Hi there     | 2017-03-22 10:10:10
6  | 1002      | 500          | Can you meet?| 2017-03-22 10:15:32
7  | 500       | 1002         | Yes          | 2017-03-22 10:20:30
8  | 1003      | 600          | Hello world  | 2017-03-23 01:00:00
9  | 1004      | 700          | Hi           | 2017-03-23 08:10:10
10 | 700       | 1004         | hello        | 2017-03-26 22:00:00

Expected result:

users
256
500

Example: Conversation between user 1001 and 256.

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01

Here 2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10 is the first replied message of the conversation and its replied within 24 hours.

Body:
Taking a swing without testing, as I think the desired result is still unclear.

First, find the "first messages" of a conversation:

select m1.id
      ,m.sender_id
      ,m.recipient_id
      ,m.Created_at
from messages m1
inner join (
    select m.sender_id
          ,m.recipient_id
          ,Min(m.Created_at) as first_message
    from messages m
    group by m.sender_id
            ,m.recipient_id
    ) m2
   on m1.sender_id = m2.sender_id
   and m1.m.recipient_id = m2m.recipient_id
   and m1.Created_at = m2.first_message

If these are properly "first messages", then find any replies in 24 hours

select distinct m3.sender_id
from messages m3
inner join (
     <the above first message select statement>
     ) fm
   on m3.sender_id = fm.recipient_id
   and m3.recipient_id = fm.sender_id
   and m3.Created_at < DATEADD (HH , 24 , fm.Created_at)
where m3.Created_at > fm.Created_at


问:
My Portal's MSSQL and vBulletin's MySQL
I have developed a Portal using Microsoft ASP.NET and MSSQL. Now, I want to include vBulletin to my site for that purpose I need to have PHP and MySQL(or MSSQL will do?). With single login feature for both the Portal and Forum.

I have hosted my site on Dedicated IIS webserver hosted on MS Server 2008.
I can install PHP on it. (and MySQL too if required)

The problem here is how can I integrate the user's of my portal with vBulletin forum??

Is there any way to Install vBulletin using IIS+PHP+MSSQL?
or
I have to use IIS+PHP+MysQL and integrate users of users of both the databases? (HOW?)

答:
At the moment vBulletin only supports MySQL.  There is talk of adding support for other databases however right now with all versions of VB MySQL is your only option.  So without heavily modifying VB this cannot use MSSQL (in fact I would strongly recommend that you don't even try embarking on that)

The other complication is that you are using two different code frameworks, PHP for vBulletin and ASP.NET (C#?) for your portal.  All these frameworks can sit together on the same dedicate box but you need them to communicate with each other.

With all this in mind the easiest way of having SSO across the two platforms (portal & vbulletin) would be to use the vBulletin user table in MySQL for your portal authentication.  There is a .NET MySQL driver that you can use for this purpose and running the necessary queries via that, from ASP.NET, should be fairly simple.

The only other thing that you will have to consider is a user logging in on your portal page not having to relog when they go to the forums.  This can be done by setting cookies etc so you will have to look at vBulletins login.php script to work out how these are handled.

There is also another option, that you may or may not want to consider (depending on how much work you have put into your portal ;)).  There is already a free portal product for vBulletin called vbAdvanced:

http://www.vbadvanced.com/

This may already meet your portal requirements and is developed specifically for vBulletin.

Title: My Portal's MSSQL and vBulletin's MySQL


问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答: I too had the same issue. Removed the watch app and did the upload. It has been accepted for review. So looks like the issue is with the validation of the watchkit extension. Will submit the app again with the watch app once this issue has been taken care of by Apple.</p>


问:
In R How to bin tibble data?
I have a tibble like this.

```<code># A tibble: 200,000 × 3
   Steps Distance   run
   <int>    <dbl> <chr>
1   1000 33.32683     0
2   2000 35.02510     0
3   3000 36.19157     0
4   4000 37.82663     0
5   5000 36.30477     0
6   6000 37.78146     0
7   7000 38.62345     0
8   8000 34.84085     0
9   9000 37.05461     0
10 10000 43.02439     0
11 10000 44.12345     1
</code>```

I want to use a group_by of "run".
Then bin the value in to a specific number of bins.
To make something like this.

```<code>run Interval Count
0   0-10     xx
0   10-100   xx
1   0-10     xx
</code>```

I found out a similar function like "bin_data", but it's not compatible with group_by.

Thank you.

答:
You can bin the data first, then use summarize and n to count the number of observations in each group.</p>

```<code>data_frame(Group = sample(letters[1:2],20,replace = T),Value=runif(20,0,5)) %>%
  mutate(Bin = cut(Value,breaks = 0:5)) %>%
  group_by(Group,Bin) %>%
  summarise(Count = n())

Source: local data frame [8 x 3]
Groups: Group [?]

  Group    Bin Count
  <chr> <fctr> <int>
1     a  (0,1]     1
2     a  (1,2]     6
3     a  (2,3]     2
4     a  (4,5]     4
5     b  (0,1]     1
6     b  (1,2]     2
7     b  (3,4]     2
8     b  (4,5]     2
</code>```

Title: In R How to bin tibble data?

Body:
I have a tibble like this.

# A tibble: 200,000 × 3
   Steps Distance   run
   <int>    <dbl> <chr>
1   1000 33.32683     0
2   2000 35.02510     0
3   3000 36.19157     0
4   4000 37.82663     0
5   5000 36.30477     0
6   6000 37.78146     0
7   7000 38.62345     0
8   8000 34.84085     0
9   9000 37.05461     0
10 10000 43.02439     0
11 10000 44.12345     1

I want to use a group_by of "run".
Then bin the value in to a specific number of bins.
To make something like this.

run Interval Count
0   0-10     xx
0   10-100   xx
1   0-10     xx

I found out a similar function like "bin_data", but it's not compatible with group_by.

Thank you.

Body:
You can bin the data first, then use summarize and n to count the number of observations in each group.

data_frame(Group = sample(letters[1:2],20,replace = T),Value=runif(20,0,5)) %>%
  mutate(Bin = cut(Value,breaks = 0:5)) %>%
  group_by(Group,Bin) %>%
  summarise(Count = n())

Source: local data frame [8 x 3]
Groups: Group [?]

  Group    Bin Count
  <chr> <fctr> <int>
1     a  (0,1]     1
2     a  (1,2]     6
3     a  (2,3]     2
4     a  (4,5]     4
5     b  (0,1]     1
6     b  (1,2]     2
7     b  (3,4]     2
8     b  (4,5]     2