问:
Rails devise authentication, exclude login screen layouts
I'm using a devise authentication. I want the login page to come on a blank page. So, render ' layouts/navigation '.... <% = Render ' layouts/Topnavbar '%>..... <% = Render ' layouts/footer '% > I don't want this to be seen. How can I do that?

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  ##    milia defines a default max_tenants, invalid_tenant exception
   handling
  ##    but you can override these if you wish to handle directly
  rescue_from ::Milia::Control::MaxTenantExceeded, :with => :max_tenants
  rescue_from ::Milia::Control::InvalidTenantAccess, :with => :invalid_tenant

  before_action :authenticate_tenant!
end
</code>```

application.html.erb

```<code><div id="wrapper">
  <!-- Navigation -->
  <%= render 'layouts/navigation' %>

  <!-- Page wraper -->
  <div id="page-wrapper" class="gray-bg">

      <!-- Page wrapper -->
      <%= render 'layouts/topnavbar' %>

      <!-- Main view  -->
      <p class="notice"><%= notice %></p>
      <%= yield %>

      <!-- Footer -->
      <%= render 'layouts/footer' %>

  </div>
  <!-- End page wrapper-->
</code>```

```<code>class UsersController < ApplicationController
before_action :authenticate_user!

def index
    @users = User.all
end

def show
    @user = User.find(params[:id])
end

def destroy
    user = User.find(params[:id])
    user.destroy
    redirect_to users_path, :notice => "User deleted"
end

def update
    @user = User.find(params[:id])

    if @user.update_attributes(secure_params)
        redirect_to user_path, :success => 'User updated'
    else
        redirect_to user_path :alert => 'Unable to update user'
    end
end

end
</code>```

I understand... Unfortunately it does not work... I assume the Milia gem file does not use control. I used Milia/sessions not devise/sessions in routes. Uses the Milia members and users controls. Where render layout: false did not work

```<code>resources :members
  get 'home/index'

  root :to => "home#index"

  # *MUST* come *BEFORE* devise's definitions (below)
  as :user do
    match '/user/confirmation' => 'milia/confirmations#update', :via => :put, :as => :update_user_confirmation
  end

  devise_for :users, :controllers => {
    :registrations => "milia/registrations",
    :confirmations => "milia/confirmations",
    :sessions => "milia/sessions",
    :passwords => "milia/passwords",
  }
</code>```

答:
This worked for me. You think it's a neat code? Thanks for the help.</p>

```<code><% if user_signed_in? %>
      <%= render 'layouts/navigation' %>

      <!-- Page wraper -->
      <div id="page-wrapper" class="gray-bg">

          <!-- Page wrapper -->
          <%= render 'layouts/topnavbar' %>

          <!-- Main view  -->
          <%= yield %>

          <!-- Footer -->
          <%= render 'layouts/footer' %>

      </div>
      <!-- End page wrapper-->
    <% end %>
    <div class="gray-bg">
      <%= yield if controller_name != 'milia/sessions' && action_name == 'new' %>
    </div>
  </div>
</code>```

Body:
I'm using a devise authentication. I want the login page to come on a blank page. So, render ' layouts/navigation '.... <% = Render ' layouts/Topnavbar '%>..... <% = Render ' layouts/footer '% > I don't want this to be seen. How can I do that?

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  ##    milia defines a default max_tenants, invalid_tenant exception
   handling
  ##    but you can override these if you wish to handle directly
  rescue_from ::Milia::Control::MaxTenantExceeded, :with => :max_tenants
  rescue_from ::Milia::Control::InvalidTenantAccess, :with => :invalid_tenant

  before_action :authenticate_tenant!
end

application.html.erb

  <%= render 'layouts/navigation' %>

      <%= render 'layouts/topnavbar' %>

<%= notice %>

      <%= yield %>

      <%= render 'layouts/footer' %>

class UsersController < ApplicationController
before_action :authenticate_user!

def index
    @users = User.all
end

def show
    @user = User.find(params[:id])
end

def destroy
    user = User.find(params[:id])
    user.destroy
    redirect_to users_path, :notice => "User deleted"
end

def update
    @user = User.find(params[:id])

    if @user.update_attributes(secure_params)
        redirect_to user_path, :success => 'User updated'
    else
        redirect_to user_path :alert => 'Unable to update user'
    end
end

end

I understand... Unfortunately it does not work... I assume the Milia gem file does not use control. I used Milia/sessions not devise/sessions in routes. Uses the Milia members and users controls. Where render layout: false did not work

resources :members
  get 'home/index'

  root :to => "home#index"

  # *MUST* come *BEFORE* devise's definitions (below)
  as :user do
    match '/user/confirmation' => 'milia/confirmations#update', :via => :put, :as => :update_user_confirmation
  end

  devise_for :users, :controllers => {
    :registrations => "milia/registrations",
    :confirmations => "milia/confirmations",
    :sessions => "milia/sessions",
    :passwords => "milia/passwords",
  }

Body:
This worked for me. You think it's a neat code? Thanks for the help.

<% if user_signed_in? %>
      <%= render 'layouts/navigation' %>

      <!-- Page wraper -->
      <div id="page-wrapper" class="gray-bg">

          <!-- Page wrapper -->
          <%= render 'layouts/topnavbar' %>

          <!-- Main view  -->
          <%= yield %>

          <!-- Footer -->
          <%= render 'layouts/footer' %>

      </div>
      <!-- End page wrapper-->
    <% end %>
    <div class="gray-bg">
      <%= yield if controller_name != 'milia/sessions' && action_name == 'new' %>
    </div>
  </div>


来源: stackexchange

问:
Why I'm getting always a new session in SparkJava?
I have a SparkJava api filter that is called by my client every 30 seconds.

```<code>before("/app/*", {
    req, _ ->
    println(req.session().attributes().size)
    println(req.session().id())
    println(req.session().isNew)
    req.session().attribute("test", "test")
})
</code>```

The result is:

```
0
node0r3ulllnarwq5i62o2wcpxmu25
true
0
node0i0morm89ftci1tntiu38p8l5026
true
0
node09n12ooeo0t34wkpaqfhbbou227
true
```

You can see above, the session id is always different.
Why the session is always a new session?

答:
I was stupidly mistaken, but the behavior is correct. REST is stateless and has no session.

There is a good explanation:

If REST applications are supposed to be stateless, how do you manage sessions?

ContentLicense: CC BY-SA 3.0

Body:
I have a SparkJava api filter that is called by my client every 30 seconds.

before("/app/*", {
    req, _ ->
    println(req.session().attributes().size)
    println(req.session().id())
    println(req.session().isNew)
    req.session().attribute("test", "test")
})

The result is:

0
node0r3ulllnarwq5i62o2wcpxmu25
true
0
node0i0morm89ftci1tntiu38p8l5026
true
0
node09n12ooeo0t34wkpaqfhbbou227
true

You can see above, the session id is always different.
Why the session is always a new session?


问:
How to set different Toggle start position in jQuery?
I have a simple jQuery toggle button but I don't want to use toggleSlide. If it is loaded homepage, the div must be opened and have a button to hide.
But if it is loaded another page, div must be closed and have button to show
Here is two code, that doesn't work. I try to add them together in HTML but doesn't work

For homepage:

```<code>$(document).ready(function(){
  $("#flip").click(function(){
    if(window.location.href == 'http://homepage/')
      $("#panel").hide("fast");
  });
});
</code>```

for another page:

```<code>$(document).ready(function(){
  $("#flip").click(function(){
    if(window.location.href != 'http://homepage/')
      $("#panel").show("fast");
  });
});
</code>```

答:
You could try something like this:

```<code>$(document).ready(function(){
   var condition = (window.location.href == 'http://homepage/');
   $("#panel").toggle(condition);
});
</code>```

But comparing strings is usually bad practice, so what I would do is set a bool at the top of the page, and when the homepage is loaded, set it to true. Otherwise, false.

Body:
I have a simple jQuery toggle button but I don't want to use toggleSlide. If it is loaded homepage, the div must be opened and have a button to hide.
But if it is loaded another page, div must be closed and have button to show
Here is two code, that doesn't work. I try to add them together in HTML but doesn't work

For homepage:

$(document).ready(function(){
  $("#flip").click(function(){
    if(window.location.href == 'http://homepage/')
      $("#panel").hide("fast");
  });
});

for another page:

$(document).ready(function(){
  $("#flip").click(function(){
    if(window.location.href != 'http://homepage/')
      $("#panel").show("fast");
  });
});

Body:
You could try something like this:

$(document).ready(function(){
   var condition = (window.location.href == 'http://homepage/');
   $("#panel").toggle(condition);
});

But comparing strings is usually bad practice, so what I would do is set a bool at the top of the page, and when the homepage is loaded, set it to true. Otherwise, false.


问:
Is there a way to use Custom Parameters of an Event as a metric in Facebook Analytics charts?
i am sending parameters with my custom event. I would like to demonstrate them as a metric in the graph charts. Is there a way to do that?

For example, when i send an event with additional parameters of secondValue, thirdValue.

I would like to decide which value to use as a metric without being limited to these three metrics:

答: There's no way to do this currently. Your best bet is to send multiple events (firstEvent, secondEvent, thirdEvent) instead of multiple custom parameters (firstValue, secondValue, thirdValue) and use the valueToSum argument for each event.</p>


问:
Fitting VotingClassifier
I'm learning scikit-learn. I've been trying to optimise a classifier for a particular task where performance is judges by log loss. I'm trying to check if a VotingClassifier() can improve my performance using my two best performing classifiers.

Here's my code:

```<code>estimators = [RandomForestClassifier(random_state=0,n_estimators=500,bootstrap=False,criterion='entropy',
                                             max_depth=None,max_features='auto'),
                      LogisticRegression(solver='lbfgs',C=opt_c)]
        vc = VotingClassifier(estimators=estimators,voting='soft',weights=[1,1])
        vc.fit(X_train_std,y_train.as_matrix())
        vcp = vc.predict_proba(X_valid_std)
        print('Score: {}\tLog Loss: {}'.format(vc.score(X_valid_std,y_valid),log_loss(y_valid,vcp)))
</code>```

However, when I try to run this code, I get the following error:

```<code>    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-123-8cd305ba77b8> in <module>()
----> 1 vc.fit(X_train_std,y_train.as_matrix())

/afs/-omited-/miniconda2/envs/iaml/lib/python2.7/site-packages/sklearn/ensemble/voting_classifier.pyc in fit(self, X, y, sample_weight)
    170                     raise ValueError('Underlying estimator \'%s\' does not'
    171                                      ' support sample weights.' % name)
--> 172         names, clfs = zip(*self.estimators)
    173         self._validate_names(names)
    174

/afs/-ommited-/miniconda2/envs/iaml/lib/python2.7/site-packages/sklearn/ensemble/base.pyc in __iter__(self)
    145     def __iter__(self):
    146         """Returns iterator over estimators in the ensemble."""
--> 147         return iter(self.estimators_)
    148
    149

AttributeError: 'RandomForestClassifier' object has no attribute 'estimators_'
</code>```

Can someone explkain why this is happening?

答: I figured out my mistake, The estimators attribute takes a list of tuples.</p>

Title: Fitting VotingClassifier

Body:
I'm learning scikit-learn. I've been trying to optimise a classifier for a particular task where performance is judges by log loss. I'm trying to check if a VotingClassifier() can improve my performance using my two best performing classifiers.

Here's my code:

estimators = [RandomForestClassifier(random_state=0,n_estimators=500,bootstrap=False,criterion='entropy',
                                             max_depth=None,max_features='auto'),
                      LogisticRegression(solver='lbfgs',C=opt_c)]
        vc = VotingClassifier(estimators=estimators,voting='soft',weights=[1,1])
        vc.fit(X_train_std,y_train.as_matrix())
        vcp = vc.predict_proba(X_valid_std)
        print('Score: {}\tLog Loss: {}'.format(vc.score(X_valid_std,y_valid),log_loss(y_valid,vcp)))

However, when I try to run this code, I get the following error:

    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-123-8cd305ba77b8> in <module>()
----> 1 vc.fit(X_train_std,y_train.as_matrix())

/afs/-omited-/miniconda2/envs/iaml/lib/python2.7/site-packages/sklearn/ensemble/voting_classifier.pyc in fit(self, X, y, sample_weight)
    170                     raise ValueError('Underlying estimator \'%s\' does not'
    171                                      ' support sample weights.' % name)
--> 172         names, clfs = zip(*self.estimators)
    173         self._validate_names(names)
    174

/afs/-ommited-/miniconda2/envs/iaml/lib/python2.7/site-packages/sklearn/ensemble/base.pyc in __iter__(self)
    145     def __iter__(self):
    146         """Returns iterator over estimators in the ensemble."""
--> 147         return iter(self.estimators_)
    148
    149

AttributeError: 'RandomForestClassifier' object has no attribute 'estimators_'

Can someone explkain why this is happening?


问:
SQL - Select *, but add in another column as the nth column?
This is probably a stupid question, but if I select tableA.*, but in the results I want a column from tableB as say the third column slotted in the middle of tableA's columns, is there a way to do this without manually selecting every single column from tableA and rearranging as required? This is in SSMS2016.

答:
Step 1 - type this into ssms.

```<code>select count(*)
from tableA a join tableB b on a.someField = b.someField
</code>```

Step 2 - start editing your select clause.   The intellisense (aka auto complete) in SSMS will reduce the number of characters you actually have to type.

If you type the columns in the order you want them to appear, you won't have to re-arrange them afterwards.

Body:
Step 1 - type this into ssms.

select count(*)
from tableA a join tableB b on a.someField = b.someField

Step 2 - start editing your select clause.   The intellisense (aka auto complete) in SSMS will reduce the number of characters you actually have to type.

If you type the columns in the order you want them to appear, you won't have to re-arrange them afterwards.


问:
Uploaded images cut off
I have a problem with new images. When I'm uploading a new image it looks like this:

Any suggestions how to fix this ?

答: I ran into this problem. Every time I added an image into a page, part would be cropped off.  I tried playing with the settings > media etc, turned off the Smush plugin, changed the image size and dimensions in photoshop. But part of the image still kept getting trimmed off when uploading. Finally, I uploaded the image directly into Media, where it looked fine.  Tried placing it in the page - cut off again.  Copied and pasted the image code into the page and it shows up fine.  I haven't nailed down the issue, but at least this is a workaround if it is only one or two problematic images.</p>

Title: Uploaded images cut off


问:
Black image when editing through PHP
I found a couple of tutorials to edit image in PHP. However it is showing a black image. I couldn't understand what's the problem here.</p>

```<code><?php
  //Set the Content Type
  header('Content-type: image/jpeg');

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('http://iamsaurav.xyz/images/avatar.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'http://iamsaurav.xyz/images/oswald.ttf';

  // Set Text to Be Printed On Image
  $text = "This is a sunset!";

  // Print Text On Image
  imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

  // Send Image to Browser
  imagejpeg($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);
?>
</code>```

答:
If you use the full path to both the image and the font it appears to work fine ~ obviously the paths used here are pertinent to my system so you would need to edit appropriately. The most likely problem is that PHP is looking in the wrong directory for the image.... if the text does not appear then that path is also most likely wrong.</p>

```<code><?php
  //Set the Content Type
  header('Content-type: image/jpeg');

  /* use absolute path */
  $jpg_image = imagecreatefromjpeg('C:/Temp2/src.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'c:/wwwroot/inc/fonts/AMAZON.ttf';

  // Set Text to Be Printed On Image
  $text = "This is a sunset!";

  // Print Text On Image
  imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

  // Send Image to Browser
  imagejpeg($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);
?>
</code>```

Title: Black image when editing through PHP

Body:
I found a couple of tutorials to edit image in PHP. However it is showing a black image. I couldn't understand what's the problem here.

<?php
  //Set the Content Type
  header('Content-type: image/jpeg');

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('http://iamsaurav.xyz/images/avatar.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'http://iamsaurav.xyz/images/oswald.ttf';

  // Set Text to Be Printed On Image
  $text = "This is a sunset!";

  // Print Text On Image
  imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

  // Send Image to Browser
  imagejpeg($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);
?>

Body:
If you use the full path to both the image and the font it appears to work fine ~ obviously the paths used here are pertinent to my system so you would need to edit appropriately. The most likely problem is that PHP is looking in the wrong directory for the image.... if the text does not appear then that path is also most likely wrong.

<?php
  //Set the Content Type
  header('Content-type: image/jpeg');

  /* use absolute path */
  $jpg_image = imagecreatefromjpeg('C:/Temp2/src.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'c:/wwwroot/inc/fonts/AMAZON.ttf';

  // Set Text to Be Printed On Image
  $text = "This is a sunset!";

  // Print Text On Image
  imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

  // Send Image to Browser
  imagejpeg($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);
?>


问:
Error importing Scheduled Task xml with Powershell
I have this code:

```<code>param(
[string]$target_server_name=$ENV:ComputerName,
[string]$task_path,
#[string]$task_user,
#[string]$task_pass,
[string]$drop_folder,
[string]$dest_folder
)

    $creds = Get-Credential
    $task_user = $creds.UserName
    $task_pass = $creds.GetNetworkCredential().Password

    robocopy $drop_folder $dest_folder /MIR
    $service = new-object -ComObject ("Schedule.Service")
    $service.Connect($target_server_name)
    $rootFolder = $service.GetFolder("\")
    Get-Item $task_path | % {
       $task_name = $_.Name.Replace('.xml', '')
       $task_xml = Get-Content $_.FullName
       $task = $service.NewTask(0)
       $task.XmlText = $task_xml
       $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
    }
</code>```

And I am trying to import some task that I exported from the Windows Task Scheduler. But I am having this error:

Can someone please tell me what I am doing wrong,
Thanks.

答:
I also found this way and I think it looks better,

```<code>$taskDefinition.XmlText = $taskxml.OuterXml
</code>```

Take a look on this: enter link description here

Body:
I have this code:

param(
[string]$target_server_name=$ENV:ComputerName,
[string]$task_path,
#[string]$task_user,
#[string]$task_pass,
[string]$drop_folder,
[string]$dest_folder
)

    $creds = Get-Credential
    $task_user = $creds.UserName
    $task_pass = $creds.GetNetworkCredential().Password

    robocopy $drop_folder $dest_folder /MIR
    $service = new-object -ComObject ("Schedule.Service")
    $service.Connect($target_server_name)
    $rootFolder = $service.GetFolder("\")
    Get-Item $task_path | % {
       $task_name = $_.Name.Replace('.xml', '')
       $task_xml = Get-Content $_.FullName
       $task = $service.NewTask(0)
       $task.XmlText = $task_xml
       $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
    }

And I am trying to import some task that I exported from the Windows Task Scheduler. But I am having this error:

Can someone please tell me what I am doing wrong,
Thanks.

Body:
I also found this way and I think it looks better,

$taskDefinition.XmlText = $taskxml.OuterXml

Take a look on this: enter link description here


问:
Java regex for a specific phone number format
I am looking for a regex java pattern to match the following string:

```<code> [Phone Number]= 1234567890
</code>```

Here:
 The regex should look for hardcoded string of "[Phone Number]=" followed by space or not, and followed by
 any numbers of digits.

That means it should match:

```<code>[Phone Number]= 123456 and
[Phone Number]=1234567890
</code>```

Any help is appreciated.

答:
Well, something like:

```<code>String pattern = "\\[Phone Number\\]= ?\\d+";
</code>```

The backslashes are doubled just because of Java string literal syntax

The square brackets are escaped to avoid them being used to group a set of characters

The ? means zero or one space

The \d+ (after unescaping) means "at least one digit"

ContentLicense: CC BY-SA 2.5

Body:
I am looking for a regex java pattern to match the following string:

 [Phone Number]= 1234567890

Here:
 The regex should look for hardcoded string of "[Phone Number]=" followed by space or not, and followed by
 any numbers of digits.

That means it should match:

[Phone Number]= 123456 and
[Phone Number]=1234567890

Any help is appreciated.

Body:
Well, something like:

String pattern = "\\[Phone Number\\]= ?\\d+";

The backslashes are doubled just because of Java string literal syntax

The square brackets are escaped to avoid them being used to group a set of characters

The ? means zero or one space

The \d+ (after unescaping) means "at least one digit"


问:
AngularJS Sortable order pricing issue
I'm facing an issue when ordering prices formatted as currency.

var myApp = angular.module("myApp", []);

myApp.factory("Purchases", function() {
  var Purchases = {};

  Purchases.data = [{
      date: "10/05/2012",
      text: "1 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£90",
      availability: "1 Available until 10th Dec 2013"
    },
    {
      date: "24/05/2012",
      text: "2 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£9.5",
      availability: "2 Available until 10th Dec 2013"
    },
    {
      date: "20/05/2012",
      text: "3 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£10",
      availability: "3 Available until 10th Dec 2013"
    }
  ];
  return Purchases;
});

function PurchasesCtrl($scope, Purchases) {
  $scope.purchases = Purchases;
  $scope.sort = {
    column: '',
    descending: false
  };
  $scope.changeSorting = function(column) {

    var sort = $scope.sort;

    if (sort.column == column) {
      sort.descending = !sort.descending;
    } else {
      sort.column = column;
      sort.descending = false;
    }
  };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="PurchasesCtrl">
    <h2>Purchases:</h2>
    <table cellspacing="0">
      <tr class="first">
        <th class="first" ng-click="changeSorting('date')">Date</th>
        <th ng-click="changeSorting('text')">Description</th>
        <th ng-click="changeSorting('price')">Amount</th>
        <th ng-click="changeSorting('availability')">Status</th>
      </tr>
      <tr ng-repeat="purchase in purchases.data|orderBy:sort.column:sort.descending">
        <td class="first">{{purchase.date}}</td>
        <td>{{purchase.text}}</td>
        <td>{{purchase.price}}</td>
        <td>{{purchase.availability}}</td>
      </tr>
    </table>
  </div>
</div></code>```

The issue order: $9.5 > $10

Is there any way to correct the ordering?

答:
Yes, check this fiddle: http://jsfiddle.net/2u3wn91z/1/ .
You want to compare numbers, not strings, so you need to separate currency (as first letter of price) and then remove currency from price):

```<code>  Purchases.data = Purchases.data.map(function (purchase) {
    purchase.currency = purchase.price.charAt(0);
    purchase.price = Number(purchase.price.substr(1));
    return purchase;
  });
   $scope.purchases = Purchases;
</code>```

When you have price separated from currency, you can display it separately:

```<code><td>{{purchase.currency}}{{purchase.price}}</td>
</code>```

Title: AngularJS Sortable order pricing issue

Body:
I'm facing an issue when ordering prices formatted as currency.

var myApp = angular.module("myApp", []);

myApp.factory("Purchases", function() {
  var Purchases = {};

  Purchases.data = [{
      date: "10/05/2012",
      text: "1 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£90",
      availability: "1 Available until 10th Dec 2013"
    },
    {
      date: "24/05/2012",
      text: "2 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£9.5",
      availability: "2 Available until 10th Dec 2013"
    },
    {
      date: "20/05/2012",
      text: "3 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£10",
      availability: "3 Available until 10th Dec 2013"
    }
  ];
  return Purchases;
});

function PurchasesCtrl($scope, Purchases) {
  $scope.purchases = Purchases;
  $scope.sort = {
    column: '',
    descending: false
  };
  $scope.changeSorting = function(column) {

    var sort = $scope.sort;

    if (sort.column == column) {
      sort.descending = !sort.descending;
    } else {
      sort.column = column;
      sort.descending = false;
    }
  };
}

Purchases:

        Date
        Description
        Amount
        Status

        {{purchase.date}}
        {{purchase.text}}
        {{purchase.price}}
        {{purchase.availability}}

The issue order: $9.5 > $10

Is there any way to correct the ordering?

Body:
Yes, check this fiddle: http://jsfiddle.net/2u3wn91z/1/ .
You want to compare numbers, not strings, so you need to separate currency (as first letter of price) and then remove currency from price):

  Purchases.data = Purchases.data.map(function (purchase) {
    purchase.currency = purchase.price.charAt(0);
    purchase.price = Number(purchase.price.substr(1));
    return purchase;
  });
   $scope.purchases = Purchases;

When you have price separated from currency, you can display it separately:

<td>{{purchase.currency}}{{purchase.price}}</td>


问:
Calculate the day tomorrow and if it is Sunday show two more days - Mysql
I'm trying to make a query where one of the fields shows the units of the orders table that are planned tomorrow, but if tomorrow is Sunday it should be Monday.

I have the table orders and the table format.

Orders table:
id_order, order_date, units

Format table:
id_format, format_type

My query initially is this:

```<code>SELECT format_type, units, DATE (NOW () + INTERVAL 1 DAY) as Tomorrow
FROM orders Join format on orders.id_format = format.id_format
WHERE DATE (date_delivery) = DATE (NOW () + INTERVAL 1 DAY)
</code>```

But it would have to be something similar like this:

```<code>SELECT format_type, units, DATE (NOW () + INTERVAL 1 DAY) as Tomorrow
FROM orders Join format on orders.id_format = format.id_format
WHERE (
  CASE
  WHEN DAYNAME (date) = "Sunday" THEN DATE (order_date) = DATE (NOW () + INTERVAL 2 DAY)
  ELSE DATE (order_date) = DATE (NOW () + INTERVAL 1 DAY)
  END;
</code>```

_____EDIT_____

This is the result I wanted

```<code>SELECT format.format_type, units, DATE(NOW()) as TODAY
FROM orders Join format on orders.id_format = format.id_formatopeso
WHERE
  CASE
    WHEN WEEKDAY(now()) = 6 then DATE(order_date) = DATE(NOW() + INTERVAL 2 DAY)
    ELSE DATE(order_date) = DATE(NOW() + INTERVAL 1 DAY)
END;
</code>```

答:
Yuu can simply select what you have in where </p>

```<code>  SELECT format_type, units,
      CASE
        WHEN  WEEKDAY(date) = 6
            then DATE_ADD(curdate(), INTERVAL +2  DAY)
            else DATE_ADD(curdate(), INTERVAL +1  DAY)
        END as tomorrow_with_sunday_check,
      DATE_ADD(curdate(), INTERVAL +1  DAY) as Tomorrow
  FROM orders Join format on orders.id_format = format.id_format
</code>```

Body:
I'm trying to make a query where one of the fields shows the units of the orders table that are planned tomorrow, but if tomorrow is Sunday it should be Monday.

I have the table orders and the table format.

Orders table:
id_order, order_date, units

Format table:
id_format, format_type

My query initially is this:

SELECT format_type, units, DATE (NOW () + INTERVAL 1 DAY) as Tomorrow
FROM orders Join format on orders.id_format = format.id_format
WHERE DATE (date_delivery) = DATE (NOW () + INTERVAL 1 DAY)

But it would have to be something similar like this:

SELECT format_type, units, DATE (NOW () + INTERVAL 1 DAY) as Tomorrow
FROM orders Join format on orders.id_format = format.id_format
WHERE (
  CASE
  WHEN DAYNAME (date) = "Sunday" THEN DATE (order_date) = DATE (NOW () + INTERVAL 2 DAY)
  ELSE DATE (order_date) = DATE (NOW () + INTERVAL 1 DAY)
  END;

_____EDIT_____

This is the result I wanted

SELECT format.format_type, units, DATE(NOW()) as TODAY
FROM orders Join format on orders.id_format = format.id_formatopeso
WHERE
  CASE
    WHEN WEEKDAY(now()) = 6 then DATE(order_date) = DATE(NOW() + INTERVAL 2 DAY)
    ELSE DATE(order_date) = DATE(NOW() + INTERVAL 1 DAY)
END;

Body:
Yuu can simply select what you have in where

  SELECT format_type, units,
      CASE
        WHEN  WEEKDAY(date) = 6
            then DATE_ADD(curdate(), INTERVAL +2  DAY)
            else DATE_ADD(curdate(), INTERVAL +1  DAY)
        END as tomorrow_with_sunday_check,
      DATE_ADD(curdate(), INTERVAL +1  DAY) as Tomorrow
  FROM orders Join format on orders.id_format = format.id_format


问:
Sort and return dict by specific list value
I found this: Sort keys in dictionary by value in a list in Python

and it is almost what I want.  I want to sort exactly as is defined in the above post, i.e., by a specific item in the value list, but I want to return the entire original dictionary sorted by the specified list entry, not a list of the keys.

My last try has failed:

```<code>details = {'India': ['New Dehli', 'A'],
           'America': ['Washington DC', 'B'],
           'Japan': ['Tokyo', 'C']
           }

print('Country-Capital List...')
print(details)
print()
temp1 = sorted(details.items(), key=lambda value: details[value][1])
print(temp1)
</code>```

The error:

```<code>{'India': ['New Dehli', 'A'], 'America': ['Washington DC', 'B'], 'Japan': ['Tokyo', 'C']}

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 11, in <module>

    temp1 = sorted(details.items(), key=lambda value: details[value][1])
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 11, in <lambda>
    temp1 = sorted(details.items(), key=lambda value: details[value][1])
TypeError: unhashable type: 'list'
</code>```

答:
You are trying to use the (key, value) pair from the dict.items() sequence as a key. Because value is a list, this fails, as keys must be hashable and lists are not.

Just use the value directly:

```<code>temp1 = sorted(details.items(), key=lambda item: item[1][1])
</code>```

I renamed the lambda argument to item to make it clearer what is being passed in. item[1] is the value from the (key, value) pair, and item[1][1] is the second entry in each list.

Demo:

```<code>>>> details = {'India': ['New Dehli', 'A'],
...            'America': ['Washington DC', 'B'],
...            'Japan': ['Tokyo', 'C']
...            }
>>> sorted(details.items(), key=lambda item: item[1][1])
[('India', ['New Dehli', 'A']), ('America', ['Washington DC', 'B']), ('Japan', ['Tokyo', 'C'])]
</code>```

Body:
I found this: Sort keys in dictionary by value in a list in Python

and it is almost what I want.  I want to sort exactly as is defined in the above post, i.e., by a specific item in the value list, but I want to return the entire original dictionary sorted by the specified list entry, not a list of the keys.

My last try has failed:

details = {'India': ['New Dehli', 'A'],
           'America': ['Washington DC', 'B'],
           'Japan': ['Tokyo', 'C']
           }

print('Country-Capital List...')
print(details)
print()
temp1 = sorted(details.items(), key=lambda value: details[value][1])
print(temp1)

The error:

{'India': ['New Dehli', 'A'], 'America': ['Washington DC', 'B'], 'Japan': ['Tokyo', 'C']}

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 11, in <module>

    temp1 = sorted(details.items(), key=lambda value: details[value][1])
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 11, in <lambda>
    temp1 = sorted(details.items(), key=lambda value: details[value][1])
TypeError: unhashable type: 'list'

Body:
You are trying to use the (key, value) pair from the dict.items() sequence as a key. Because value is a list, this fails, as keys must be hashable and lists are not.

Just use the value directly:

temp1 = sorted(details.items(), key=lambda item: item[1][1])

I renamed the lambda argument to item to make it clearer what is being passed in. item[1] is the value from the (key, value) pair, and item[1][1] is the second entry in each list.

Demo:

>>> details = {'India': ['New Dehli', 'A'],
...            'America': ['Washington DC', 'B'],
...            'Japan': ['Tokyo', 'C']
...            }
>>> sorted(details.items(), key=lambda item: item[1][1])
[('India', ['New Dehli', 'A']), ('America', ['Washington DC', 'B']), ('Japan', ['Tokyo', 'C'])]


问:
Using Aspectj compile time weaving and Java compile time annotation processing in one project
I have searched far and wide and have not found anything that would help me resolve my problem. I am trying to implement a certain functionality and I am creating a PoC solution, here is the issue though:

it involves using both compile time weaved AspectJ and compile time annotation processors

and I have no idea how to make both of those work at the same time.

So far I have been using just AspectJ aspects in *.aj files with the aspectj-maven-plugin, and it was working fine. As soon as I tried adding annotation processing with a maven-compiler-plugin though, an issue became aparent: the weaved classes in the target directory generated in the compilation phase by the aspectj-maven-plugin were overwritten by the maven-compiler-plugin by the classes it generated during it's compilation phase.

The console output says that first the aspectj-maven-plugin does it's work and weaves all the classes:

```<code>[INFO] --- aspectj-maven-plugin:1.10:compile (default) @ demo ---
[INFO] Showing AJC message detail for messages of types: [error, warning, fail]
...and a list of all the Join Points and Intertypes done
</code>```

But then the maven-compiler-plugin goes to work and recompiles everything (and generates classes with the annotation processor):

```<code>[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ demo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to dir\demo\target\classes
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (compile-project) @ demo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 19 source files to dir\demo\target\classes
</code>```

Here is the relevant part of the pom.xml:

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
    <source>${maven.compiler.source}</source>
    <target>${maven.compiler.target}</target>
</configuration>
<executions>
    <execution>
        <id>default-compile</id>
        <configuration>
            <compilerArgument>-proc:none</compilerArgument>
            <includes>
                <include>
                    path/to/annotation/processor/Processor.java
                </include>
            </includes>
        </configuration>
    </execution>
    <execution>
        <id>compile-project</id>
        <phase>compile</phase>
        <goals>
            <goal>compile</goal>
        </goals>
    </execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.10</version>
<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjtools</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
</dependencies>
<configuration>
    <showWeaveInfo>true</showWeaveInfo>
    <complianceLevel>${maven.compiler.source}</complianceLevel>
    <source>${maven.compiler.source}</source>
    <target>${maven.compiler.target}</target>
</configuration>
<executions>
    <execution>
        <phase>process-sources</phase>
        <goals>
            <goal>compile</goal>
            <goal>test-compile</goal>
        </goals>
    </execution>
</executions>
</plugin>
</code>```

Separately, both the aspects and the annotation processors work fine, so they specifically aren't the problem, I assume the issue is the build configuration.

I'm guessing that either I am messing something up with the executions/phases in the plugins, or maybe I don't even need to use both of them, maybe just one properly conifgured would be enough, but I have no idea how to combine compilation with ajc and running the annotation processor (and in two phases, first with proc none to compile the Annotation Processor itself and then to do the annotation processing). Please help!

答:
For me the best strategy so far was to disable the Java compiler altogether when using the AspectJ compiler, and let the AspectJ compiler do the annotation processing and the compilation alone. An example maven build configuration would look like this:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <skipMain>true</skipMain>
                <skip>true</skip>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

If that doesn't work for you for some reason, you could try using the Java compiler for annotation processing only and let the AspectJ compiler do the rest.

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <proc>only</proc>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <configuration>
                <proc>none</proc>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

I also see you've got too many executions defined in your build file (2 for the java compiler: default-compile + compile-project), with non-default execution IDs. I suggest you leave only the default executions with their default ID, unless you have a specific reason for having them.

Body:
I have searched far and wide and have not found anything that would help me resolve my problem. I am trying to implement a certain functionality and I am creating a PoC solution, here is the issue though:

it involves using both compile time weaved AspectJ and compile time annotation processors

and I have no idea how to make both of those work at the same time.

So far I have been using just AspectJ aspects in *.aj files with the aspectj-maven-plugin, and it was working fine. As soon as I tried adding annotation processing with a maven-compiler-plugin though, an issue became aparent: the weaved classes in the target directory generated in the compilation phase by the aspectj-maven-plugin were overwritten by the maven-compiler-plugin by the classes it generated during it's compilation phase.

The console output says that first the aspectj-maven-plugin does it's work and weaves all the classes:

[INFO] --- aspectj-maven-plugin:1.10:compile (default) @ demo ---
[INFO] Showing AJC message detail for messages of types: [error, warning, fail]
...and a list of all the Join Points and Intertypes done

But then the maven-compiler-plugin goes to work and recompiles everything (and generates classes with the annotation processor):

[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ demo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to dir\demo\target\classes
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (compile-project) @ demo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 19 source files to dir\demo\target\classes

Here is the relevant part of the pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
    <source>${maven.compiler.source}</source>
    <target>${maven.compiler.target}</target>
</configuration>
<executions>
    <execution>
        <id>default-compile</id>
        <configuration>
            <compilerArgument>-proc:none</compilerArgument>
            <includes>
                <include>
                    path/to/annotation/processor/Processor.java
                </include>
            </includes>
        </configuration>
    </execution>
    <execution>
        <id>compile-project</id>
        <phase>compile</phase>
        <goals>
            <goal>compile</goal>
        </goals>
    </execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.10</version>
<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjtools</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
</dependencies>
<configuration>
    <showWeaveInfo>true</showWeaveInfo>
    <complianceLevel>${maven.compiler.source}</complianceLevel>
    <source>${maven.compiler.source}</source>
    <target>${maven.compiler.target}</target>
</configuration>
<executions>
    <execution>
        <phase>process-sources</phase>
        <goals>
            <goal>compile</goal>
            <goal>test-compile</goal>
        </goals>
    </execution>
</executions>
</plugin>

Separately, both the aspects and the annotation processors work fine, so they specifically aren't the problem, I assume the issue is the build configuration.

I'm guessing that either I am messing something up with the executions/phases in the plugins, or maybe I don't even need to use both of them, maybe just one properly conifgured would be enough, but I have no idea how to combine compilation with ajc and running the annotation processor (and in two phases, first with proc none to compile the Annotation Processor itself and then to do the annotation processing). Please help!

Body:
For me the best strategy so far was to disable the Java compiler altogether when using the AspectJ compiler, and let the AspectJ compiler do the annotation processing and the compilation alone. An example maven build configuration would look like this:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <skipMain>true</skipMain>
                <skip>true</skip>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

If that doesn't work for you for some reason, you could try using the Java compiler for annotation processing only and let the AspectJ compiler do the rest.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <proc>only</proc>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <configuration>
                <proc>none</proc>
            </configuration>
        </plugin>
    </plugins>
</build>

I also see you've got too many executions defined in your build file (2 for the java compiler: default-compile + compile-project), with non-default execution IDs. I suggest you leave only the default executions with their default ID, unless you have a specific reason for having them.


问:
AttributeError: 'function' object has no attribute
I've been trying to make a game, but this one error keeps appearing. I'm a beginner in python so I hope you guys can even look at this horrendous code.

```<code>AttributeError: 'function' object has no attribute 'armorEquipped'
</code>```

I'm very confused on what this means but could someone explain it to me?

```<code>normalarmor={
"TRAINING ARMOR":["Armor meant for training","no element", +10, " health"]}

firearmor={
    "LIGHTBRINGER":["Armor that brings light", "Fire element", +10, " health, Grass type deals less damage"]}

def equipArmor():
    print()
    m= True
    while m==True:
        z=True
        armorInInventory= len(normalarmor) + len(firearmor) +len(airarmor) +len(grassarmor)+len (waterarmor)
        armorInInventory=int(armorInInventory)
        print ("You have", armorInInventory, "armors")
        print ("You have these armors:")
        for name6 in airarmor:
            print(name6)
        for name2 in normalarmor:
            print(name2)
        for name3 in firearmor:
            print (name3)
        for name7 in grassarmor:
            print (name7)
        for name9 in waterarmor:
            print (name9)
        print ("Which armor would you like to equip or view")
        equipArmor.armorEquipped=input()
        equipArmor.armorEquipped= equipArmor.armorEquipped.upper()
        if (equipArmor.armorEquipped in normalarmor or
            equipArmor.armorEquipped in waterarmor or
            equipArmor.armorEquipped in firearmor or
            equipArmor.armorEquipped in airarmor or
            equipArmor.armorEquipped in grassarmor):
            if equipArmor.armorEquipped in normalarmor:
                print (normalarmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1=variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        m= False
                        z= False
                    elif variable1 == "NO":
                        z= False

                        m=True
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in firearmor:
                print (firearmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1 =variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        m= False
                        z= False
                    elif variable1 == "NO":
                        z= True
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in airarmor:
                print (airarmor[armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1=variable1.upper()
                    if variable1== "YES":
                        print (armorEquipped, "Equipped")
                        z= False
                        m=False
                    elif variable1 == "NO":
                        z= False
                        m=True
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in grassarmor:
                print (grassarmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1= variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        x= False
                    elif variable1 == "NO":
                        m=True
                        z= False
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in waterarmor:
                print (waterarmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1= variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        x= False
                    elif variable1 == "NO":
                        m=True
                        z= False
                    else:
                        print ("That is not a valid answer")
                        z=True
</code>```

and it messes up around here:

```<code>def tutorial():
    x=True
    uhealth= normalarmor[equipArmor.armorEquipped][2]+uhealth
</code>```

Why is this problem appearing and what is this problem?
Please help me !

答:
@TheGamerCow I've got a 24" screen but your code ran off it.

I've replaced it like this:

```<code> if (equipArmor.armorEquipped in normalarmor or
        equipArmor.armorEquipped in waterarmor or
        equipArmor.armorEquipped in firearmor or
        equipArmor.armorEquipped in airarmor or
        equipArmor.armorEquipped in grassarmor):
</code>```

Check for styling at: multiline conditions

Body:
I've been trying to make a game, but this one error keeps appearing. I'm a beginner in python so I hope you guys can even look at this horrendous code.

AttributeError: 'function' object has no attribute 'armorEquipped'

I'm very confused on what this means but could someone explain it to me?

normalarmor={
"TRAINING ARMOR":["Armor meant for training","no element", +10, " health"]}

firearmor={
    "LIGHTBRINGER":["Armor that brings light", "Fire element", +10, " health, Grass type deals less damage"]}

def equipArmor():
    print()
    m= True
    while m==True:
        z=True
        armorInInventory= len(normalarmor) + len(firearmor) +len(airarmor) +len(grassarmor)+len (waterarmor)
        armorInInventory=int(armorInInventory)
        print ("You have", armorInInventory, "armors")
        print ("You have these armors:")
        for name6 in airarmor:
            print(name6)
        for name2 in normalarmor:
            print(name2)
        for name3 in firearmor:
            print (name3)
        for name7 in grassarmor:
            print (name7)
        for name9 in waterarmor:
            print (name9)
        print ("Which armor would you like to equip or view")
        equipArmor.armorEquipped=input()
        equipArmor.armorEquipped= equipArmor.armorEquipped.upper()
        if (equipArmor.armorEquipped in normalarmor or
            equipArmor.armorEquipped in waterarmor or
            equipArmor.armorEquipped in firearmor or
            equipArmor.armorEquipped in airarmor or
            equipArmor.armorEquipped in grassarmor):
            if equipArmor.armorEquipped in normalarmor:
                print (normalarmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1=variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        m= False
                        z= False
                    elif variable1 == "NO":
                        z= False

                        m=True
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in firearmor:
                print (firearmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1 =variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        m= False
                        z= False
                    elif variable1 == "NO":
                        z= True
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in airarmor:
                print (airarmor[armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1=variable1.upper()
                    if variable1== "YES":
                        print (armorEquipped, "Equipped")
                        z= False
                        m=False
                    elif variable1 == "NO":
                        z= False
                        m=True
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in grassarmor:
                print (grassarmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1= variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        x= False
                    elif variable1 == "NO":
                        m=True
                        z= False
                    else:
                        print ("That is not a valid answer")
                        z=True
            if equipArmor.armorEquipped in waterarmor:
                print (waterarmor[equipArmor.armorEquipped])
                while z== True:
                    print ("Equip? Yes or No")
                    variable1= input()
                    variable1= variable1.upper()
                    if variable1== "YES":
                        print (equipArmor.armorEquipped, "Equipped")
                        x= False
                    elif variable1 == "NO":
                        m=True
                        z= False
                    else:
                        print ("That is not a valid answer")
                        z=True

and it messes up around here:

def tutorial():
    x=True
    uhealth= normalarmor[equipArmor.armorEquipped][2]+uhealth

Why is this problem appearing and what is this problem?
Please help me !

Body:
@TheGamerCow I've got a 24" screen but your code ran off it.

I've replaced it like this:

 if (equipArmor.armorEquipped in normalarmor or
        equipArmor.armorEquipped in waterarmor or
        equipArmor.armorEquipped in firearmor or
        equipArmor.armorEquipped in airarmor or
        equipArmor.armorEquipped in grassarmor):

Check for styling at: multiline conditions


问:
Aligning an image next to a table row
I want to display image next to each row in a table using Html and CSS.
Something like this image:

Images will be placed at the red cross position: on right side of each row and not created within extra column.

What would be the best way to do that.

答:
You could try using the :last-child combined with the :after pseudo.

tr td:last-child::after {
  content: '';
  display: inline-block;
  position: absolute;
  height: 1em;
  width: 1em;
  background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <th>1</th>
    <th>2</th>
  </thead>
  <tb>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tb>
</table></code>```

Title: Aligning an image next to a table row

Body:
You could try using the :last-child combined with the :after pseudo.

tr td:last-child::after {
  content: '';
  display: inline-block;
  position: absolute;
  height: 1em;
  width: 1em;
  background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat center;
}

<table>
  <thead>
    <th>1</th>
    <th>2</th>
  </thead>
  <tb>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tb>
</table>


问:
ngForm (submit) is not working in Angular 2

import { Component, OnInit } from '@angular/core'
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Router, ParamMap } from '@angular/router';
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';

import { CustomerService } from '../services/customer.service';
import { ICustomer } from '../model/customer.model';

@Component({
    templateUrl: './create.customer.component.html'

})

export class CreateCustomerComponent {
    customer: ICustomer;
    errorMessage: string;
    constructor(
        private customerService: CustomerService,
        private route: ActivatedRoute,
        private routeNavigate: Router,
        private location: Location) {
    }

    create(): void {
        this.customerService.createCustomer(this.customer)
            .subscribe(res => {
                if (res) {
                    this.routeNavigate.navigate(['/customers']);
                }
            },
            error => {
                var results = error['_body'];
                this.errorMessage = error.statusText + ' ' + error.text;
                console.log(this.errorMessage);
            });
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<admin-menu></admin-menu>
<hr />

<div>
    <header class="page-header">
        <h4 class="col-sm-8 clearfix">Add Customer </h4>
        <b>
            Go to All Customers
        </b>
    </header>
</div>
<div class="row">
    <div class="panel-heading" *ngIf="errorMessage">
        <div class="has-error">{{errorMessage}}</div>
    </div>

    <div class="col-sm-8 col-md-8 col-md-offset-3 col-sm-offset-1">
        <form (ngSubmit)="create()" class="form_margin" #custCreateForm="ngForm">
            <div class="form-group row hidden">
                <div class="col-sm-4 col-md-3">
                    <label for="customerId">Customer ID :</label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           id="customerId"
                           type="text"
                           name="customerId"
                           [(ngModel)]="customer.Id"
                           #customerIdVar="ngModel" />
                    <span class="help-block" *ngIf="(customerIdVar.touched ||
                                                         customerIdVar.dirty) &&
                                                         customerIdVar.errors">
                        <span *ngIf="customerIdVar.errors.required">
                            Customer ID is required.
                        </span>
                    </span>
                </div>
            </div>
            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="firstName">FirstName : </label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           id="firstName"
                           placeholder="FirstName"
                           required
                           name="firstName"
                           [(ngModel)]="customer.FirstName"
                           #firstNameVar="ngModel" />
                    <span class="help-block" *ngIf="(firstNameVar.touched ||
                                                         firstNameVar.dirty) &&
                                                         firstNameVar.errors">
                        <span *ngIf="firstNameVar.errors.required">
                            FirstName is required.
                        </span>
                    </span>
                </div>
            </div>
            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="lastName">LastName :</label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           id="lastName"
                           placeholder="LastName"
                           required
                           name="lastName"
                           [(ngModel)]="customer.LastName"
                           #lastNameVar="ngModel" />
                    <span class="help-block" *ngIf="(lastNameVar.touched ||
                                                         lastNameVar.dirty) &&
                                                         lastNameVar.errors">
                        <span *ngIf="lastNameVar.errors.required">
                            LastName is required.
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="email">Email : </label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           id="email"
                           type="text"
                           placeholder="Email"
                           required
                           name="email"
                           [(ngModel)]="customer.Email"
                           #emailVar="ngModel" />
                    <span class="help-block" *ngIf="(emailVar.touched ||
                                                         emailVar.dirty) &&
                                                         emailVar.errors">
                        <span *ngIf="emailVar.errors.required">
                            Email is required.
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="DOB">Date of Birth : </label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           id="DOB"
                           type="email"
                           placeholder="Email"
                           required
                           name="DOB"
                           [(ngModel)]="customer.DOB"
                           #dobVar="ngModel" />
                    <span class="help-block" *ngIf="(dobVar.touched ||
                                                         dobVar.dirty) &&
                                                         dobVar.errors">
                        <span *ngIf="dobVar.errors.required">
                            Email is required.
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="address">Adress: </label>
                </div>
                <div class="col-sm-8 col-md-8">

                    <textarea class="form-control"
                              rows="4" cols="50"
                              form="usrform"
                              id="address"
                              placeholder="Address"
                              required
                              name="address"
                              [(ngModel)]="customer.Address"
                              #addressVar="ngModel"></textarea>

                    <!--<input class="form-control"
                           type="text"
                           id="address"
                           placeholder="Address"
                           required
                           name="address"
                           [(ngModel)]="customer.Address"
                           #addressVar="ngModel" />-->
                    <span class="help-block" *ngIf="(addressVar.touched ||
                                                         addressVar.dirty) &&
                                                         addressVar.errors">
                        <span *ngIf="addressVar.errors.required">
                            Address is required.
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="contactNo">Contact No: </label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           type="tel"
                           id="contactNo"
                           placeholder="Mobile number"
                           required
                           name="contactNo"
                           [(ngModel)]="customer.Address"
                           #contactNoVar="ngModel" />
                    <span class="help-block" *ngIf="(contactNoVar.touched ||
                                                         contactNoVar.dirty) &&
                                                         contactNoVar.errors">
                        <span *ngIf="contactNoVar.errors.required">
                            Mobile Number is required.
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="emergencyContactNo">Emergency Contact No: </label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           type="tel"
                           id="emergencyContactNo"
                           placeholder="Mobile number"
                           required
                           name="emergencyContactNo"
                           [(ngModel)]="customer.Address"
                           #emergencyContactNoVar="ngModel" />
                    <span class="help-block" *ngIf="(emergencyContactNoVar.touched ||
                                                         emergencyContactNoVar.dirty) &&
                                                         emergencyContactNoVar.errors">
                        <span *ngIf="emergencyContactNoVar.errors.required">
                            Emergency Contact number is required.
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col-sm-4 col-md-3">
                    <label for="isActive">Is Active_Member: </label>
                </div>
                <div class="col-sm-4 col-md-4">
                    <input class="form-control"
                           type="checkbox"
                           id="isActive"
                           disabled
                           name="isActive"
                           (ngModel)="customer.IsActive_Member"
                           #isActiveVar="ngModel" />
                </div>
            </div>

            <div class="form-group row hidden">
                <div class="col-sm-4 col-md-3">
                    <label for="isDeleted">Is Deleted: </label>
                </div>
                <div class="col-sm-8 col-md-8">
                    <input class="form-control"
                           type="text"
                           id="isDeleted"
                           disabled
                           name="isDeleted"
                           [(ngModel)]="customer.IsActive_Member"
                           #isDeletedVar="ngModel" />
                </div>
            </div>

        </form>
        <div class="row">

            <button class="btn btn-primary"
                    type="submit"
                    style="width:80px;margin-right:10px"
                    [disabled]="!custCreateForm.valid">
                Save
            </button>
        </div>
    </div>
</div></code>```

On submit button URL redirect to login page with NgForm Content in querystring format .

I am not sure what mistake I am doing here. see the image

I not finding the exact reason why its redirecting, rather than hitting Submit method or showing error in console log

On Submit click form is not hitting the debugger and full page get refreshed

答:
you need to provide the form id in the when submitting a form..</p>

```<code><form (ngSubmit)="create(custCreateForm)" class="form_margin" #custCreateForm="ngForm">
</code>```

Body:
import { Component, OnInit } from '@angular/core'
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Router, ParamMap } from '@angular/router';
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';

import { CustomerService } from '../services/customer.service';
import { ICustomer } from '../model/customer.model';

@Component({
    templateUrl: './create.customer.component.html'

})

export class CreateCustomerComponent {
    customer: ICustomer;
    errorMessage: string;
    constructor(
        private customerService: CustomerService,
        private route: ActivatedRoute,
        private routeNavigate: Router,
        private location: Location) {
    }

    create(): void {
        this.customerService.createCustomer(this.customer)
            .subscribe(res => {
                if (res) {
                    this.routeNavigate.navigate(['/customers']);
                }
            },
            error => {
                var results = error['_body'];
                this.errorMessage = error.statusText + ' ' + error.text;
                console.log(this.errorMessage);
            });
    }
}

<admin-menu></admin-menu>

Add Customer

            Go to All Customers

{{errorMessage}}

        <form (ngSubmit)="create()" class="form_margin" #custCreateForm="ngForm">

                    Customer ID :

                    <input class="form-control"
                           id="customerId"
                           type="text"
                           name="customerId"
                           [(ngModel)]="customer.Id"
                           #customerIdVar="ngModel" />

                            Customer ID is required.

                    FirstName :

                    <input class="form-control"
                           id="firstName"
                           placeholder="FirstName"
                           required
                           name="firstName"
                           [(ngModel)]="customer.FirstName"
                           #firstNameVar="ngModel" />

                            FirstName is required.

                    LastName :

                    <input class="form-control"
                           id="lastName"
                           placeholder="LastName"
                           required
                           name="lastName"
                           [(ngModel)]="customer.LastName"
                           #lastNameVar="ngModel" />

                            LastName is required.

                    Email :

                    <input class="form-control"
                           id="email"
                           type="text"
                           placeholder="Email"
                           required
                           name="email"
                           [(ngModel)]="customer.Email"
                           #emailVar="ngModel" />

                            Email is required.

                    Date of Birth :

                    <input class="form-control"
                           id="DOB"
                           type="email"
                           placeholder="Email"
                           required
                           name="DOB"
                           [(ngModel)]="customer.DOB"
                           #dobVar="ngModel" />

                            Email is required.

                    Adress:

                    <textarea class="form-control"
                              rows="4" cols="50"
                              form="usrform"
                              id="address"
                              placeholder="Address"
                              required
                              name="address"
                              [(ngModel)]="customer.Address"
                              #addressVar="ngModel"></textarea>

                            Address is required.

                    Contact No:

                    <input class="form-control"
                           type="tel"
                           id="contactNo"
                           placeholder="Mobile number"
                           required
                           name="contactNo"
                           [(ngModel)]="customer.Address"
                           #contactNoVar="ngModel" />

                            Mobile Number is required.

                    Emergency Contact No:

                    <input class="form-control"
                           type="tel"
                           id="emergencyContactNo"
                           placeholder="Mobile number"
                           required
                           name="emergencyContactNo"
                           [(ngModel)]="customer.Address"
                           #emergencyContactNoVar="ngModel" />

                            Emergency Contact number is required.

                    Is Active_Member:

                    <input class="form-control"
                           type="checkbox"
                           id="isActive"
                           disabled
                           name="isActive"
                           (ngModel)="customer.IsActive_Member"
                           #isActiveVar="ngModel" />

                    Is Deleted:

                    <input class="form-control"
                           type="text"
                           id="isDeleted"
                           disabled
                           name="isDeleted"
                           [(ngModel)]="customer.IsActive_Member"
                           #isDeletedVar="ngModel" />

        </form>

            <button class="btn btn-primary"
                    type="submit"
                    style="width:80px;margin-right:10px"
                    [disabled]="!custCreateForm.valid">
                Save
            </button>

On submit button URL redirect to login page with NgForm Content in querystring format .

I am not sure what mistake I am doing here. see the image

I not finding the exact reason why its redirecting, rather than hitting Submit method or showing error in console log

On Submit click form is not hitting the debugger and full page get refreshed

Body:
you need to provide the form id in the when submitting a form..

<form (ngSubmit)="create(custCreateForm)" class="form_margin" #custCreateForm="ngForm">


问:
Generate a video stream from Basler camera grabbing loop
I am a beginner in video streaming and handling.

I need to take the stream from a Basler GiGE camera and display it in a web container.

I am using the Basler.Pylon C# API to access the camera and grab images one by one. from the IGrabResult object returned, I can access various parameters such as width, height, stride, and of course the byte buffer.

On my PC, I can easily display that in an image window, but what do i need to do to display that in an ASP.NET web application?

EDIT

I am not looking for code but more for guidelines, if someone could explain how video streaming works in general, that would work too

答: You have at least two options - first one is producing series of jpeg-images every few seconds and show them one by one on client using  tag and simple javascript code. Second option is to generate and stream mp4-video and show it on client with some COM-windows media player or html5 control.</p>


问:
Haskell Yesod problems
someone could help me?! I'm working in a Haskell Yesod site for college on a C9 workspace, I've already installed by command Yesod and update cabal,  but when I try "stack build" command, this miserable error message appears:

```<code> $ stack build

aulahaskell-0.0.0: build (lib + exe)
Preprocessing library aulahaskell-0.0.0...
[ 7 of 13] Compiling Handler.Cliente  ( src/Handler/Cliente.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Cliente.o )

/home/ubuntu/workspace/web2017/src/Handler/Cliente.hs:10:1: error:
    Failed to load interface for ‘Network.HTTP.Types.Status’
    It is a member of the hidden package ‘http-types-0.9.1’.
    Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package aulahaskell-0.0.0 using:
      /home/ubuntu/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 build lib:aulahaskell exe:aulahaskell --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1
</code>```

Seriously, I tried a bunch of things to fix it, but nothing is working =S

答:
How did you start the yesod project? It's recommended to do:</p>

```<code>stack new my-yesod-project yesod-(your database here)
cd my-yesod-project
stack build
</code>```

Title: Haskell Yesod problems

Body:
someone could help me?! I'm working in a Haskell Yesod site for college on a C9 workspace, I've already installed by command Yesod and update cabal,  but when I try "stack build" command, this miserable error message appears:

 $ stack build

aulahaskell-0.0.0: build (lib + exe)
Preprocessing library aulahaskell-0.0.0...
[ 7 of 13] Compiling Handler.Cliente  ( src/Handler/Cliente.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Cliente.o )

/home/ubuntu/workspace/web2017/src/Handler/Cliente.hs:10:1: error:
    Failed to load interface for ‘Network.HTTP.Types.Status’
    It is a member of the hidden package ‘http-types-0.9.1’.
    Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package aulahaskell-0.0.0 using:
      /home/ubuntu/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 build lib:aulahaskell exe:aulahaskell --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1

Seriously, I tried a bunch of things to fix it, but nothing is working =S

Body:
How did you start the yesod project? It's recommended to do:

stack new my-yesod-project yesod-(your database here)
cd my-yesod-project
stack build


问:
Which parts in NodeJs are asynchronous and which parts are not?
Although I'm not having a practical problem, I'm in need of some explanation about what makes something asynchronous in standard Javascript  in NodeJs. Take for example this piece of code:

```<code>function pause(ms) {
    var dt = new Date()
    while((new Date()) - dt <= ms) {

    }
    console.log("Third")
}

console.log("First")

pause(3000)

console.log("second")
</code>```

The output is

```<code> First
 Third
 second
</code>```

Since NodeJs is asynchronous I would have expected the outcome to be "First Second Third". The following code however is asynchronous:

```<code>console.log("First")
setTimeOut(function(){
    console.log("Third")
}, 3000)

console.log("Second")
</code>```

The output is:
    First
    Second
    Third

The problem is I do not fully understand why. Is it because while loops are blocking, even though I've put it inside a function? If so, what else is blocking and what isn't? Has it something to do with the event loop? Are only I/O operations asynchronous? Is there an overview of what is and isn't or is there a general principle?

答:
The JS/Node.js language by default is synchronous (or blocking if you prefer) - as are most programming languages - in that lines of code are executed one after another, which is why the output of the first example is "First", "Third", "Second".

```<code>console.log("First");  // Outputs "First"

pause(3000);           // Outputs "Third"

console.log("second"); // Outputs "Second"
</code>```

That is pause() is just a function that is called and executed synchronously; there is nothing special about it.

In the second example the languages event-driven model has been used via setTimeout(), which accepts a callback function as a parameter that is called when the timer expires. Which means the sequence of outputs is different.

So to answer your question: standard JavaScript code is synchronous, but many of the standard library functions are non-blocking. As indeed your own can be if written accordingly.

Which standard library functions? Well I/O and timers generally are non-blocking, but it really is a case of reading the documentation.

Body:
Although I'm not having a practical problem, I'm in need of some explanation about what makes something asynchronous in standard Javascript  in NodeJs. Take for example this piece of code:

function pause(ms) {
    var dt = new Date()
    while((new Date()) - dt <= ms) {

    }
    console.log("Third")
}

console.log("First")

pause(3000)

console.log("second")

The output is

 First
 Third
 second

Since NodeJs is asynchronous I would have expected the outcome to be "First Second Third". The following code however is asynchronous:

console.log("First")
setTimeOut(function(){
    console.log("Third")
}, 3000)

console.log("Second")

The output is:
    First
    Second
    Third

The problem is I do not fully understand why. Is it because while loops are blocking, even though I've put it inside a function? If so, what else is blocking and what isn't? Has it something to do with the event loop? Are only I/O operations asynchronous? Is there an overview of what is and isn't or is there a general principle?

Body:
The JS/Node.js language by default is synchronous (or blocking if you prefer) - as are most programming languages - in that lines of code are executed one after another, which is why the output of the first example is "First", "Third", "Second".

console.log("First");  // Outputs "First"

pause(3000);           // Outputs "Third"

console.log("second"); // Outputs "Second"

That is pause() is just a function that is called and executed synchronously; there is nothing special about it.

In the second example the languages event-driven model has been used via setTimeout(), which accepts a callback function as a parameter that is called when the timer expires. Which means the sequence of outputs is different.

So to answer your question: standard JavaScript code is synchronous, but many of the standard library functions are non-blocking. As indeed your own can be if written accordingly.

Which standard library functions? Well I/O and timers generally are non-blocking, but it really is a case of reading the documentation.


问:
Javascript Raphael animations not showing
I have this function

```<code>function generateCircles2(){
    for(var i = 1; i<500; i++){
    var position = Math.floor(Math.random() * 600);
    var size = Math.floor(Math.random() * 8);
    var circle = paper.circle(-50,position,size);
    var time = Math.floor(Math.random() * 4000) + 2000;
    circle.attr("fill", "#000000");
    var cirAni = Raphael.animate({cy: position, cx: 850}, time);
    circle.animate(cirAni.delay(100));
  }
}
</code>```

which is suppose to generate circles to move across the screen at random points, however the circles do not appear and it also stops other animations from happening over the top of these ones. How can I get these circles to move across randomly whilst keeping the other animations going at the same time?

答:
This is because the correct method is 'animation' and not 'animate' for an animation object (as opposed to animating an element).

So instead of

```<code>var cirAni = Raphael.animate({cy: position, cx: 850}, time);
</code>```

Switch to

```<code>var cirAni = Raphael.animation({cy: position, cx: 850}, time);
</code>```

jsfiddle

Body:
I have this function

function generateCircles2(){
    for(var i = 1; i<500; i++){
    var position = Math.floor(Math.random() * 600);
    var size = Math.floor(Math.random() * 8);
    var circle = paper.circle(-50,position,size);
    var time = Math.floor(Math.random() * 4000) + 2000;
    circle.attr("fill", "#000000");
    var cirAni = Raphael.animate({cy: position, cx: 850}, time);
    circle.animate(cirAni.delay(100));
  }
}

which is suppose to generate circles to move across the screen at random points, however the circles do not appear and it also stops other animations from happening over the top of these ones. How can I get these circles to move across randomly whilst keeping the other animations going at the same time?

Body:
This is because the correct method is 'animation' and not 'animate' for an animation object (as opposed to animating an element).

So instead of

var cirAni = Raphael.animate({cy: position, cx: 850}, time);

Switch to

var cirAni = Raphael.animation({cy: position, cx: 850}, time);

jsfiddle


问:
Ellipsize for EditText
Ellipsize for EditText works only with

inputType - none

editable  - false

But this is making my EditText uneditable.
How can this be handled considering localization also.

Expected behavior:

Text in EditText should be shown with ellipses.

EditText should be editable.

Tried these but no success:

setEllipsize(TextUtils.TruncateAt.END) as per setEllipsize

android:ellipsize="end"
 android:singleLine="true"

答:
```<code>OnKeyListener keyListener = editText.getKeyListener();
editText.setOnFocusChangeListener(new OnFocusChangeListener(){
  void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus){
      editText.setOnKeyListener(null);
    }else{
      editText.setOnKeyListener(keyListener);
    }
  }
});
</code>```

This works for me, it ellipsizes the text when focus on the EditText is lost. Doesn't ellipsize while typing though.

Title: Ellipsize for EditText

Body:
OnKeyListener keyListener = editText.getKeyListener();
editText.setOnFocusChangeListener(new OnFocusChangeListener(){
  void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus){
      editText.setOnKeyListener(null);
    }else{
      editText.setOnKeyListener(keyListener);
    }
  }
});

This works for me, it ellipsizes the text when focus on the EditText is lost. Doesn't ellipsize while typing though.


问:
Android: Getting file name from camera?
I ran into an issue with something that I am probably just overlooking.

I want to take a picture from the surface preview of the camera, and save it to the sd_card. This works ALMOST perfect. I assigned it a file name, but it does not use the filename.

This is what I have been trying to do :

```<code>Button imagecapture = (Button) findViewById(R.id.imagecapture);
imagecapture.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        String filename = null;
        ImageCaptureCallback iccb = null;

        try {
            filename = timeStampFormat.format(new Date());
            ContentValues values = new ContentValues();
            values.put(Media.TITLE, filename);
            values.put(Media.DESCRIPTION, "Image capture by camera");

            Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
            iccb = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e(getClass().getSimpleName(), ex.getMessage(), ex);
        }
        camera.takePicture(mShutterCallback, mPictureCallbackRaw, iccb);
        com.froogloid.android.gspot.Park.imageFileName = filename;
    }
});
</code>```

It won't use the filename (i.e. time/date stamp I ask it to.)

答: This was resolved by implementing PictureCallback via a ImageCaptureCallback class, and Overriding the onPictureTaken where the file was being written via a file output stream. All you had to do was change the fileoutput stream to the filename you want.</p>

OwnerDisplayName: Chrispix

ContentLicense: CC BY-SA 4.0

Title: Android: Getting file name from camera?

Body:
I ran into an issue with something that I am probably just overlooking.

I want to take a picture from the surface preview of the camera, and save it to the sd_card. This works ALMOST perfect. I assigned it a file name, but it does not use the filename.

This is what I have been trying to do :

Button imagecapture = (Button) findViewById(R.id.imagecapture);
imagecapture.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        String filename = null;
        ImageCaptureCallback iccb = null;

        try {
            filename = timeStampFormat.format(new Date());
            ContentValues values = new ContentValues();
            values.put(Media.TITLE, filename);
            values.put(Media.DESCRIPTION, "Image capture by camera");

            Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
            iccb = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e(getClass().getSimpleName(), ex.getMessage(), ex);
        }
        camera.takePicture(mShutterCallback, mPictureCallbackRaw, iccb);
        com.froogloid.android.gspot.Park.imageFileName = filename;
    }
});

It won't use the filename (i.e. time/date stamp I ask it to.)


问:
Spring-Boot | loading different messages.properties files for different clients/users dynamically
I searched a lot but I can't find any useful information on my topic. Let me explain.

I created a spring application that can change its layout based on the user that is logged in. This layout can be uploaded by an admin. Now I want to add a function that the admin can upload a specific messages.properties for this user, so the texts change based on the logged in user as well. The templates that I created with thymeleaf are always the same. So the message keys are the same, just the values are changing.

I tried to create a dynamic ReloadableResourceBundleMessageSource but that is not working because at the configuration time you don't know what the name of the messages.propertie will be.

Do I just don't get it? I don't know. Is there any way to create a dynamic messages.properties-loader that can identify the file with a name like:
messages_foo_de_DE.properties

答:
You can keep locale or language preference associated with user. Once the user logged in you know the current user locale or language. Now you can set the locale using LocaleResolver</p>

```<code>LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
Locale userLocale = new Locale('de')// Locale loaded dynamically from DB or url parameter.

localeResolver.setLocale(request, response, userLocale );
</code>```

Body:
You can keep locale or language preference associated with user. Once the user logged in you know the current user locale or language. Now you can set the locale using LocaleResolver

LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
Locale userLocale = new Locale('de')// Locale loaded dynamically from DB or url parameter.

localeResolver.setLocale(request, response, userLocale );


问:
A bb recipe to add file to both initramfs and root
I am trying to edit my bb recipe to install my app to initramfs as well as the root. The issue i am facing is do_install() I don't think i can have the install copy to ${D} as well as initramfs-basic/1.0-r0/rootfs/bin (I don't know the variable for that location unless its ${base_sbindir} but it doesn't show up there).

It will only show up in the root bin directory after the system has booted but nothing i do with also copy it to the initramfs drive. How can i copy to both locations?

答: It turns out initramfs is just another image recipe. adding IMAGE_INSTALL_append = " myapp " added it to the initramfs as well as the root.</p>


问:
python install fails "egg_info failed with error code 1". No previous recommendations on similar posts have worked
New to python, but I have v. 3.6.3 installed and I'm trying to install an api from github. I type "pip install lendingclub" into the command line and get the error msg:

"Command "python setup.py egg_info" failed with error code 1 in
  C:\Users\REDPOI~1\AppData\Local\Temp\pip-build-adfw3v8o\pybars\"

I have tried updating pip with the commands :

```<code>"pip install --upgrade setuptools"
</code>```

And

```<code>"easy_install -U setuptools"
</code>```

The "pip3 install" gives the same error; I tried that in case the syntax was different for the newer python version. I have the Environment variables set to be able to access python from the command line rather than the anaconda environment. Any help would be greatly appreciated. I am at a loss :/

答:
Read these methods :

Try to clean your pip and modules caches first, see :
Removing pip's cache?

Try to intall it that current module witthout any caches by this
    command :  "pip --no-cache-dir install setuptools"

Or try to install it offline, first you need to download that module
    package from github ( prees that "clone or download" green button )
    then extarct that package to some folder, in terminal or cmd try to cd to that
    folder, then use this command : "python setup.py install"

Good Luck ...

Body:
New to python, but I have v. 3.6.3 installed and I'm trying to install an api from github. I type "pip install lendingclub" into the command line and get the error msg:

"Command "python setup.py egg_info" failed with error code 1 in
  C:\Users\REDPOI~1\AppData\Local\Temp\pip-build-adfw3v8o\pybars\"

I have tried updating pip with the commands :

"pip install --upgrade setuptools"

And

"easy_install -U setuptools"

The "pip3 install" gives the same error; I tried that in case the syntax was different for the newer python version. I have the Environment variables set to be able to access python from the command line rather than the anaconda environment. Any help would be greatly appreciated. I am at a loss :/


问:
.Net core 2 console appsettings transform
I am trying to add appsettings transformation to a .net core 2 console application e.g.

appSettings.json

appSettings.Test.json

appSettings.Prod.json

I have found the following code works for asp.net core:

```<code>public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:
true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
</code>```

However, I don't know how to get env.EnvironmentName because there is no IHostingEnvironment in a console app.

Any help will be appreciated

答:
Couldn't find anything else so using preprocessor directives for now

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if

```<code>public Startup()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)
</code>```

```<code>#if RELEASE
</code>```

```<code>        .AddJsonFile($"appsettings.Release.json", optional:
true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
</code>```

Body:
I am trying to add appsettings transformation to a .net core 2 console application e.g.

appSettings.json

appSettings.Test.json

appSettings.Prod.json

I have found the following code works for asp.net core:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:
true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

However, I don't know how to get env.EnvironmentName because there is no IHostingEnvironment in a console app.

Any help will be appreciated

Body:
Couldn't find anything else so using preprocessor directives for now

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if

public Startup()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)

#if RELEASE

        .AddJsonFile($"appsettings.Release.json", optional:
true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}