问:
CAAnimation on multiple SceneKit nodes simultaneously
I am creating an application wherein I am using SceneKit contents in AR app. I have multiple nodes which are being placed at different places in my scene. They may or may not be necessarily be inside one parent node. The user has to choose a correct node, as per challenge set by the application. If the user chooses correct node, the correct node goes through one kind of animation and incorrect ones (may be several) undergo another set of animation. I am accomplishing animations using CAAnimation directly, which is all good. Basically to accomplish this, I am creating an array of all nodes and using them for animation.

```<code>DispatchQueue.global(qos: .userInteractive).async { [weak self] in
    for node in (self?.nodesAddedInScene.keys)! {
        for index in 1...node.childNodes.count - 1 {
            if node.childNodes[index].childNodes.first?.name == "target" {
                self?.riseUpSpinAndFadeAnimation(on: node.childNodes[index])
            } else {
                self?.fadeAnimation(on: node.childNodes[index])
            }
        }
    }
}
</code>```

When user chooses "target" node, that node goes through one set of animation and others go through another set of animations.

RiseUpSpinAndFadeAnimation:

```<code>    private func riseUpSpinAndFadeAnimation(on shape: SCNNode) {
        let riseUpAnimation = CABasicAnimation(keyPath: "position")
        riseUpAnimation.fromValue = SCNVector3(shape.position.x, shape.position.y, shape.position.z)
        riseUpAnimation.toValue = SCNVector3(shape.position.x, shape.position.y + 0.5, shape.position.z)

        let spinAnimation = CABasicAnimation(keyPath: "eulerAngles.y")
        spinAnimation.toValue = shape.eulerAngles.y + 180.0
        spinAnimation.autoreverses = true

        let fadeAnimation = CABasicAnimation(keyPath: "opacity")
        fadeAnimation.toValue = 0.0

        let riseUpSpinAndFadeAnimation = CAAnimationGroup()
        riseUpSpinAndFadeAnimation.animations = [riseUpAnimation, fadeAnimation, spinAnimation]
        riseUpSpinAndFadeAnimation.duration = 1.0
        riseUpSpinAndFadeAnimation.fillMode = kCAFillModeForwards
        riseUpSpinAndFadeAnimation.isRemovedOnCompletion = false

        shape.addAnimation(riseUpSpinAndFadeAnimation, forKey: "riseUpSpinAndFade")
    }
</code>```

FadeAnimation:

```<code>private func fadeAnimation(on shape: SCNNode) {
    let fadeAnimation = CABasicAnimation(keyPath: "opacity")
    fadeAnimation.toValue = 0.0
    fadeAnimation.duration = 0.5
    fadeAnimation.fillMode = kCAFillModeForwards
    fadeAnimation.isRemovedOnCompletion = false
    shape.addAnimation(fadeAnimation, forKey: "fade")
}
</code>```

I expect animations to work out, which they are actually. However, the issue is since the nodes are in an array animation is not being done at the same time for all nodes. There are minute differences in start of animation which actually is leading to not so good UI.

What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node. Arrays don't seem to be a wise choice to me. However, I am afraid if I make all of these nodes child nodes of an empty node and the run animation on that empty node, possibly it would be difficult to manage placement of these child nodes in the first place since they supposed to be kept at random distances and not necessarily close together. Given that this ultimately drives AR experience, it more so becomes a bummer.

Requesting some inputs whether there are methods to attach animation to multiple (selected out of those) object (even if sequentially) but RUN them together. I used shape.addAnimation(fadeAnimation, forKey: "fade") "forKey", can that be made of use in such use case? Any pointers appreciated.

答:
I've had up to fifty SCNNodes animating in perfect harmony by using CAKeyframe animations that are paused (.speed = 0) and setting the animation's time offset (.timeOffset) inside a SCNSceneRendererDelegate "renderer(updateAtTime:)" function.

It's pretty amazing how you can add a paused animation with an time offset every 1/60th of a second for a large number of nodes. Hats off to the SceneKit developers for having so little overhead on adding and removing CAAnimations.

I tried many different CAAnimation/SCNAction techniques before settling on this. In other methods the animations would drift out of sync over time.

Body:
I am creating an application wherein I am using SceneKit contents in AR app. I have multiple nodes which are being placed at different places in my scene. They may or may not be necessarily be inside one parent node. The user has to choose a correct node, as per challenge set by the application. If the user chooses correct node, the correct node goes through one kind of animation and incorrect ones (may be several) undergo another set of animation. I am accomplishing animations using CAAnimation directly, which is all good. Basically to accomplish this, I am creating an array of all nodes and using them for animation.

DispatchQueue.global(qos: .userInteractive).async { [weak self] in
    for node in (self?.nodesAddedInScene.keys)! {
        for index in 1...node.childNodes.count - 1 {
            if node.childNodes[index].childNodes.first?.name == "target" {
                self?.riseUpSpinAndFadeAnimation(on: node.childNodes[index])
            } else {
                self?.fadeAnimation(on: node.childNodes[index])
            }
        }
    }
}

When user chooses "target" node, that node goes through one set of animation and others go through another set of animations.

RiseUpSpinAndFadeAnimation:

    private func riseUpSpinAndFadeAnimation(on shape: SCNNode) {
        let riseUpAnimation = CABasicAnimation(keyPath: "position")
        riseUpAnimation.fromValue = SCNVector3(shape.position.x, shape.position.y, shape.position.z)
        riseUpAnimation.toValue = SCNVector3(shape.position.x, shape.position.y + 0.5, shape.position.z)

        let spinAnimation = CABasicAnimation(keyPath: "eulerAngles.y")
        spinAnimation.toValue = shape.eulerAngles.y + 180.0
        spinAnimation.autoreverses = true

        let fadeAnimation = CABasicAnimation(keyPath: "opacity")
        fadeAnimation.toValue = 0.0

        let riseUpSpinAndFadeAnimation = CAAnimationGroup()
        riseUpSpinAndFadeAnimation.animations = [riseUpAnimation, fadeAnimation, spinAnimation]
        riseUpSpinAndFadeAnimation.duration = 1.0
        riseUpSpinAndFadeAnimation.fillMode = kCAFillModeForwards
        riseUpSpinAndFadeAnimation.isRemovedOnCompletion = false

        shape.addAnimation(riseUpSpinAndFadeAnimation, forKey: "riseUpSpinAndFade")
    }

FadeAnimation:

private func fadeAnimation(on shape: SCNNode) {
    let fadeAnimation = CABasicAnimation(keyPath: "opacity")
    fadeAnimation.toValue = 0.0
    fadeAnimation.duration = 0.5
    fadeAnimation.fillMode = kCAFillModeForwards
    fadeAnimation.isRemovedOnCompletion = false
    shape.addAnimation(fadeAnimation, forKey: "fade")
}

I expect animations to work out, which they are actually. However, the issue is since the nodes are in an array animation is not being done at the same time for all nodes. There are minute differences in start of animation which actually is leading to not so good UI.

What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node. Arrays don't seem to be a wise choice to me. However, I am afraid if I make all of these nodes child nodes of an empty node and the run animation on that empty node, possibly it would be difficult to manage placement of these child nodes in the first place since they supposed to be kept at random distances and not necessarily close together. Given that this ultimately drives AR experience, it more so becomes a bummer.

Requesting some inputs whether there are methods to attach animation to multiple (selected out of those) object (even if sequentially) but RUN them together. I used shape.addAnimation(fadeAnimation, forKey: "fade") "forKey", can that be made of use in such use case? Any pointers appreciated.


来源: stackexchange

问:
Send parameters to webhook on dialogflow sdk v2
I'm trying to send some parameters to dialogflow (api.ai) such as username, email, etc but I couldn't figure it out. The problem is I cannot get/set any specific data (such as username, email, etc.) with Dialogflow v2 Nodejs SDK. I tried to use queryParams.payload (v1: originalRequest) but It didn't work somehow. Also, I tried to trigger custom event with data but I couldn't get any event data on the response. Does someone know how to send some specific data for session talk on dialogFlow?

EXAMPLE OF PAYLOAD

```<code>  const projectId = 'test-bot-test-1111';
  const sessionId = user.uuid;
  const languageCode = 'en-GB';

  const sessionClient = new dialogFlow.SessionsClient();
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode
      }
    },
    queryParams: {
      payload: {
        data: {
           username: 'bob',
           email: 'bob@test.com'
        }
      }
    }
  };

  let resultReq;

  console.log('request :: ', request, '\n\n');

  try {
    resultReq = await sessionClient.detectIntent(request);
  } catch (err) {
    // eslint-disable-next-line no-console
    return console.error('ERROR:', err);
  }
</code>```

EXAMPLE OF EVENT

```<code>  const projectId = 'test-bot-test-1111';
  const sessionId = user.uuid;
  const languageCode = 'en-GB';

  const sessionClient = new dialogFlow.SessionsClient();
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

const request = {
    session: sessionPath,
    queryInput: {
      event: {
        name: 'custom_event',
        languageCode,
        parameters: {
          name: 'sam',
          user_name: 'sam',
          a: 'saaaa'
        }
      }
    },
    queryParams: {
      payload: {
        data: user
      }
    }
  };

  let resultReq;

  console.log('request :: ', request, '\n\n');

  try {
    resultReq = await sessionClient.detectIntent(request);
  } catch (err) {
    // eslint-disable-next-line no-console
    return console.error('ERROR:', err);
  }
</code>```

答:
Dialogflow's v2 API uses gRPC and has a few quirks, one of which you've run into.  If you look at the samples for the Node.js library you can see how to workaround this.  You'll need to impliment a jsonToStructProto method to convert your JavaScript object to a proto struct or just copy the structjson.js file <s>in the sample</s> in this gist.  Below is a fully working example using the structjson.js file:

```<code>// Imports the Dialogflow library
const dialogflow = require('dialogflow');

// Import the JSON to gRPC struct converter
const structjson = require('./structjson.js');

// Instantiates a sessison client
const sessionClient = new dialogflow.SessionsClient();

// The path to identify the agent that owns the created intent.
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

// The text query request.
const request = {
  session: sessionPath,
  queryInput: {
    event: {
      name: eventName,
      parameters: structjson.jsonToStructProto({foo: 'bar'}),
      languageCode: languageCode,
    },
  },
};

sessionClient
  .detectIntent(request)
  .then(responses => {
    console.log('Detected intent');
    logQueryResult(sessionClient, responses[0].queryResult);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send some parameters to dialogflow (api.ai) such as username, email, etc but I couldn't figure it out. The problem is I cannot get/set any specific data (such as username, email, etc.) with Dialogflow v2 Nodejs SDK. I tried to use queryParams.payload (v1: originalRequest) but It didn't work somehow. Also, I tried to trigger custom event with data but I couldn't get any event data on the response. Does someone know how to send some specific data for session talk on dialogFlow?

EXAMPLE OF PAYLOAD

  const projectId = 'test-bot-test-1111';
  const sessionId = user.uuid;
  const languageCode = 'en-GB';

  const sessionClient = new dialogFlow.SessionsClient();
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode
      }
    },
    queryParams: {
      payload: {
        data: {
           username: 'bob',
           email: 'bob@test.com'
        }
      }
    }
  };

  let resultReq;

  console.log('request :: ', request, '\n\n');

  try {
    resultReq = await sessionClient.detectIntent(request);
  } catch (err) {
    // eslint-disable-next-line no-console
    return console.error('ERROR:', err);
  }

EXAMPLE OF EVENT

  const projectId = 'test-bot-test-1111';
  const sessionId = user.uuid;
  const languageCode = 'en-GB';

  const sessionClient = new dialogFlow.SessionsClient();
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

const request = {
    session: sessionPath,
    queryInput: {
      event: {
        name: 'custom_event',
        languageCode,
        parameters: {
          name: 'sam',
          user_name: 'sam',
          a: 'saaaa'
        }
      }
    },
    queryParams: {
      payload: {
        data: user
      }
    }
  };

  let resultReq;

  console.log('request :: ', request, '\n\n');

  try {
    resultReq = await sessionClient.detectIntent(request);
  } catch (err) {
    // eslint-disable-next-line no-console
    return console.error('ERROR:', err);
  }

Body:
Dialogflow's v2 API uses gRPC and has a few quirks, one of which you've run into.  If you look at the samples for the Node.js library you can see how to workaround this.  You'll need to impliment a jsonToStructProto method to convert your JavaScript object to a proto struct or just copy the structjson.js file <s>in the sample</s> in this gist.  Below is a fully working example using the structjson.js file:

// Imports the Dialogflow library
const dialogflow = require('dialogflow');

// Import the JSON to gRPC struct converter
const structjson = require('./structjson.js');

// Instantiates a sessison client
const sessionClient = new dialogflow.SessionsClient();

// The path to identify the agent that owns the created intent.
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

// The text query request.
const request = {
  session: sessionPath,
  queryInput: {
    event: {
      name: eventName,
      parameters: structjson.jsonToStructProto({foo: 'bar'}),
      languageCode: languageCode,
    },
  },
};

sessionClient
  .detectIntent(request)
  .then(responses => {
    console.log('Detected intent');
    logQueryResult(sessionClient, responses[0].queryResult);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

ContentLicense: CC BY-SA 4.0


问:
Finding minimum value more efficiently in racket

Hello,

I am working on some Racket practice. I am aware that Racket has a built in min function, but I am trying to write one from scratch. I have done some work and found some ideas online, but the code is not very efficient. I am thinking I will need to use a helper method. I am a bit lost on how to further modify this code to make it efficient. I ran this code on the test case shown and it took way too long. On smaller test cases the code does return the correct results. Any suggestions would be great.

```<code>(define (minim lst)
    (cond
      ((null? (cdr lst)) (car lst))
      ((< (car lst) (minim (cdr lst))) (car lst))
      (else
        (minim (cdr lst)))) )
</code>```

(minim '(3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4))

Would return 1.

Body:
Hello,

I am working on some Racket practice. I am aware that Racket has a built in min function, but I am trying to write one from scratch. I have done some work and found some ideas online, but the code is not very efficient. I am thinking I will need to use a helper method. I am a bit lost on how to further modify this code to make it efficient. I ran this code on the test case shown and it took way too long. On smaller test cases the code does return the correct results. Any suggestions would be great.

(define (minim lst)
    (cond
      ((null? (cdr lst)) (car lst))
      ((< (car lst) (minim (cdr lst))) (car lst))
      (else
        (minim (cdr lst)))) )

(minim '(3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4))

Would return 1.

Body:
Assuming an unsorted list, the most natural way to find the minimum would be to go through the entire list, comparing each element against some initial min value, and whenever an element is smaller than that min, the element gets saved as the new min. At the end, min gets returned when list becomes empty (base case).

For example, consider the following:

(define (minimum lst acc)
  (cond
    ((null? lst) acc)
    ((< (car lst) acc)
     (minimum (cdr lst) (car lst)))
    (else
     (minimum (cdr lst) acc))))

(define (mymin lst)
  (if (null? lst)
      #f
      (minimum (cdr lst) (car lst))))

mymin takes O(n) time to find min value in a list, using n-1 comparisons, where n is the number of elements in list.

You can test this with longer and shorter lists locally:

(mymin   '(3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4
           3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4 -1))
=> -1


问:
Can't convert Fixnum into String - Devise/sessions Controller issue
So this is the error I see:

```<code>TypeError in Devise/sessionsController#create

can't convert Fixnum into String

Application Trace | Framework Trace | Full Trace
app/controllers/application_controller.rb:21:in `set_current_user'
</code>```

This is how application_controller.rb looks:

```<code>    class ApplicationController < ActionController::Base
  helper :all
   helper_method :current_user, :logged_in?

  protect_from_forgery
  before_filter :set_current_user

  def set_xhr_flash
    flash.discard if request.xhr?
  end

  def correct_safari_and_ie_accept_headers
    ajax_request_types = ['text/javascript', 'application/json', 'text/xml']
    request.accepts.sort! { |x, y| ajax_request_types.include?(y.to_s) ? 1 : -1 } if request.xhr?
  end

  protected

  def set_current_user
    Authorization.current_user = current_user
  end

end
</code>```

Help!

Edit1: Per the request, here is the output of the log file.

```<code>    User Load (0.3ms)  SELECT "users".* FROM "users" WHERE ("users"."username" = 'test') LIMIT 1
Completed   in 289ms

TypeError (can't convert Fixnum into String):
  app/controllers/application_controller.rb:21:in `set_current_user'

Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (340.7ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (350.6ms)

Started GET "/users/login" for 127.0.0.1 at 2011-01-19 17:16:18 -0500
  Processing by Devise::SessionsController#new as HTML
nil
Rendered devise/sessions/new.html.erb within layouts/application (5.9ms)
Completed 200 OK in 65ms (Views: 15.6ms | ActiveRecord: 0.0ms)

Started POST "/users/login" for 127.0.0.1 at 2011-01-19 17:16:31 -0500
  Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+SYzwvqO1Kp8GhYwSA9u3plM5A/RNNRFT3wzJICXP6s=", "user"=>{"f_name"=>"First Name", "l_name"=>"Last Name", "username"=>"test", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"Email Address"}, "commit"=>"Submit"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE ("users"."username" = 'test') LIMIT 1
Completed   in 199ms

TypeError (can't convert Fixnum into String):
  app/controllers/application_controller.rb:21:in `set_current_user'

Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (348.3ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (355.7ms)
</code>```

Anyone come up with any solutions for this?

答:
Ok so I finally found the answer. The db got corrupt. Once I dumped the entire db, deleted the db file and re-created everything - I was good to go.

sigh

I just hope I can figure out a way to prevent that from happening in production.

ContentLicense: CC BY-SA 2.5

Body:
So this is the error I see:

TypeError in Devise/sessionsController#create

can't convert Fixnum into String

Application Trace | Framework Trace | Full Trace
app/controllers/application_controller.rb:21:in `set_current_user'

This is how application_controller.rb looks:

    class ApplicationController < ActionController::Base
  helper :all
   helper_method :current_user, :logged_in?

  protect_from_forgery
  before_filter :set_current_user

  def set_xhr_flash
    flash.discard if request.xhr?
  end

  def correct_safari_and_ie_accept_headers
    ajax_request_types = ['text/javascript', 'application/json', 'text/xml']
    request.accepts.sort! { |x, y| ajax_request_types.include?(y.to_s) ? 1 : -1 } if request.xhr?
  end

  protected

  def set_current_user
    Authorization.current_user = current_user
  end

end

Help!

Edit1: Per the request, here is the output of the log file.

    User Load (0.3ms)  SELECT "users".* FROM "users" WHERE ("users"."username" = 'test') LIMIT 1
Completed   in 289ms

TypeError (can't convert Fixnum into String):
  app/controllers/application_controller.rb:21:in `set_current_user'

Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (340.7ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (350.6ms)

Started GET "/users/login" for 127.0.0.1 at 2011-01-19 17:16:18 -0500
  Processing by Devise::SessionsController#new as HTML
nil
Rendered devise/sessions/new.html.erb within layouts/application (5.9ms)
Completed 200 OK in 65ms (Views: 15.6ms | ActiveRecord: 0.0ms)

Started POST "/users/login" for 127.0.0.1 at 2011-01-19 17:16:31 -0500
  Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+SYzwvqO1Kp8GhYwSA9u3plM5A/RNNRFT3wzJICXP6s=", "user"=>{"f_name"=>"First Name", "l_name"=>"Last Name", "username"=>"test", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"Email Address"}, "commit"=>"Submit"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE ("users"."username" = 'test') LIMIT 1
Completed   in 199ms

TypeError (can't convert Fixnum into String):
  app/controllers/application_controller.rb:21:in `set_current_user'

Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (348.3ms)
Rendered /Users/marcamillion/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (355.7ms)

Anyone come up with any solutions for this?


问:
Document / Folder (Parent Child) Display - only show folders with contents
I am building my own simple document display model with the concept of Directories (Folders) with containing Documents.  I have built the database and can successfully get a list of all the documents that are in each folder.  My security model has only security on a document level and NOT on a folder level so when i render out the display of folders (and documents) alot of the time many users are seeing empty folders which are not relevant.  What is an efficient way of filtering out the folders that don't contain direct children of documents (except those that have nested folders who DO contain documents)

Below is my recursive function that generates my JSON

```<code>        public List<DirectoryViewModel> FlatToHierarchy(List<Data.Directory> list, List<MyDocumentsViewModel> documents, Guid? parentId = null)
    {
        return (from i in list
                where i.ParentId == parentId
                select new DirectoryViewModel
                {
                    Id = i.Id,
                    Description = i.Description,
                    ParentId = i.ParentId,
                    Name = i.Name,

                    Documents = documents.Where(x => x.DirectoryId == i.Id).ToList(),
                    Directories = FlatToHierarchy(list, documents, i.Id)
                }).ToList();
    }
</code>```

and below is an example of the output generated

{
   "Directories":[
      {
         "Id":"8072d20b-c424-465e-87be-7b09ad64a6cc",
         "Name":"Front of House",
         "Description":"Checklists \u0026 Evaluations",
         "ParentId":null,
         "Documents":[
            {
               "LatestVersion":false,
               "Id":"7a580b85-edff-4c18-9ba4-ea893a5b1c11",
               "Name":"Welcome Pack",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603479817)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"263.822 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603479817)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":false,
               "Id":"b288a86d-370e-43b2-a938-f817468ccc44",
               "Name":"scenarios",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603539867)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"816.909 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603539867)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":false,
               "Id":"67ac3117-309b-40d5-82ca-424de9723d20",
               "Name":"Tour",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603617990)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"262.362 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603617990)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":false,
               "Id":"734bf12e-a219-4190-b390-0369901174bb",
               "Name":"Evaluation Sheet",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603797893)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"670.168 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603797893)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"64907293-4fde-4f5c-a6f3-640e002c8122",
               "Name":"Walk-through",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603503013)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"500.525 KB",
               "Url":"https://xxxxx5VtqKA",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603503013)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"bcdb12a6-de80-45c3-ac97-0cab879a4b34",
               "Name":"staff",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603575103)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"279.536 KB",
               "Url":"https://xxxxxaVnDfQ",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603575103)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"b1d02b16-a0ba-4100-ada0-ce36ec647f36",
               "Name":"Checklist",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603522967)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"244.976 KB",
               "Url":"https://xxxxxdSngtA",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603522967)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"226ceb41-ff93-4a4a-963b-3afbefe75a57",
               "Name":"Cheat Sheet",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603555770)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"788.114 KB",
               "Url":"https://xxxxxjyqoBQ",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603555770)\/",
               "ModifiedBy":"Christopher"
            }
         ],
         "Directories":[

         ]
      },
      {
         "Id":"e9d28c6b-8e6d-4429-8ea4-eb3dc3bc64eb",
         "Name":"Franchise",
         "Description":"All things xxx",
         "ParentId":null,
         "Documents":[

         ],
         "Directories":[
            {
               "Id":"d0c9eced-9d02-4332-be47-f1ff2e5a7fe6",
               "Name":"Fitout",
               "Description":"Description",
               "ParentId":"e9d28c6b-8e6d-4429-8ea4-eb3dc3bc64eb",
               "Documents":[
                  {
                     "LatestVersion":true,
                     "Id":"b0c17fbe-fd15-4343-9032-039e79d461bc",
                     "Name":"Finding and Fitting out Your xxxx (Deck)",
                     "Description":"",
                     "Extension":"pdf",
                     "Secured":true,
                     "Printable":false,
                     "Downloadable":false,
                     "CoverImage":"",
                     "Public":false,
                     "CreatedDate":"\/Date(1509524413437)\/",
                     "CreatedBy":"Christopher",
                     "Version":1,
                     "DirectoryId":"d0c9eced-9d02-4332-be47-f1ff2e5a7fe6",
                     "Size":"8.395 MB",
                     "Url":"https://xxxxxPhIf5g",
                     "VersionNotes":"",
                     "ModifiedDate":"\/Date(1509524413437)\/",
                     "ModifiedBy":"Christopher"
                  }
               ],
               "Directories":[

               ]
            }
         ]
      }
   ]
}```

If anyone could point me in the right direction (either a JS or C# based approach (would prefer backend though) that would be great.

Thank you

答:
```<code>        from i in
            (from i in list where i.ParentId == parentId select i)
        let subDirectories = FlatToHierarchy(list, documents, i.Id)
        where (documents.Any(x => x.DirectoryId == i.Id) || subDirectories.Any())
        select new
        {
            ...
            Directories = subDirectories
        };
</code>```

Body:
I am building my own simple document display model with the concept of Directories (Folders) with containing Documents.  I have built the database and can successfully get a list of all the documents that are in each folder.  My security model has only security on a document level and NOT on a folder level so when i render out the display of folders (and documents) alot of the time many users are seeing empty folders which are not relevant.  What is an efficient way of filtering out the folders that don't contain direct children of documents (except those that have nested folders who DO contain documents)

Below is my recursive function that generates my JSON

        public List<DirectoryViewModel> FlatToHierarchy(List<Data.Directory> list, List<MyDocumentsViewModel> documents, Guid? parentId = null)
    {
        return (from i in list
                where i.ParentId == parentId
                select new DirectoryViewModel
                {
                    Id = i.Id,
                    Description = i.Description,
                    ParentId = i.ParentId,
                    Name = i.Name,

                    Documents = documents.Where(x => x.DirectoryId == i.Id).ToList(),
                    Directories = FlatToHierarchy(list, documents, i.Id)
                }).ToList();
    }

and below is an example of the output generated

{
   "Directories":[
      {
         "Id":"8072d20b-c424-465e-87be-7b09ad64a6cc",
         "Name":"Front of House",
         "Description":"Checklists \u0026 Evaluations",
         "ParentId":null,
         "Documents":[
            {
               "LatestVersion":false,
               "Id":"7a580b85-edff-4c18-9ba4-ea893a5b1c11",
               "Name":"Welcome Pack",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603479817)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"263.822 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603479817)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":false,
               "Id":"b288a86d-370e-43b2-a938-f817468ccc44",
               "Name":"scenarios",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603539867)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"816.909 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603539867)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":false,
               "Id":"67ac3117-309b-40d5-82ca-424de9723d20",
               "Name":"Tour",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603617990)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"262.362 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603617990)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":false,
               "Id":"734bf12e-a219-4190-b390-0369901174bb",
               "Name":"Evaluation Sheet",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603797893)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"670.168 KB",
               "Url":"",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603797893)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"64907293-4fde-4f5c-a6f3-640e002c8122",
               "Name":"Walk-through",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603503013)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"500.525 KB",
               "Url":"https://xxxxx5VtqKA",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603503013)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"bcdb12a6-de80-45c3-ac97-0cab879a4b34",
               "Name":"staff",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603575103)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"279.536 KB",
               "Url":"https://xxxxxaVnDfQ",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603575103)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"b1d02b16-a0ba-4100-ada0-ce36ec647f36",
               "Name":"Checklist",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603522967)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"244.976 KB",
               "Url":"https://xxxxxdSngtA",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603522967)\/",
               "ModifiedBy":"Christopher"
            },
            {
               "LatestVersion":true,
               "Id":"226ceb41-ff93-4a4a-963b-3afbefe75a57",
               "Name":"Cheat Sheet",
               "Description":"",
               "Extension":"pdf",
               "Secured":false,
               "Printable":true,
               "Downloadable":true,
               "CoverImage":"",
               "Public":false,
               "CreatedDate":"\/Date(1509603555770)\/",
               "CreatedBy":"Christopher",
               "Version":1,
               "DirectoryId":"8072d20b-c424-465e-87be-7b09ad64a6cc",
               "Size":"788.114 KB",
               "Url":"https://xxxxxjyqoBQ",
               "VersionNotes":"",
               "ModifiedDate":"\/Date(1509603555770)\/",
               "ModifiedBy":"Christopher"
            }
         ],
         "Directories":[

         ]
      },
      {
         "Id":"e9d28c6b-8e6d-4429-8ea4-eb3dc3bc64eb",
         "Name":"Franchise",
         "Description":"All things xxx",
         "ParentId":null,
         "Documents":[

         ],
         "Directories":[
            {
               "Id":"d0c9eced-9d02-4332-be47-f1ff2e5a7fe6",
               "Name":"Fitout",
               "Description":"Description",
               "ParentId":"e9d28c6b-8e6d-4429-8ea4-eb3dc3bc64eb",
               "Documents":[
                  {
                     "LatestVersion":true,
                     "Id":"b0c17fbe-fd15-4343-9032-039e79d461bc",
                     "Name":"Finding and Fitting out Your xxxx (Deck)",
                     "Description":"",
                     "Extension":"pdf",
                     "Secured":true,
                     "Printable":false,
                     "Downloadable":false,
                     "CoverImage":"",
                     "Public":false,
                     "CreatedDate":"\/Date(1509524413437)\/",
                     "CreatedBy":"Christopher",
                     "Version":1,
                     "DirectoryId":"d0c9eced-9d02-4332-be47-f1ff2e5a7fe6",
                     "Size":"8.395 MB",
                     "Url":"https://xxxxxPhIf5g",
                     "VersionNotes":"",
                     "ModifiedDate":"\/Date(1509524413437)\/",
                     "ModifiedBy":"Christopher"
                  }
               ],
               "Directories":[

               ]
            }
         ]
      }
   ]
}

If anyone could point me in the right direction (either a JS or C# based approach (would prefer backend though) that would be great.

Thank you


问:
Java String.Format Specifications
I've spent a while searching google. It has lead to a few articles from here, and elsewhere.
I'm looking to use the string format engine (or w.e it should be called - please give me the proper term if you know it) to get the end of an input string rather than the start of the string..

Example:

```<code>System.out.printf("[%tY/%<tm/%<td-%<tH.%<tM.%<tS][%-20.20s] %s%n", new Date(), "long.string.class.test.TestClass", "Content Test...");
</code>```

Outputs:

```<code>[2017/12/05-21.49.11]"[long.string.class.te] Content Test...
</code>```

Whereas I want:

```<code>[2017/12/05-21.49.11]"[class.test.TestClass] Content Test...
</code>```

In addition, I was curious if it's possible to also replace the first 3 characters with '...' should the string exceed the 20 character limit..

答:
You can't do that solely in the format string, you have to pass the text you want to print.  That's not exactly hard...

```<code>    String[] data = { "a short string", "a very long string to see that we get only the last 20 characters" };

    for (String s : data)
    {
        System.out.println("....:....|....:....|");
        System.out.printf("%20s\n",s.substring(Math.max(0, s.length()-20)));
    }
</code>```

Adjust to %s if you don't want a fixed length, and %-20s to left-justify if you want.

Output:

```<code>....:....|....:....|
      a short string
....:....|....:....|
e last 20 characters
</code>```

Title: Java String.Format Specifications

Body:
I've spent a while searching google. It has lead to a few articles from here, and elsewhere.
I'm looking to use the string format engine (or w.e it should be called - please give me the proper term if you know it) to get the end of an input string rather than the start of the string..

Example:

System.out.printf("[%tY/%<tm/%<td-%<tH.%<tM.%<tS][%-20.20s] %s%n", new Date(), "long.string.class.test.TestClass", "Content Test...");

Outputs:

[2017/12/05-21.49.11]"[long.string.class.te] Content Test...

Whereas I want:

[2017/12/05-21.49.11]"[class.test.TestClass] Content Test...

In addition, I was curious if it's possible to also replace the first 3 characters with '...' should the string exceed the 20 character limit..

Body:
You can't do that solely in the format string, you have to pass the text you want to print.  That's not exactly hard...

    String[] data = { "a short string", "a very long string to see that we get only the last 20 characters" };

    for (String s : data)
    {
        System.out.println("....:....|....:....|");
        System.out.printf("%20s\n",s.substring(Math.max(0, s.length()-20)));
    }

Adjust to %s if you don't want a fixed length, and %-20s to left-justify if you want.

Output:

....:....|....:....|
      a short string
....:....|....:....|
e last 20 characters


问:
i draw a circle with pygame, but it says i have too many arguments
I am coding a game for a project and am trying to figure out how to draw a circle that I can use as a button. I have used the pygame.draw.circle function. here is my current code:

```<code>import pygame
block_color = (0, 0, 255)
display_height = 600
display_width = 600
pygame.init()
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.draw.circle(gameDisplay, block_color, (50, 50), 20, 0)
thing_width = 100
thing_height = 100
thing_startx = 10
thing_starty = 10
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
pygame.display.update()
</code>```

according to the pygame function documentation, this should work, but all I get is:

```<code>line 12, in <module>
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
NameError: name 'circle' is not defined
</code>```

答:
You are using pygame.draw.rect instead of pygame.draw.circle. Try the following instead:

```<code>pygame.draw.circle(gameDisplay, block_color, (50, 50), 20, 0)
</code>```

circle(Surface, color, pos, radius, width=0) -> Rect

  Draws a circular shape on the Surface. The pos argument is the center of the circle, and radius is the size. The width argument is the thickness to draw the outer edge. If width is zero then the circle will be filled.

Body:
I am coding a game for a project and am trying to figure out how to draw a circle that I can use as a button. I have used the pygame.draw.circle function. here is my current code:

import pygame
block_color = (0, 0, 255)
display_height = 600
display_width = 600
pygame.init()
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.draw.circle(gameDisplay, block_color, (50, 50), 20, 0)
thing_width = 100
thing_height = 100
thing_startx = 10
thing_starty = 10
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
pygame.display.update()

according to the pygame function documentation, this should work, but all I get is:

line 12, in <module>
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
NameError: name 'circle' is not defined

Body:
You are using pygame.draw.rect instead of pygame.draw.circle. Try the following instead:

pygame.draw.circle(gameDisplay, block_color, (50, 50), 20, 0)

circle(Surface, color, pos, radius, width=0) -> Rect

  Draws a circular shape on the Surface. The pos argument is the center of the circle, and radius is the size. The width argument is the thickness to draw the outer edge. If width is zero then the circle will be filled.


问:
Secure API AuthSub in Java (Google Calendar API)
I would like to authenticate my Google AuthSub requests.  Basically I need to generate a private key and respective certificate, upload this certificate to Google, and sign with the key on subsequent calls to Google AuthSub.  I think the most straightforward approach is to use Java's keytool as follows:

```<code># Generate the RSA keys and certificate
keytool -genkey -v -alias Example -keystore ./Example.jks\
  -keyalg RSA -sigalg SHA1withRSA\
  -dname "CN=www.example.com, OU=Engineering, O=My_Company, L=Mountain  View, ST=CA, C=US"\
  -storepass changeme -keypass changeme

# Output the public certificate to a file
keytool -export -rfc -keystore ./Example.jks -storepass changeme \
  -alias Example -file mycert.pem
</code>```

(As specified by http://code.google.com/apis/gdata/docs/auth/authsub.html#keytool)

I uploaded the given certificate, mycert.pem to Google.  In my Java client, I then loaded the private key as follows:

```<code>PrivateKey key = AuthSubUtil.getPrivateKeyFromKeystore(
                               "Example.jks", "changeme", "Example", "changeme");
</code>```

No exceptions are thrown upon loading this key.  The key is then used during AuthSub calls, as follows.

```<code>String requestUrl =
  AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
                            "https://www.google.com/calendar/feeds/",
                            true,
                            true);
...
// Servlet context, user follows the 'next link' with token attached.
String onetimeUseToken = AuthSubUtil.getTokenFromReply(
                                           httpServletRequest.getQueryString());

// Exchange for the AuthSub token.
String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken, key);

// Use the token.
CalendarService.setAuthSubToken(sessionToken, key);

// Get calendars from the user.
URL feedUrl =
    new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");

// Exception is thrown HERE.
CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);
</code>```

The exception is not thrown while setting or exchanging the token, but rather upon attempting to access the user's resources.  I'm not quite sure what to make of this.  The exception is as follows:

```<code>Token invalid - Invalid AuthSub token.
</code>```

I toyed around a bit with https:// versus http:// for the feed URL and scope URL, but with little success, it's possible I haven't tried a certain combination though.

答: Seems like all of the above works correctly, I just had an irrelevant coding error.  For the record, http and https both work as long as one is used consistently (otherwise you get a 'scope' error).</p>

Body:
I would like to authenticate my Google AuthSub requests.  Basically I need to generate a private key and respective certificate, upload this certificate to Google, and sign with the key on subsequent calls to Google AuthSub.  I think the most straightforward approach is to use Java's keytool as follows:

# Generate the RSA keys and certificate
keytool -genkey -v -alias Example -keystore ./Example.jks\
  -keyalg RSA -sigalg SHA1withRSA\
  -dname "CN=www.example.com, OU=Engineering, O=My_Company, L=Mountain  View, ST=CA, C=US"\
  -storepass changeme -keypass changeme

# Output the public certificate to a file
keytool -export -rfc -keystore ./Example.jks -storepass changeme \
  -alias Example -file mycert.pem

(As specified by http://code.google.com/apis/gdata/docs/auth/authsub.html#keytool)

I uploaded the given certificate, mycert.pem to Google.  In my Java client, I then loaded the private key as follows:

PrivateKey key = AuthSubUtil.getPrivateKeyFromKeystore(
                               "Example.jks", "changeme", "Example", "changeme");

No exceptions are thrown upon loading this key.  The key is then used during AuthSub calls, as follows.

String requestUrl =
  AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
                            "https://www.google.com/calendar/feeds/",
                            true,
                            true);
...
// Servlet context, user follows the 'next link' with token attached.
String onetimeUseToken = AuthSubUtil.getTokenFromReply(
                                           httpServletRequest.getQueryString());

// Exchange for the AuthSub token.
String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken, key);

// Use the token.
CalendarService.setAuthSubToken(sessionToken, key);

// Get calendars from the user.
URL feedUrl =
    new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");

// Exception is thrown HERE.
CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);

The exception is not thrown while setting or exchanging the token, but rather upon attempting to access the user's resources.  I'm not quite sure what to make of this.  The exception is as follows:

Token invalid - Invalid AuthSub token.

I toyed around a bit with https:// versus http:// for the feed URL and scope URL, but with little success, it's possible I haven't tried a certain combination though.


问:
Unable to find CMake in Android Studio
I need to add C/C++ code in my Android program for which I needed LLDB, CMake, and NDK. I found LLDB and NDK in SDK manager, but CMake is missing from there. I tried manually downloading it from the CMake official site and found out that for Android we need SDK customized CMake.

As you can see there is no option such as CMake.

Where do I find a version of CMake for Android?

I have tried CMake from the website and one I found in ndk-bundle/build folder, but both are giving the same error as below. What can be made out of it and how can the issue be solved?

```<code>Build command failed.

Error while executing 'C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\cmake.exe' with arguments {-HC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni -BC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\.externalNativeBuild\cmake\debug\armeabi -GAndroid Gradle - Ninja -DANDROID_ABI=armeabi -DANDROID_NDK=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\build\intermediates\cmake\debug\obj\armeabi -DCMAKE_BUILD_TYPE=Debug -DCMAKE_MAKE_PROGRAM=C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\ninja.exe -DCMAKE_TOOLCHAIN_FILE=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle\build\cmake\android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=15 -DCMAKE_CXX_FLAGS=-std=c++11 -DANDROID_TOOLCHAIN=clang -DANDROID_STL=gnustl_static}
CMake Error: Could not create named generator Android Gradle - Ninja
Generators
  Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 9 2008 [arch]  = Generates Visual Studio 2008 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 8 2005 [arch]  = Generates Visual Studio 2005 project files.
                                 Optional [arch] can be "Win64".
  Visual Studio 7 .NET 2003    = Deprecated.  Generates Visual Studio .NET
                                 2003 project files.
  Borland Makefiles            = Generates Borland makefiles.
  NMake Makefiles              = Generates NMake makefiles.
  NMake Makefiles JOM          = Generates JOM makefiles.
  Green Hills MULTI            = Generates Green Hills MULTI files
                                 (experimental, work-in-progress).
  MSYS Makefiles               = Generates MSYS makefiles.
  MinGW Makefiles              = Generates a make file for use with
                                 mingw32-make.
  Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
  CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files.
  CodeBlocks - NMake Makefiles = Generates CodeBlocks project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - MinGW Makefiles   = Generates CodeLite project files.
  CodeLite - NMake Makefiles   = Generates CodeLite project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - MinGW Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - NMake Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - MinGW Makefiles       = Generates Kate project files.
  Kate - NMake Makefiles       = Generates Kate project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - NMake Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - MinGW Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.
Error:executing external native build for cmake C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni\CMakeLists.txt
</code>```

答:
Go to Android SDK manager

Select Android SDK Tools

Find CMake and click Apply to download.

Later click OK

Title: Unable to find CMake in Android Studio

Body:
I need to add C/C++ code in my Android program for which I needed LLDB, CMake, and NDK. I found LLDB and NDK in SDK manager, but CMake is missing from there. I tried manually downloading it from the CMake official site and found out that for Android we need SDK customized CMake.

As you can see there is no option such as CMake.

Where do I find a version of CMake for Android?

I have tried CMake from the website and one I found in ndk-bundle/build folder, but both are giving the same error as below. What can be made out of it and how can the issue be solved?

Build command failed.

Error while executing 'C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\cmake.exe' with arguments {-HC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni -BC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\.externalNativeBuild\cmake\debug\armeabi -GAndroid Gradle - Ninja -DANDROID_ABI=armeabi -DANDROID_NDK=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\build\intermediates\cmake\debug\obj\armeabi -DCMAKE_BUILD_TYPE=Debug -DCMAKE_MAKE_PROGRAM=C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\ninja.exe -DCMAKE_TOOLCHAIN_FILE=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle\build\cmake\android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=15 -DCMAKE_CXX_FLAGS=-std=c++11 -DANDROID_TOOLCHAIN=clang -DANDROID_STL=gnustl_static}
CMake Error: Could not create named generator Android Gradle - Ninja
Generators
  Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 9 2008 [arch]  = Generates Visual Studio 2008 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 8 2005 [arch]  = Generates Visual Studio 2005 project files.
                                 Optional [arch] can be "Win64".
  Visual Studio 7 .NET 2003    = Deprecated.  Generates Visual Studio .NET
                                 2003 project files.
  Borland Makefiles            = Generates Borland makefiles.
  NMake Makefiles              = Generates NMake makefiles.
  NMake Makefiles JOM          = Generates JOM makefiles.
  Green Hills MULTI            = Generates Green Hills MULTI files
                                 (experimental, work-in-progress).
  MSYS Makefiles               = Generates MSYS makefiles.
  MinGW Makefiles              = Generates a make file for use with
                                 mingw32-make.
  Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
  CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files.
  CodeBlocks - NMake Makefiles = Generates CodeBlocks project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - MinGW Makefiles   = Generates CodeLite project files.
  CodeLite - NMake Makefiles   = Generates CodeLite project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - MinGW Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - NMake Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - MinGW Makefiles       = Generates Kate project files.
  Kate - NMake Makefiles       = Generates Kate project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - NMake Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - MinGW Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.
Error:executing external native build for cmake C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni\CMakeLists.txt


问:
Python 3 Player not moving
```<code>class Player(pg.sprite.Sprite):
    def __init__(self):
       pg.sprite.Sprite.__init__(self)
       self.x = 32
       self.y = 32
       self.yspeed = 0
       self.xspeed = 0
       self.image = pg.draw.rect(screen, yellow, (self.x, self.y, tilesize, tilesize))
       self.rect = pg.Rect(self.x, self.y, 32, 32)

    def moveRight(self):
        self.xspeed = 5
        self.yspeed = 0

    def moveLeft(self):
        self.xspeed = -5
        self.yspeed = 0

    def moveUp(self):
        self.xspeed = 0
        self.yspeed = -5

    def moveDown(self):
        self.xspeed = 0
        self.yspeed = 5

playing = True
while playing:

    p = Player()

    for event in pg.event.get():

        if event.type == pg.QUIT:
            playing = False

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_d:
                p.moveRight()
            if event.key == pg.K_a:
                p.moveLeft()
            if event.key == pg.K_w:
                p.moveUp()
            if event.key == pg.K_s:
                p.moveDown()

    p.x += p.xspeed
    p.y += p.yspeed

    screen.fill(black)
    p.__init__()
    drawGrid()
    pg.display.update()
    clock.tick(60)
</code>```

Confused as to why my player is not moving? Just making a simple game loop where the player continually goes in one direction until pressed otherwise 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

答:
Big mistake: don't create p = Player() inside while playing because it recreates Player() in every loop so it reset all information.

Create Player() before while

And don't use p.__init__() because it reset informations too.

To draw it you need

```<code>screen.blit(p.image, p.rect)
</code>```

But I see another mistake

```<code>self.image = pg.draw.rect(screen, yellow, (self.x, self.y, tilesize, tilesize))
</code>```

pygame.draw.rect() doesn't create image, it draws directly on screen and returns Rect().

It needs more changes.

EDIT: Code could look like this:

```<code>class Player(pg.sprite.Sprite):

    def __init__(self):
       pg.sprite.Sprite.__init__(self)
       self.x = 32
       self.y = 32
       self.yspeed = 0
       self.xspeed = 0

    def draw(self, screen):
       pg.draw.rect(screen, yellow, (self.x, self.y, tilesize, tilesize))

    def moveRight(self):
        self.xspeed = 5
        self.yspeed = 0

    def moveLeft(self):
        self.xspeed = -5
        self.yspeed = 0

    def moveUp(self):
        self.xspeed = 0
        self.yspeed = -5

    def moveDown(self):
        self.xspeed = 0
        self.yspeed = 5

p = Player()
playing = True
while playing:

    for event in pg.event.get():

        if event.type == pg.QUIT:
            playing = False

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_d:
                p.moveRight()
            if event.key == pg.K_a:
                p.moveLeft()
            if event.key == pg.K_w:
                p.moveUp()
            if event.key == pg.K_s:
                p.moveDown()

    p.x += p.xspeed
    p.y += p.yspeed

    screen.fill(black)
    p.draw()
    drawGrid()
    pg.display.update()
    clock.tick(60)
</code>```

Title: Python 3 Player not moving

Body:
class Player(pg.sprite.Sprite):
    def __init__(self):
       pg.sprite.Sprite.__init__(self)
       self.x = 32
       self.y = 32
       self.yspeed = 0
       self.xspeed = 0
       self.image = pg.draw.rect(screen, yellow, (self.x, self.y, tilesize, tilesize))
       self.rect = pg.Rect(self.x, self.y, 32, 32)

    def moveRight(self):
        self.xspeed = 5
        self.yspeed = 0

    def moveLeft(self):
        self.xspeed = -5
        self.yspeed = 0

    def moveUp(self):
        self.xspeed = 0
        self.yspeed = -5

    def moveDown(self):
        self.xspeed = 0
        self.yspeed = 5

playing = True
while playing:

    p = Player()

    for event in pg.event.get():

        if event.type == pg.QUIT:
            playing = False

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_d:
                p.moveRight()
            if event.key == pg.K_a:
                p.moveLeft()
            if event.key == pg.K_w:
                p.moveUp()
            if event.key == pg.K_s:
                p.moveDown()

    p.x += p.xspeed
    p.y += p.yspeed

    screen.fill(black)
    p.__init__()
    drawGrid()
    pg.display.update()
    clock.tick(60)

Confused as to why my player is not moving? Just making a simple game loop where the player continually goes in one direction until pressed otherwise 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

Body:
Big mistake: don't create p = Player() inside while playing because it recreates Player() in every loop so it reset all information.

Create Player() before while

And don't use p.__init__() because it reset informations too.

To draw it you need

screen.blit(p.image, p.rect)

But I see another mistake

self.image = pg.draw.rect(screen, yellow, (self.x, self.y, tilesize, tilesize))

pygame.draw.rect() doesn't create image, it draws directly on screen and returns Rect().

It needs more changes.

EDIT: Code could look like this:

class Player(pg.sprite.Sprite):

    def __init__(self):
       pg.sprite.Sprite.__init__(self)
       self.x = 32
       self.y = 32
       self.yspeed = 0
       self.xspeed = 0

    def draw(self, screen):
       pg.draw.rect(screen, yellow, (self.x, self.y, tilesize, tilesize))

    def moveRight(self):
        self.xspeed = 5
        self.yspeed = 0

    def moveLeft(self):
        self.xspeed = -5
        self.yspeed = 0

    def moveUp(self):
        self.xspeed = 0
        self.yspeed = -5

    def moveDown(self):
        self.xspeed = 0
        self.yspeed = 5

p = Player()
playing = True
while playing:

    for event in pg.event.get():

        if event.type == pg.QUIT:
            playing = False

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_d:
                p.moveRight()
            if event.key == pg.K_a:
                p.moveLeft()
            if event.key == pg.K_w:
                p.moveUp()
            if event.key == pg.K_s:
                p.moveDown()

    p.x += p.xspeed
    p.y += p.yspeed

    screen.fill(black)
    p.draw()
    drawGrid()
    pg.display.update()
    clock.tick(60)


问:
MongoDB nested aggregation not finding inner collection
I am new to Stack and MongoDB. I have adjusted my codes based on other posts but couldn't figure out where i went wrong. I have three collections. Microbe is connected to Activities (1 to M) and Activities to Bio-Activities (1 to M). I would like to show the nest from Microbe until Bio-Activities in the form of an array.

```<code>Microbe collection
{"_id": 1, item: "abc", species: 12, quantity: 2},
{"_id": 2, item: "jkl", species: 20, quantity: 1},
{"_id": 3}

Activities collection
{"_id": 1, code: "MON1003", item: "abc", type: "Monitor", repeat: 120, size: "27", resolution: "1920x1080"},
{"_id": 2, code: "MON1012", item: "abc", type: "Monitor", repeat: 85, size: "23", resolution: "1280x800"},
{"_id": 3, code: "MON1031", item: "jkl", type: "Monitor", repeat: 60, size: "21", resolution: "1920x1080"}

Bio-Activities collection
{"_id": 1, code: "MON1003", description: "bio 1", quantity: 120},
{"_id": 2, code: "MON1003", description: "bio 2", quantity: 80},
{"_id": 3, code: "MON1012", description: "bio 3", quantity: 60},
{"_id": 4, code: "MON1012", description: "bio 4", quantity: 70},
{"_id": 5, code: "MON1012", description: "bio 5", quantity: 170},
{"_id": 6, code: "MON1031", description: "bio 6", quantity: 270}
</code>```

This is my code:

```<code>db.microbe.aggregate([
{
$lookup:
{
from: "activities",
localField: "item",
foreignField: "item",
as: "activities"
}
},{
$lookup:
{
    from: "bioactivities",
    localField: "code",
    foreignField: "code",
    as: "bioactivities"
}
},{
    $unwind: "$activities"
},{
$group: {
    _id: "$_id",
    item: {$first: "$item"},
    species: {$first: "$species"},
    quantity: {$first: "$quantity"},
    activities: {$push: {
        id: "$activities._id",
        code: "$activities.code",
        item: "$activities.item",
        type: "$activities.type",
        repeat: "$activities.repeat",
        size: "$activities.size",
        bioactivities: "$bioactivities"
    }
    }
}
}
]).pretty()
</code>```

But I get this output which shows empty "bioactivities". Where did I go wrong?

```<code>    {
    "_id" : 2,
    "item" : "jkl",
    "species" : 20,
            "quantity" : 1,
            "activities" : [
                    {
                    "id" : 3,
                    "code" : "MON1031",
                    "item" : "jkl",
                    "type" : "Monitor",
                    "repeat" : 60,
                    "size" : "21",
                    "bioactivities" : [ ]
            }
    ]
    }
    {
            "_id" : 1,
            "item" : "abc",
            "species" : 12,
            "quantity" : 2,
            "activities" : [
            {
                    "id" : 1,
                    "code" : "MON1003",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 120,
                    "size" : "27",
                    "bioactivities" : [ ]
            },
            {
                    "id" : 2,
                    "code" : "MON1012",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 85,
                    "size" : "23",
                    "bioactivities" : [ ]
            }
    ]
    }
</code>```

Thanks.

答:
Got it. "Order does matter", quoting Mongo's video.
Solution: I should $unwind my "activities" before I do a $lookup to "bioactivities". Here's the code.</p>

```<code>    db.microbe.aggregate([
    {
    $lookup:
    {
        from: "activities",
        localField: "item",
        foreignField: "item",
        as: "activities"
    }
    },{
        $unwind: "$activities"
    },{
        $lookup:
    {
        from: "bioactivities",
        localField: "activities.code",
        foreignField: "code",
        as: "bioactivities"
    }
    },{
        $group: {
            _id: "$_id",
            item: {$first: "$item"},
            species: {$first: "$species"},
            quantity: {$first: "$quantity"},
            activities: {$push: {
                 id: "$activities._id",
                 code: "$activities.code",
                 item: "$activities.item",
                 type: "$activities.type",
                 repeat: "$activities.repeat",
                 size: "$activities.size",
                 bioactivities: "$bioactivities"
            }
       }
    }
    }
    ]).pretty()
</code>```

Body:
I am new to Stack and MongoDB. I have adjusted my codes based on other posts but couldn't figure out where i went wrong. I have three collections. Microbe is connected to Activities (1 to M) and Activities to Bio-Activities (1 to M). I would like to show the nest from Microbe until Bio-Activities in the form of an array.

Microbe collection
{"_id": 1, item: "abc", species: 12, quantity: 2},
{"_id": 2, item: "jkl", species: 20, quantity: 1},
{"_id": 3}

Activities collection
{"_id": 1, code: "MON1003", item: "abc", type: "Monitor", repeat: 120, size: "27", resolution: "1920x1080"},
{"_id": 2, code: "MON1012", item: "abc", type: "Monitor", repeat: 85, size: "23", resolution: "1280x800"},
{"_id": 3, code: "MON1031", item: "jkl", type: "Monitor", repeat: 60, size: "21", resolution: "1920x1080"}

Bio-Activities collection
{"_id": 1, code: "MON1003", description: "bio 1", quantity: 120},
{"_id": 2, code: "MON1003", description: "bio 2", quantity: 80},
{"_id": 3, code: "MON1012", description: "bio 3", quantity: 60},
{"_id": 4, code: "MON1012", description: "bio 4", quantity: 70},
{"_id": 5, code: "MON1012", description: "bio 5", quantity: 170},
{"_id": 6, code: "MON1031", description: "bio 6", quantity: 270}

This is my code:

db.microbe.aggregate([
{
$lookup:
{
from: "activities",
localField: "item",
foreignField: "item",
as: "activities"
}
},{
$lookup:
{
    from: "bioactivities",
    localField: "code",
    foreignField: "code",
    as: "bioactivities"
}
},{
    $unwind: "$activities"
},{
$group: {
    _id: "$_id",
    item: {$first: "$item"},
    species: {$first: "$species"},
    quantity: {$first: "$quantity"},
    activities: {$push: {
        id: "$activities._id",
        code: "$activities.code",
        item: "$activities.item",
        type: "$activities.type",
        repeat: "$activities.repeat",
        size: "$activities.size",
        bioactivities: "$bioactivities"
    }
    }
}
}
]).pretty()

But I get this output which shows empty "bioactivities". Where did I go wrong?

    {
    "_id" : 2,
    "item" : "jkl",
    "species" : 20,
            "quantity" : 1,
            "activities" : [
                    {
                    "id" : 3,
                    "code" : "MON1031",
                    "item" : "jkl",
                    "type" : "Monitor",
                    "repeat" : 60,
                    "size" : "21",
                    "bioactivities" : [ ]
            }
    ]
    }
    {
            "_id" : 1,
            "item" : "abc",
            "species" : 12,
            "quantity" : 2,
            "activities" : [
            {
                    "id" : 1,
                    "code" : "MON1003",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 120,
                    "size" : "27",
                    "bioactivities" : [ ]
            },
            {
                    "id" : 2,
                    "code" : "MON1012",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 85,
                    "size" : "23",
                    "bioactivities" : [ ]
            }
    ]
    }

Thanks.

Body:
Got it. "Order does matter", quoting Mongo's video.
Solution: I should $unwind my "activities" before I do a $lookup to "bioactivities". Here's the code.

    db.microbe.aggregate([
    {
    $lookup:
    {
        from: "activities",
        localField: "item",
        foreignField: "item",
        as: "activities"
    }
    },{
        $unwind: "$activities"
    },{
        $lookup:
    {
        from: "bioactivities",
        localField: "activities.code",
        foreignField: "code",
        as: "bioactivities"
    }
    },{
        $group: {
            _id: "$_id",
            item: {$first: "$item"},
            species: {$first: "$species"},
            quantity: {$first: "$quantity"},
            activities: {$push: {
                 id: "$activities._id",
                 code: "$activities.code",
                 item: "$activities.item",
                 type: "$activities.type",
                 repeat: "$activities.repeat",
                 size: "$activities.size",
                 bioactivities: "$bioactivities"
            }
       }
    }
    }
    ]).pretty()


问:
Android gmail can't scale background image correctly

```

See code above.  On android, the image is not scaled correctly. See image attached.  Is there anyone who know how to fix it? Thanks!

答:
You are giving the table a width & height same as the td inside it. You should be able to use media queries to control the table height.

Try this code:

```<code><html>
  <head>
    <style type="text/css">
     @media only screen and (max-width:480px) {
     .bannerTable{width:100% !important;height:auto !important;}
     }
    </style>
  </head>
  <body>
  <td>
    <table align="center" background="{{imgUrl}}" width="597" style="width:100%; max-width:597px; height:461px;display:block;" class="bannerTable">
      <tr>
        <td>Content goes here</td>
      </tr>
    </table>
  </body>
</html>
</code>```

Hope this works for you

Body:
You are giving the table a width & height same as the td inside it. You should be able to use media queries to control the table height.

Try this code:

<html>
  <head>
    <style type="text/css">
     @media only screen and (max-width:480px) {
     .bannerTable{width:100% !important;height:auto !important;}
     }
    </style>
  </head>
  <body>
  <td>
    <table align="center" background="{{imgUrl}}" width="597" style="width:100%; max-width:597px; height:461px;display:block;" class="bannerTable">
      <tr>
        <td>Content goes here</td>
      </tr>
    </table>
  </body>
</html>

Hope this works for you


问:
What is database backed Cache and how does it work?
What is database backed Cache and how does it work ? Something similar in line of when the app server goes down and database is backed by cache there is no time wasted to repopulate an in memory cache</p>

答:
A database backed cache is a method of storing data that is costly (in resources or time) to generate or derive.  You could see them implemented for such things as:

improving web server performance by caching dynamic pages in a db as static html so additional hits to the page do not incur the overhead of regenerating the page.  Yes, this might be counter-intuitive as often database access is the bottleneck, though in some cases it is not.

Improving query time against a slow (or offsite) directory server or database.

If I understand your example correctly, I believe you might have it backwards.  The database is backing some other primary location.  For example, in an app server farm, if a security token is stored in a db backed cache and the app server you are currently interacting with goes down you could be routed to a different service instance. The token cache check it's in-memory cache which won't contain the token, so it will be retrieved from the database, deserialized and added to the (new) local cache.  The benefits are minimized network transport and improved resilience to failures.

Hope this helps.


问:
Error w/ Webpack Server
So I'm not really sure what's wrong, and I've looked into other solutions but none of them work. I've also looked at other similar issues and I still can't fix. Anyone have any ideas?

```<code> ERROR in multi (webpack)-dev-server/client?http://localhost:8080
 main.js
 Module not found: Error: Can't resolve 'main.js' in
 '/Users/11reed/Desktop/sty-fg'
 @ multi (webpack)-dev-server/client?http://localhost:8080 main.js
</code>```

here is my config

```<code> module.exports ={
    entry: 'main.js',
    output: {
        filename: 'sty-fg.js'
    },
    watch: true,
    module:{
        loaders:[
            {
            test: /\.styl$/,
            exclude: /node_modules/,
            loader: "style-loader!css-loader!stylus-loader"
            }
        ],
    }
}
</code>```

答:
I think basically webpack can't find main.js. Looks like you are missing a loader for js and a resolve for .js like so:

```<code>  resolve: {
    extensions: ['.js'],
  }
  module:{
    loaders:[
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: "babel-loader"
        },
        { // existing
          test: /\.styl$/,
          exclude: /node_modules/,
          loader: "style-loader!css-loader!stylus-loader"
        }
    ],
}
</code>```

Reference: https://webpack.js.org/loaders/babel-loader/

Title: Error w/ Webpack Server

Body:
So I'm not really sure what's wrong, and I've looked into other solutions but none of them work. I've also looked at other similar issues and I still can't fix. Anyone have any ideas?

 ERROR in multi (webpack)-dev-server/client?http://localhost:8080
 main.js
 Module not found: Error: Can't resolve 'main.js' in
 '/Users/11reed/Desktop/sty-fg'
 @ multi (webpack)-dev-server/client?http://localhost:8080 main.js

here is my config

 module.exports ={
    entry: 'main.js',
    output: {
        filename: 'sty-fg.js'
    },
    watch: true,
    module:{
        loaders:[
            {
            test: /\.styl$/,
            exclude: /node_modules/,
            loader: "style-loader!css-loader!stylus-loader"
            }
        ],
    }
}

Body:
I think basically webpack can't find main.js. Looks like you are missing a loader for js and a resolve for .js like so:

  resolve: {
    extensions: ['.js'],
  }
  module:{
    loaders:[
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: "babel-loader"
        },
        { // existing
          test: /\.styl$/,
          exclude: /node_modules/,
          loader: "style-loader!css-loader!stylus-loader"
        }
    ],
}

Reference: https://webpack.js.org/loaders/babel-loader/


问:
Python ICMP Pinger
I'm trying to make an ICMP Pinger for class but I get this error when I try to compile it. I'm not sure what else to do, most of the code is a skeleton code from my textbook so I'm not entirely sure what's going wrong.

When I compile this code

```<code>from socket import *
import os
import sys
import struct
import time
import select
import binascii

ICMP_ECHO_REQUEST = 8

def checksum(str):
    csum = 0
    countTo = (len(str) / 2) * 2

    count = 0
    while count < countTo:
        thisVal = ord(str(str[count+1])) * 256 + ord(str(str[count]))
        csum = csum + thisVal
        csum = csum & 0xffffffff
        count = count + 2

    if countTo < len(str):
        csum = csum + ord(str[leb(str) - 1])
        csum = csum & 0xffffffff

    csum = (csum >> 16) + (csum & 0xffff)
    csum = csum + (csum >> 16)
    answer = ~csum
    answer = answer & 0xffff
    andswer = answer >> 8 | (answer << 8 & 0xff00)
    return answer

def recieveOnePing(mySocket, ID, timeout, destAddr):
    timeLeft = timeout

    while 1:
        startedSelect = time.time()
        whatReady = select.select([mySocket], [], [], timeLeft)
        howLongInSelect = (time.time() - startedSelect)
        if whatReady[0] == []: # Timeout
            return "Request timed out."
        timeRecieved = time.time()
        recPacket, addr = mySocket.recvfrom(1024)

        icmph = recPacket[20:28]
        type, code, checksum, pID, sq = struct.unpack("bbHHh", icmph)

        print ("The header received in the ICMP reply is ",type, code, checksum, pID, sq)
        if pID == ID:
            bytesinDbl = struct.calcsize("d")
            timeSent = struct.unpack("d", recPacket[28:28 + bytesinDbl])[0]
            rtt=timeReceived - timeSent

        print ("RTT is : ")
        return rtt

        timeLeft = timeLeft - howLongInSelect
        if timeLeft <= 0:
            return "Request timed out"

def sendOnePing(mySocket, destAddr, ID):
    myChecksum = 0
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0 , myChecksum, ID, 1)
    data = struct.pack("d", time.time())
    myChecksum = checksum(header + data)

    if sys.platform == 'darwin':
        myChecksum = socket.htons(myChecksum) & 0xffff
    else:
        myChecksum = socket.htons(myChecksum)

    header = stuct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
    packet = header + data

    mySocket.sendto(packet, (destAddr, 1))

def doOnePing(destAddr, timeout):
    icmp = getprotobyname("icmp")

    mySocket = socket(AF_INET, SOCK_STREAM)

    myId = os.getpid() & 0xFFFF
    sendOnePing(mySocket, destAddr, myID)
    delay = recieveOnePing(mySocket, myID, timeout, destAddr)

    mySocket.close()
    return delay

def ping(host, timeout=1):
    dest = gethostbyname(host)
    print ("Pinging" + dest + "using Python:")
    print ("")
    while 1:
        delay = doOnePing(dest, timeout)
        print(delay)
        time.sleep(1)
    return delay

ping("www.google.com")
</code>```

I get this error

```<code>File "ICMPPinger.py", line 17, in checksum
    thisVal = ord(str(str[count+1])) * 256 + ord(str(str[count]))
TypeError: 'bytes' object is not callable
</code>```

Should I rename my variable? I'm not sure what this line is supposed to be doing and when I had it as

```<code>thisVal = ord(str[count+1]) * 256 + ord(str[count]))
</code>```

I got the error:
    File "ICMPPinger.py", line 17, in checksum thisVal = ord(str[count+1]) * 256 + ord(str[count]) TypeError: ord() expected string of length 1, but int found

答:
In def doOnePing() you have defined variable with name myId but you're passing variable as name myID which is why you get the undefined variable error. So as fix replace myId with myID as follows while defining the variable:

```<code>myID = os.getpid() & 0xFFFF
</code>```

Title: Python ICMP Pinger

Body:
I'm trying to make an ICMP Pinger for class but I get this error when I try to compile it. I'm not sure what else to do, most of the code is a skeleton code from my textbook so I'm not entirely sure what's going wrong.

When I compile this code

from socket import *
import os
import sys
import struct
import time
import select
import binascii

ICMP_ECHO_REQUEST = 8

def checksum(str):
    csum = 0
    countTo = (len(str) / 2) * 2

    count = 0
    while count < countTo:
        thisVal = ord(str(str[count+1])) * 256 + ord(str(str[count]))
        csum = csum + thisVal
        csum = csum & 0xffffffff
        count = count + 2

    if countTo < len(str):
        csum = csum + ord(str[leb(str) - 1])
        csum = csum & 0xffffffff

    csum = (csum >> 16) + (csum & 0xffff)
    csum = csum + (csum >> 16)
    answer = ~csum
    answer = answer & 0xffff
    andswer = answer >> 8 | (answer << 8 & 0xff00)
    return answer

def recieveOnePing(mySocket, ID, timeout, destAddr):
    timeLeft = timeout

    while 1:
        startedSelect = time.time()
        whatReady = select.select([mySocket], [], [], timeLeft)
        howLongInSelect = (time.time() - startedSelect)
        if whatReady[0] == []: # Timeout
            return "Request timed out."
        timeRecieved = time.time()
        recPacket, addr = mySocket.recvfrom(1024)

        icmph = recPacket[20:28]
        type, code, checksum, pID, sq = struct.unpack("bbHHh", icmph)

        print ("The header received in the ICMP reply is ",type, code, checksum, pID, sq)
        if pID == ID:
            bytesinDbl = struct.calcsize("d")
            timeSent = struct.unpack("d", recPacket[28:28 + bytesinDbl])[0]
            rtt=timeReceived - timeSent

        print ("RTT is : ")
        return rtt

        timeLeft = timeLeft - howLongInSelect
        if timeLeft <= 0:
            return "Request timed out"

def sendOnePing(mySocket, destAddr, ID):
    myChecksum = 0
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0 , myChecksum, ID, 1)
    data = struct.pack("d", time.time())
    myChecksum = checksum(header + data)

    if sys.platform == 'darwin':
        myChecksum = socket.htons(myChecksum) & 0xffff
    else:
        myChecksum = socket.htons(myChecksum)

    header = stuct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
    packet = header + data

    mySocket.sendto(packet, (destAddr, 1))

def doOnePing(destAddr, timeout):
    icmp = getprotobyname("icmp")

    mySocket = socket(AF_INET, SOCK_STREAM)

    myId = os.getpid() & 0xFFFF
    sendOnePing(mySocket, destAddr, myID)
    delay = recieveOnePing(mySocket, myID, timeout, destAddr)

    mySocket.close()
    return delay

def ping(host, timeout=1):
    dest = gethostbyname(host)
    print ("Pinging" + dest + "using Python:")
    print ("")
    while 1:
        delay = doOnePing(dest, timeout)
        print(delay)
        time.sleep(1)
    return delay

ping("www.google.com")

I get this error

File "ICMPPinger.py", line 17, in checksum
    thisVal = ord(str(str[count+1])) * 256 + ord(str(str[count]))
TypeError: 'bytes' object is not callable

Should I rename my variable? I'm not sure what this line is supposed to be doing and when I had it as

thisVal = ord(str[count+1]) * 256 + ord(str[count]))

I got the error:
    File "ICMPPinger.py", line 17, in checksum thisVal = ord(str[count+1]) * 256 + ord(str[count]) TypeError: ord() expected string of length 1, but int found

Body:
In def doOnePing() you have defined variable with name myId but you're passing variable as name myID which is why you get the undefined variable error. So as fix replace myId with myID as follows while defining the variable:

myID = os.getpid() & 0xFFFF


问:
linear-gradient not working in ionic3
I am trying to create a new gradient color in my Ionic3 variable.sass file.

```<code>$colors: (
  primary:    #4471C1,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222,
  newcolor: linear-gradient(#0fe2f3, #4caefe)
);
</code>```

This is giving me the following error

```<code>The value`` must be a color.
</code>```

How can I add a gradient color?

答:
You can try as shown below.

app.scss

```<code>.toolbar-background {
    background: -webkit-linear-gradient(-55deg, #50a2a7 35%, #e9b44c 100%) !important;
}
</code>```

UI

When I applied it to my app:

Title: linear-gradient not working in ionic3

Body:
I am trying to create a new gradient color in my Ionic3 variable.sass file.

$colors: (
  primary:    #4471C1,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222,
  newcolor: linear-gradient(#0fe2f3, #4caefe)
);

This is giving me the following error

The value`` must be a color.

How can I add a gradient color?

Body:
You can try as shown below.

app.scss

.toolbar-background {
    background: -webkit-linear-gradient(-55deg, #50a2a7 35%, #e9b44c 100%) !important;
}

UI

When I applied it to my app:


问:
How to add MySQL table column with a default value of another column of the existing row
The current existing table looks like this:

```<code>id    number    amount
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00
</code>```

Now i would like add new column allocated_amount with the default value of the amount column in every existing row.

```<code>id    number    amount      allocated_amount
1     123       30000.00    30000.00
2     123       15000.00    15000.00
3     321       45000.00    45000.00
...   ...       ...         ...
1000  567       75000.00    75000.00
</code>```

It is possible? Im using MySQL Workbench GUI.

答:
Virtual Column:</p>
```<code>alter table Table1
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;
</code>```

Body:
The current existing table looks like this:

id    number    amount
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00

Now i would like add new column allocated_amount with the default value of the amount column in every existing row.

id    number    amount      allocated_amount
1     123       30000.00    30000.00
2     123       15000.00    15000.00
3     321       45000.00    45000.00
...   ...       ...         ...
1000  567       75000.00    75000.00

It is possible? Im using MySQL Workbench GUI.

Body:
Virtual Column:

alter table Table1
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;


问:
Fastest way to code up hitting a URL
I need to login to a site, then hit a certain URL about a thousand times (with different params, of course).

The URL is something this:

```<code>http://www.foo.com/bar.asp?id=x    ' where x is the ID
</code>```

Of course if I simply hit the URL without being logged, it will fail.
I am not very familiar with this type of work, but I would imagine that whatever the method I choose, it would have to support cookies.

I was thinking that I could create a winform app with a browser control and somehow drive it, but that seems like a massive overkill.

Is there a better way?

答: You may want to look into WCAT if you are mainly interested in how your server performs under load.</p>

Title: Fastest way to code up hitting a URL

Body:
I need to login to a site, then hit a certain URL about a thousand times (with different params, of course).

The URL is something this:

http://www.foo.com/bar.asp?id=x    ' where x is the ID

Of course if I simply hit the URL without being logged, it will fail.
I am not very familiar with this type of work, but I would imagine that whatever the method I choose, it would have to support cookies.

I was thinking that I could create a winform app with a browser control and somehow drive it, but that seems like a massive overkill.

Is there a better way?


问:
How to return top 3 rows if last row is tied
Suppose my table contains data like that

```<code>  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80
</code>```

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

答:
```<code>Select * from Table_Name
ORDER BY Rating
LIMIT 4
</code>```

Body:
Suppose my table contains data like that

  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.