问:
Angular installation
I want to install Angular version 4.* on my windows 7.

I am currently using Angular version 1.6.*

I tried following command

```<code>npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@next --save
</code>```

But its not working

Can any one please guide me to install and to create angular 4 project..

答:
Make sure you have node version above 6.9 and npm above 3

Check the version by using node --version and npm --version

Install angular cli using npm install -g @angular/cli

-g installs the angular globally on your system and you just have to run this command only once

Create the angular project using ‘ng new angularprojectname’

Go to that project folder and check the angular version by ‘ng -v’

Upgrade this version to angular 4 by running this command-

For Windows-
        npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/platform-browser@next @angular/platform-browser-dynamic@next @angular/platform-server@next @angular/router@next @angular/animations@next --save

For Linux/Mac-
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@next --save

Make sure to upgrade the typescript version by running command-
npm install typescript@2.2.1 --save

Ignore whatever warning it shows up and now check the angular version by ‘ng -v’
The version has changed from 2.2.4 to 4.1.0

You can also check all the info about your angular cli in package.json file.

Title: Angular installation

Body:
I want to install Angular version 4.* on my windows 7.

I am currently using Angular version 1.6.*

I tried following command

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@next --save

But its not working

Can any one please guide me to install and to create angular 4 project..


来源: stackexchange

问:
How can I create an alias for an edit_path in Rails?
I have an edit_path set up to edit a customer, and it works fine.  However, due to some legacy privilege authorization issues, I need to use a different naming convention for customers, so my privileges are named action_company instead of action_customer.  I need to be able to use an path like edit_company_path but I'm not sure how to get this to work, I  keep getting undefined method 'edit_company_path'.  I've tried messing around with the routes, but I'm clearly misunderstanding how Rails maps paths to actions.

How can I map this custom path alias to the correct edit action for customers?

答:
undefined method 'edit_company_path'

If you want to set an alias to an existing edit path, use as:. Something like below

```<code>#routes.rb

get '/edit/:id', to: 'controller#edit', as: :edit_company
</code>```

This will you the required route helper which you can use.

ContentLicense: CC BY-SA 3.0

Body:
undefined method 'edit_company_path'

If you want to set an alias to an existing edit path, use as:. Something like below

#routes.rb

get '/edit/:id', to: 'controller#edit', as: :edit_company

This will you the required route helper which you can use.


问:
Newtonsoft.Json.JsonSerializationException has been thrown - Xamarin
I am working with live feeds on my app. After converting to Json and trying to display on my application is get this an exception thrown. I have looked at many answers relating to this issue but most answers are just the same as what i have in my code below? How can i resolve this problem?

Activity

```<code>{
    string result = new HTTPDataHandler().GetHTTPData(@params[0]);
    return result;
}

protected override void OnPostExecute(string result){
    RssObject data = JsonConvert.DeserializeObject<RssObject>(result);
    mDialog.Dismiss();
    DataAdapter adapter = new DataAdapter(data, mainActivity);
    mainActivity.rv.SetAdapter(adapter);
    adapter.NotifyDataSetChanged();
}
</code>```

Model

```<code>public class Feed
{
    public string url { get; set; }
    public string title { get; set; }
    public string link { get; set; }
    public string author { get; set; }
    public string description { get; set; }
    public string image { get; set; }
}

public class Item
{
    public string title { get; set; }
    public string pubDate { get; set; }
    public string link { get; set; }
    public string guid { get; set; }
    public string author { get; set; }
    public string thumbnail { get; set; }
    public string description { get; set; }
    public string content { get; set; }
    public List<object> enclosure { get; set; }
    public List<string> categories { get; set; }
}

public class RssObject
{
    public string status { get; set; }
    public Feed feed { get; set; }
    public List<Item> items { get; set; }
}
</code>```

error

```<code>Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Object]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'items[0].enclosure.link', line 1, position 1142.
</code>```

json

```<code>"status": "ok"
"feed": {
"url": "http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml"
"title": "NYT > Technology"
"link": "https://www.nytimes.com/section/technology?partner=rss&emc=rss"
"author": ""
"description": ""
"image": "https://static01.nyt.com/images/misc/NYT_logo_rss_250x40.png"
}
"items": [
{
"title": "Uber Fires Executive Over Handling of Rape Investigation in India"
"pubDate": "2017-06-08 00:55:39"
"link": "https://www.nytimes.com/2017/06/07/technology/uber-fires-executive.html?partner=rss&emc=rss"
"guid": "https://www.nytimes.com/2017/06/07/technology/uber-fires-executive.html"
"author": "MIKE ISAAC"
"thumbnail": ""
"description": "The president of Uber’s Asia business was terminated after reporters questioned why he obtained medical records of a woman attacked by her Uber driver."
"content": "The president of Uber’s Asia business was terminated after reporters questioned why he obtained medical records of a woman attacked by her Uber driver."
"enclosure": {
"link": "https://static01.nyt.com/images/2017/06/08/business/08UBER1-sub/08UBER1-sub-moth.jpg"
}
"categories": [
"0": "Uber Technologies Inc"
"1": "Sex Crimes"
"2": "Ethics and Official Misconduct"
"3": "Alexander, Eric"
]
}
</code>```

答:
If I understood correctly, you're trying work on an RSS feed converted into json. As far as I remember, in XML the enclosure tag has three required attributes "url", "length", and "type". So first issue is the enclosure is ill-formatted.

Assuming that json is how you want it to be. In json, enclosure is an object, notice {} not an array [].  But in C# its declared as List<object> which usually represents an array in json. So you're trying to deserialize an object into an List<object>.

There are couple of ways you can resolve this. One, if you know the schema of enclosure, create a new class to represent the schema and use it as type (or List if its supposed to be an array) instead of List<object>. Two, if enclosure is not necessary, just remove the property in C# class, so it can be ignored on deserialization. If you need enclosure, but don't know what the schema could be, let us know, we'll spend few more cycles to find a solution for you.

Body:
I am working with live feeds on my app. After converting to Json and trying to display on my application is get this an exception thrown. I have looked at many answers relating to this issue but most answers are just the same as what i have in my code below? How can i resolve this problem?

Activity

{
    string result = new HTTPDataHandler().GetHTTPData(@params[0]);
    return result;
}

protected override void OnPostExecute(string result){
    RssObject data = JsonConvert.DeserializeObject<RssObject>(result);
    mDialog.Dismiss();
    DataAdapter adapter = new DataAdapter(data, mainActivity);
    mainActivity.rv.SetAdapter(adapter);
    adapter.NotifyDataSetChanged();
}

Model

public class Feed
{
    public string url { get; set; }
    public string title { get; set; }
    public string link { get; set; }
    public string author { get; set; }
    public string description { get; set; }
    public string image { get; set; }
}

public class Item
{
    public string title { get; set; }
    public string pubDate { get; set; }
    public string link { get; set; }
    public string guid { get; set; }
    public string author { get; set; }
    public string thumbnail { get; set; }
    public string description { get; set; }
    public string content { get; set; }
    public List<object> enclosure { get; set; }
    public List<string> categories { get; set; }
}

public class RssObject
{
    public string status { get; set; }
    public Feed feed { get; set; }
    public List<Item> items { get; set; }
}

error

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Object]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'items[0].enclosure.link', line 1, position 1142.

json

"status": "ok"
"feed": {
"url": "http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml"
"title": "NYT > Technology"
"link": "https://www.nytimes.com/section/technology?partner=rss&emc=rss"
"author": ""
"description": ""
"image": "https://static01.nyt.com/images/misc/NYT_logo_rss_250x40.png"
}
"items": [
{
"title": "Uber Fires Executive Over Handling of Rape Investigation in India"
"pubDate": "2017-06-08 00:55:39"
"link": "https://www.nytimes.com/2017/06/07/technology/uber-fires-executive.html?partner=rss&emc=rss"
"guid": "https://www.nytimes.com/2017/06/07/technology/uber-fires-executive.html"
"author": "MIKE ISAAC"
"thumbnail": ""
"description": "The president of Uber’s Asia business was terminated after reporters questioned why he obtained medical records of a woman attacked by her Uber driver."
"content": "The president of Uber’s Asia business was terminated after reporters questioned why he obtained medical records of a woman attacked by her Uber driver."
"enclosure": {
"link": "https://static01.nyt.com/images/2017/06/08/business/08UBER1-sub/08UBER1-sub-moth.jpg"
}
"categories": [
"0": "Uber Technologies Inc"
"1": "Sex Crimes"
"2": "Ethics and Official Misconduct"
"3": "Alexander, Eric"
]
}


问:
How to get ClockPicker for Bootstrap (Plugin) to appear in a Bootstrap Modal pop up form?
Here is the link to ClockPicker for Bootstrap: http://www.jqueryrain.com/?B83aD_dg

It works perfectly; however, when I try to use it to fill in a text-input in a Bootstrap modal pop up, the clock appears behind the modal pop up. How can I get the clock picker to appear in (or in front of) the modal pop up instead?

Here is an image of what happens:

I've tried changing the z-index of the div to be in front; I've also tried changing the z-index of every element in clockpicker.css to be in front (for example: z-index: 1120). However, all this does is make the clock disappear.

```<code><div class="modal fade appointment-modal"
     id="appointment-modal"
     tabindex="-1"
     role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true">

<div class="modal-dialog tutors-modal">
    <div class="modal-content tutors-modal">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title">Appointment Scheduler</h4>
        </div>
        <div class="modal-body" style="height: 575px; left: 2.5%;">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <div class="alert alert-danger"><span class="glyphicon glyphicon-alert"></span>
                            <form role="form" action="/portal/make-appointment/" method="post" id="appointment_form" class="form-horizontal">
                                <div class="col-lg-6">

                                    <div class="input-group clockpicker" id = "clockpicker" style="padding: 6px; padding-bottom: 20px;">
                                        <input type="text" class="form-control" id = "time" name="time" value="08:00">
                                        <span class="input-group-addon">
                                            <span class="glyphicon glyphicon-time"></span>
                                        </span>
                                    </div>
                                    <script type="text/javascript">
                                        var input = $('#time');
                                        input.clockpicker({
                                            autoclose: true
                                        });
                                    </script>
                                    <input type="submit" name="submit" id="submit" value="Schedule Appointment" class="btn btn-info pull-right">
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
        </div>
    </div>
</div>
</code>```

答:
just add this style to your clockpicker

```<code>.clockpicker-popover
{
   z-index: 999999 !important;
}
</code>```

Body:
Here is the link to ClockPicker for Bootstrap: http://www.jqueryrain.com/?B83aD_dg

It works perfectly; however, when I try to use it to fill in a text-input in a Bootstrap modal pop up, the clock appears behind the modal pop up. How can I get the clock picker to appear in (or in front of) the modal pop up instead?

Here is an image of what happens:

I've tried changing the z-index of the div to be in front; I've also tried changing the z-index of every element in clockpicker.css to be in front (for example: z-index: 1120). However, all this does is make the clock disappear.

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Appointment Scheduler

                            <form role="form" action="/portal/make-appointment/" method="post" id="appointment_form" class="form-horizontal">

                                        <input type="text" class="form-control" id = "time" name="time" value="08:00">

                                    <input type="submit" name="submit" id="submit" value="Schedule Appointment" class="btn btn-info pull-right">

                            </form>

Body:
just add this style to your clockpicker

.clockpicker-popover
{
   z-index: 999999 !important;
}


问:
Search Filter in nested ng-repeat in a list and Hide parents that don't have children
Demo

I wanted to filter the items in a dynamic list names that is fetched from json files. here my requirement is to hide the parents that don't have children i'm sharing my sample code here.. in my program the parent list is still showing.

index.html

```<code> <!DOCTYPE html>
    <html ng-app="myItemsApp">

    <head>
      <meta charset="utf-8" />
      <title>dynamic title</title>

      <link data-require="bootstrap-css" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

      <script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
      <script data-require="bootstrap" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
      <script src="script.js"></script>
    </head>

    <body>

      <form >
           <div class="form-group">
        <input type="text" class="form-control" ng-model="getlist" placeholder="Search Docs..">
            </div>
      </form>

      <div ng-controller=NavController>
        <h3>Load title dynamically</h3>
        <div class="row">
          <div class="col-md-4">
            <div class="panel panel-default">
              <ul class="list-group" ng-repeat="(key,item) in itemDetails">
                {{key}}
                <li ng-repeat="i in item | filter:getlist"><a class="list-group-item" ng-click="select(i)" >{{i.title}}</a></li>
              </ul>
            </div>
          </div>

          <div class="col-md-8">
            <div class="panel panel-default">
              <h2>Title_from json: {{selected.title}}</h2>
            </div>
          </div>
        </div>
      </div>
    </body>
    </html>
</code>```

script.js

```<code>var myItemsApp = angular.module('myItemsApp', []);

myItemsApp.factory('itemsFactory', ['$http', function($http){
  var itemsFactory ={
    itemDetails: function() {
      return $http(
      {
        url: "action.json",
        method: "GET",
      })
      .then(function (response) {
        return response.data;
        });
      }
    };
    return itemsFactory;

}]);

myItemsApp.controller('NavController', ['$scope', 'itemsFactory', function($scope, itemsFactory){
  var promise = itemsFactory.itemDetails();

    promise.then(function (data) {
        $scope.itemDetails = data;
        console.log(data);
    });
    $scope.select = function(item) {
      $scope.selected = item;
    }
    $scope.selected = {};
}]);
</code>```

action.json

```<code>{

   "product": [{
         "title": "Product View",
         "path": "test1"

      },

      {
         "title": "Product Add",
         "path": "2"

      },
      {
         "title": "Product Update",
         "path": "test3"

      },

      {
         "title": "Product delete",
         "path": "test4"

      }
   ],

   "page": [{
      "title": "About us"
   }]

}
</code>```

答:
It should be like this

```<code><div class="col-md-4">
    <div class="panel panel-default">
      <ul class="list-group" ng-repeat="(key,item) in itemDetails" >
        {{result.length > 0 ?key : ''}}
        <li ng-repeat="i in result = (item | filter:getlist)"><a class="list-group-item" ng-click="select(i)" >{{i.title}}</a></li>
      </ul>
    </div>
  </div>
</code>```

Demo

Body:
Demo

I wanted to filter the items in a dynamic list names that is fetched from json files. here my requirement is to hide the parents that don't have children i'm sharing my sample code here.. in my program the parent list is still showing.

index.html

 <!DOCTYPE html>

      <meta charset="utf-8" />
      <title>dynamic title</title>

      <link data-require="bootstrap-css" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

      <form >

        <input type="text" class="form-control" ng-model="getlist" placeholder="Search Docs..">

      </form>

Load title dynamically

                {{key}}

{{i.title}}

Title_from json: {{selected.title}}

script.js

var myItemsApp = angular.module('myItemsApp', []);

myItemsApp.factory('itemsFactory', ['$http', function($http){
  var itemsFactory ={
    itemDetails: function() {
      return $http(
      {
        url: "action.json",
        method: "GET",
      })
      .then(function (response) {
        return response.data;
        });
      }
    };
    return itemsFactory;

}]);

myItemsApp.controller('NavController', ['$scope', 'itemsFactory', function($scope, itemsFactory){
  var promise = itemsFactory.itemDetails();

    promise.then(function (data) {
        $scope.itemDetails = data;
        console.log(data);
    });
    $scope.select = function(item) {
      $scope.selected = item;
    }
    $scope.selected = {};
}]);

action.json

{

   "product": [{
         "title": "Product View",
         "path": "test1"

      },

      {
         "title": "Product Add",
         "path": "2"

      },
      {
         "title": "Product Update",
         "path": "test3"

      },

      {
         "title": "Product delete",
         "path": "test4"

      }
   ],

   "page": [{
      "title": "About us"
   }]

}

Body:
It should be like this

<div class="col-md-4">
    <div class="panel panel-default">
      <ul class="list-group" ng-repeat="(key,item) in itemDetails" >
        {{result.length > 0 ?key : ''}}
        <li ng-repeat="i in result = (item | filter:getlist)"><a class="list-group-item" ng-click="select(i)" >{{i.title}}</a></li>
      </ul>
    </div>
  </div>

Demo


问:
mybatis transaction rollback
case 1：

```<code>class TestService{
     @Autowired
     private SqlSessionTemplate sqlSession;

    public void insert(Map map1,Map map2,Map map3){
          sqlSession.insert("testMapper.insert",map1);
          sqlSession.insert("testMapper.insert",map2);
          sqlSession.insert("testMapper.insert",map3);
    }
}
</code>```

case 2：

```<code>@Service
class ObjectService{
     @Autowired
     private SqlSessionTemplate sqlSession;

    public void insert(Map map){
          sqlSession.insert("testMapper.insert",map);
    }
}

class TestService{
     @Autowired
     private ObjectService objectService;

    public void insert(Map map1,Map map2,Map map3){
          objectService.insert(map1);
          objectService.insert(map2);
          objectService.insert(map3);
    }
}
</code>```

I use mybatis and I have configured transactions using spring. I have a problem that the code described in the case #1 throws exception and the transaction is rolled back (so nothing is really inserted into database).

When I run case #2 the error is thrown again but data is still inserted into database and rollback does not happen.

答:
Most probably you transaction configuration does not treat TestService.insert as a transactional method so it is not executed in transaction so each invocation of objectService.insert runs in its own transaction.

It means that for example the first invocation objectService.insert(map1) runs fine and the the problem happens during the second invocation. At that time the first transaction is already committed and even there is some problem with insertion of the second record the result of the first transaction is already persisted to database. And this looks like the absence of the rollback on the TestService.insert.

Title: mybatis transaction rollback

Body:
case 1：

class TestService{
     @Autowired
     private SqlSessionTemplate sqlSession;

    public void insert(Map map1,Map map2,Map map3){
          sqlSession.insert("testMapper.insert",map1);
          sqlSession.insert("testMapper.insert",map2);
          sqlSession.insert("testMapper.insert",map3);
    }
}

case 2：

@Service
class ObjectService{
     @Autowired
     private SqlSessionTemplate sqlSession;

    public void insert(Map map){
          sqlSession.insert("testMapper.insert",map);
    }
}

class TestService{
     @Autowired
     private ObjectService objectService;

    public void insert(Map map1,Map map2,Map map3){
          objectService.insert(map1);
          objectService.insert(map2);
          objectService.insert(map3);
    }
}

I use mybatis and I have configured transactions using spring. I have a problem that the code described in the case #1 throws exception and the transaction is rolled back (so nothing is really inserted into database).

When I run case #2 the error is thrown again but data is still inserted into database and rollback does not happen.


问:
jQuery: prevent click queue
```<code>$("#right").live("click", function(event) {
    $(".image_scroll").animate({"left": "+=300px"}, "slow");
});
</code>```

I need the click to basically not register until the animation is done.
I've tried using return false but that just seems to kill the link entirely.

Tried also using $(".image_scroll").stop().animate({"left": "+=300px"}, "slow"); but that just makes the animation stutter and look glitchy.

Edit: The id #right is on an image, not an a tag. The HTML is as follows:

```<code><img src="/images/right.png" id="right" alt="" />
<div id="container">
    <div id="image_scroll">
        <img src="1.jpg" />
        <img src="3.jpg" />
        <img src="4.jpg" />
    </div><!-- /#image_scroll -->
</div> <!-- /#container
</code>```

答:
```<code>var handler = function(event) {
    $("#right").die("click");
    $(".image_scroll").animate({"left": "+=300px"}, "slow", function(){
        $("#right").live("click", handler);
    });
};
$("#right").live("click", handler);
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery: prevent click queue

Body:
$("#right").live("click", function(event) {
    $(".image_scroll").animate({"left": "+=300px"}, "slow");
});

I need the click to basically not register until the animation is done.
I've tried using return false but that just seems to kill the link entirely.

Tried also using $(".image_scroll").stop().animate({"left": "+=300px"}, "slow"); but that just makes the animation stutter and look glitchy.

Edit: The id #right is on an image, not an a tag. The HTML is as follows:


问:
I want to make a discord blacklister bot that reads messages but i can't make him read the messages
I want to make a discord bot to blacklist certain words and for that i was trying to first read a message that was sent by a user and check if a word in that message is blacklisted and then remove the message but i don't know how to make the bot read the messages</p>

答:
Ok so i did something and now i have this

```<code> public static async void OnMessageReceived(object sender, MessageEventArgs e)
    {
        if (e.Message.Text.Contains(toBlacklist.ToString()))
        {
            Message[] blacklistedMessagesToDelete;
            blacklistedMessagesToDelete = await e.Channel.DownloadMessages(1);

            await e.Channel.DeleteMessages(blacklistedMessagesToDelete);
        }
    }
</code>```

but the toBlacklist is an array with more words in it and if i don't pass in a string in quotation marks instead of it, it won't delete the message

Body:
Ok so i did something and now i have this

 public static async void OnMessageReceived(object sender, MessageEventArgs e)
    {
        if (e.Message.Text.Contains(toBlacklist.ToString()))
        {
            Message[] blacklistedMessagesToDelete;
            blacklistedMessagesToDelete = await e.Channel.DownloadMessages(1);

            await e.Channel.DeleteMessages(blacklistedMessagesToDelete);
        }
    }

but the toBlacklist is an array with more words in it and if i don't pass in a string in quotation marks instead of it, it won't delete the message


问:
Commands to renew a Java Keystore with a Symantec renewal using a new CSR (not the original CSR)
Two years ago, I got a VeriSign/Symantec SSL certificate.  When initiating this request, we created a CSR on a random server that is not associated with the common name of the certificate.  To create a Java Keystore, I did the following two steps.

```<code>openssl pkcs12 -export -in common_name.cer -inkey common_name.key -out renewal.p12 -name common_name_alias -CAfile NewVerisignIM.cer -caname root

keytool -importkeystore -deststorepass XXX! -destkeypass XXX!
-destkeystore renewal.keystore -srckeystore renewal.p12 -srcstoretype PKCS12 -srcstorepass XXX! -alias common_name_alias
</code>```

Now our certificate is about to expire.  When using the original entry on the Symantec website, and creating a new CSR, we got the signed certificate file (same file name as common_name.cer above), the private key (same file name as common_name.key above).  After signing the new CSR, we DID NOT get back the "NewVerisignIM.cer" file, which appears to be the root CA and intermediate CA combined in one file (aka the CA chain I believe).  So I don't know how to recreate the Java Keystore without that file.

I tried using the old "NewVerisignIM.cer" with the new files after signing, but that did not work.  That's all I've tried so far.  I got a Java exception of

PKIX path building failed:
  sun.security.provider.certpath.SunCertPathBuilderException: unable to
  find valid certification path to requested target

This site contains instructions when using the original CSR and using a JKS.

https://knowledge.symantec.com/kb/index?page=content&id=SO11942&pmv=print&actp=PRINT&viewlocale=en_US

But this question/answer recommends using a new CSR.

Renew certificate with Java Keytool - reuse old CSR?

What commands can I use if we use the new CSR?

答:
I had the commands correct.  The new private key is needed in the first command (X509 to PKCS12).  The new signed certificate is needed in the first command.  And the original CA chain file, when the original certificate was created, is needed in the first command.  The renewal did not contain this file as output.  In 2015, Verisign probably had not been acquired by Symantec yet, so the file was named "NewVerisignIM.cer".  The second command above converts from PKCS12 to JKS (Java Keystore) format.

My problem was that servers acting as the client who were authenticating against this server did not have the public key updated, because there was a new private key assigned in the renewal.  Please note that this new private key is recommended by Symantec, but not required.  So I had to export the certificate from the newly created JKS store after the conversion of those two commands on the server containing the common name of the renewal certificate, and then delete the old public key (entry) from the client Java Keystore (on a different server), and import the new public key, so it could talk to the server (with the renewal, and new private key).

Commands run on server (new keystore gets created):

```<code>openssl pkcs12 -export -in common_name.cer -inkey common_name.key -out renewal.p12 -name common_name_alias -CAfile NewVerisignIM.cer -caname root

keytool -importkeystore -deststorepass XXX! -destkeypass XXX!
-destkeystore renewal.keystore -srckeystore renewal.p12 -srcstoretype PKCS12 -srcstorepass ppp1 -alias common_name_alias

keytool -export -alias https-renewal -file https-renewal.pem -keystore renewal.keystore
</code>```

Commands run on client (keystore remains the same):

```<code>keytool –delete –alias https-renewal –keystore original.keystore –storepass ppp2

keytool -import -v -alias https-renewal -file https-renewal.pem -keystore original.keystore -storepass ppp2
</code>```

(where "https-renewal.pem" is the file exported from the 3rd command in this answer)

Body:
Two years ago, I got a VeriSign/Symantec SSL certificate.  When initiating this request, we created a CSR on a random server that is not associated with the common name of the certificate.  To create a Java Keystore, I did the following two steps.

openssl pkcs12 -export -in common_name.cer -inkey common_name.key -out renewal.p12 -name common_name_alias -CAfile NewVerisignIM.cer -caname root

keytool -importkeystore -deststorepass XXX! -destkeypass XXX!
-destkeystore renewal.keystore -srckeystore renewal.p12 -srcstoretype PKCS12 -srcstorepass XXX! -alias common_name_alias

Now our certificate is about to expire.  When using the original entry on the Symantec website, and creating a new CSR, we got the signed certificate file (same file name as common_name.cer above), the private key (same file name as common_name.key above).  After signing the new CSR, we DID NOT get back the "NewVerisignIM.cer" file, which appears to be the root CA and intermediate CA combined in one file (aka the CA chain I believe).  So I don't know how to recreate the Java Keystore without that file.

I tried using the old "NewVerisignIM.cer" with the new files after signing, but that did not work.  That's all I've tried so far.  I got a Java exception of

PKIX path building failed:
  sun.security.provider.certpath.SunCertPathBuilderException: unable to
  find valid certification path to requested target

This site contains instructions when using the original CSR and using a JKS.

https://knowledge.symantec.com/kb/index?page=content&id=SO11942&pmv=print&actp=PRINT&viewlocale=en_US

But this question/answer recommends using a new CSR.

Renew certificate with Java Keytool - reuse old CSR?

What commands can I use if we use the new CSR?

Body:
I had the commands correct.  The new private key is needed in the first command (X509 to PKCS12).  The new signed certificate is needed in the first command.  And the original CA chain file, when the original certificate was created, is needed in the first command.  The renewal did not contain this file as output.  In 2015, Verisign probably had not been acquired by Symantec yet, so the file was named "NewVerisignIM.cer".  The second command above converts from PKCS12 to JKS (Java Keystore) format.

My problem was that servers acting as the client who were authenticating against this server did not have the public key updated, because there was a new private key assigned in the renewal.  Please note that this new private key is recommended by Symantec, but not required.  So I had to export the certificate from the newly created JKS store after the conversion of those two commands on the server containing the common name of the renewal certificate, and then delete the old public key (entry) from the client Java Keystore (on a different server), and import the new public key, so it could talk to the server (with the renewal, and new private key).

Commands run on server (new keystore gets created):

openssl pkcs12 -export -in common_name.cer -inkey common_name.key -out renewal.p12 -name common_name_alias -CAfile NewVerisignIM.cer -caname root

keytool -importkeystore -deststorepass XXX! -destkeypass XXX!
-destkeystore renewal.keystore -srckeystore renewal.p12 -srcstoretype PKCS12 -srcstorepass ppp1 -alias common_name_alias

keytool -export -alias https-renewal -file https-renewal.pem -keystore renewal.keystore

Commands run on client (keystore remains the same):

keytool –delete –alias https-renewal –keystore original.keystore –storepass ppp2

keytool -import -v -alias https-renewal -file https-renewal.pem -keystore original.keystore -storepass ppp2

(where "https-renewal.pem" is the file exported from the 3rd command in this answer)


问:
What is the difference between the `num` and `count` parameters in a Caffe blob when using a Python layer?
In the Euclidean Loss Example for a Python layer in Caffe, there is usage of bottom[0].num as well as bottom[0].count.

It appears that both have exactly the same meaning.

From the Caffe blob.hpp, there are functions with the same name defined as:

```<code>inline int count() const { return count_; }
</code>```

and

```<code>inline int num() const { return LegacyShape(0); }
</code>```

It seems that count_ keeps track of the number of elements in the blob, and this also seems to be the value returned by num().

Is this the case? Can I use them interchangeably?

答:
According to these Caffe docs, num is a "Deprecated legacy shape accessor num: use shape(0) instead."

On the other hand, count is the product of all the dimensions.

So, num gives you a number of elements, each of which may have several channels, height, and width. count is the total count of values. They should only agree if every dimension in shape is 1, except for shape(0).

Body:
In the Euclidean Loss Example for a Python layer in Caffe, there is usage of bottom[0].num as well as bottom[0].count.

It appears that both have exactly the same meaning.

From the Caffe blob.hpp, there are functions with the same name defined as:

inline int count() const { return count_; }

and

inline int num() const { return LegacyShape(0); }

It seems that count_ keeps track of the number of elements in the blob, and this also seems to be the value returned by num().

Is this the case? Can I use them interchangeably?


问:
Elegantly handle different parameter types
I have a function that, in the simplest of cases, operates on an iterable of items.

```<code>def foo(items):
    for item in items:
        # do stuff
</code>```

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

```<code>def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above
</code>```

I can merge these two cases like this:

```<code>def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff
</code>```

This works just fine. Now I get a third use case that looks like this:

```<code>def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again
</code>```

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

答:
hasattr(object, name)

```<code>    if hasattr(obj, '__iter__'):
        return [o for o in obj]
    elif hasattr(obj, 'iteritems'):
        return [o for o in obj.iteritems()]
    elif isinstance(obj, list) or isinstance(obj, tuple):
        return [o.iteritems() for o in [o for o in obj]]
    else:
        raise TypeError

class Bar(list):
    def iteritems(self):
        return self.__iter__()

print foo([1,2,3])
print foo(Bar([1,2,3]))
print foo([[1,2,3], [1,2,3]])
print foo(1)

[1, 2, 3]
[1, 2, 3]
[[1, 2, 3], [1, 2, 3]]
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    print foo(1)
  File "test.py", line 11, in foo
    raise TypeError
TypeError
</code>```

Body:
I have a function that, in the simplest of cases, operates on an iterable of items.

def foo(items):
    for item in items:
        # do stuff

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above

I can merge these two cases like this:

def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff

This works just fine. Now I get a third use case that looks like this:

def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

Body:
hasattr(object, name)

    if hasattr(obj, '__iter__'):
        return [o for o in obj]
    elif hasattr(obj, 'iteritems'):
        return [o for o in obj.iteritems()]
    elif isinstance(obj, list) or isinstance(obj, tuple):
        return [o.iteritems() for o in [o for o in obj]]
    else:
        raise TypeError

class Bar(list):
    def iteritems(self):
        return self.__iter__()

print foo([1,2,3])
print foo(Bar([1,2,3]))
print foo([[1,2,3], [1,2,3]])
print foo(1)

[1, 2, 3]
[1, 2, 3]
[[1, 2, 3], [1, 2, 3]]
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    print foo(1)
  File "test.py", line 11, in foo
    raise TypeError
TypeError


问:
Are these two Activerecord queryes just one Database query. Trying to solve an N+1
I am curious if these two queries are the same for the purposes of solving an N+1 query. I only want one query to the database being made. If they are the same, why? How does Activerecord handle this? What is going on?

```<code>products = Product.where(user_id: user.id)
products.includes(:restrictions).select do |product|
   !product.restrictions.map(&:state_name).include?("CT")
end
</code>```

and

```<code>Product.includes(:restrictions).where(user_id: user.id).select do |product|
   product.restrictions.map(&:state_name).include?("CT")
end
</code>```

A Product has many Restrictions

答:
Those 2 are exactly same..you can check out their sql versions to verify

```<code>Product.includes(:restrictions).where(user_id: user.id).to_sql
</code>```

But the fact that the first one is written on different lines will query the db twice..
First only

```<code>Product.where(user_id: user.id)
</code>```

Second with includes which preloads the associated records

```<code>Product.includes(:restrictions).where(user_id: user.id)
</code>```

This pretty much explains the concept of scopes which are chainable to active record collection objects. You can divide a query into parts and define them as scopes as well..

Body:
I am curious if these two queries are the same for the purposes of solving an N+1 query. I only want one query to the database being made. If they are the same, why? How does Activerecord handle this? What is going on?

products = Product.where(user_id: user.id)
products.includes(:restrictions).select do |product|
   !product.restrictions.map(&:state_name).include?("CT")
end

and

Product.includes(:restrictions).where(user_id: user.id).select do |product|
   product.restrictions.map(&:state_name).include?("CT")
end

A Product has many Restrictions

Body:
Those 2 are exactly same..you can check out their sql versions to verify

Product.includes(:restrictions).where(user_id: user.id).to_sql

But the fact that the first one is written on different lines will query the db twice..
First only

Product.where(user_id: user.id)

Second with includes which preloads the associated records

Product.includes(:restrictions).where(user_id: user.id)

This pretty much explains the concept of scopes which are chainable to active record collection objects. You can divide a query into parts and define them as scopes as well..


问:
transforming a string into a list in python
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

```<code>['[', '1', ',', '2', ',', '3', ',', '4', ']']
</code>```

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

```<code>[1,2,3,4]
</code>```

but I don't know how to get that output into a variable, can someone help?

答:
Use ast.literal_eval:

```<code>In [3]: import ast

In [4]: s = "[1,2,3,4]"

In [5]: ast.literal_eval(s)
Out[5]: [1, 2, 3, 4]

In [6]: L = ast.literal_eval(s)

In [7]: L
Out[7]: [1, 2, 3, 4]
</code>```

Body:
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

['[', '1', ',', '2', ',', '3', ',', '4', ']']

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

[1,2,3,4]

but I don't know how to get that output into a variable, can someone help?

Body:
Use ast.literal_eval:

In [3]: import ast

In [4]: s = "[1,2,3,4]"

In [5]: ast.literal_eval(s)
Out[5]: [1, 2, 3, 4]

In [6]: L = ast.literal_eval(s)

In [7]: L
Out[7]: [1, 2, 3, 4]


问:
VB.NET 2015 How to call an external Python program from Visual Basic Program
I am trying to run a compiled Python Program File *.pyc from within Visual Basic 2015 program button click method

```<code>    Dim OpenCMD
    OpenCMD = CreateObject("wscript.shell")
    OpenCMD.run("C:\WinPython\CODES\python runnow.pyc")
</code>```

This throws the below error:

```<code>An unhandled exception of type 'System.IO.FileNotFoundException' occurred in
Microsoft.VisualBasic.dll

Additional information: The system cannot find the file specified.
(Exception from HRESULT: 0x80070002)
</code>```

When I run the same command in command line using cmd.exe it runs successfully

```<code>python runnow.pyc
</code>```

Please help me to run the python program from VB.NET 2015 I am using Visual Studio Community 2015 edition.

Many thanks in advance for your valuable answers.

答:
I suspect your problem might be at this line:

```<code>OpenCMD.run("C:\WinPython\CODES\python runnow.pyc")
</code>```

...since you indicated that simply running python runnow.pyc in cmd.exe works as expected.

Try specifying the full path to your runnow.pyc file in your OpenCMD.run call. I'm guessing it can't find the file because it is not in your Python executable's working directory when that method is called.

Body:
I am trying to run a compiled Python Program File *.pyc from within Visual Basic 2015 program button click method

    Dim OpenCMD
    OpenCMD = CreateObject("wscript.shell")
    OpenCMD.run("C:\WinPython\CODES\python runnow.pyc")

This throws the below error:

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in
Microsoft.VisualBasic.dll

Additional information: The system cannot find the file specified.
(Exception from HRESULT: 0x80070002)

When I run the same command in command line using cmd.exe it runs successfully

python runnow.pyc

Please help me to run the python program from VB.NET 2015 I am using Visual Studio Community 2015 edition.

Many thanks in advance for your valuable answers.

Body:
I suspect your problem might be at this line:

OpenCMD.run("C:\WinPython\CODES\python runnow.pyc")

...since you indicated that simply running python runnow.pyc in cmd.exe works as expected.

Try specifying the full path to your runnow.pyc file in your OpenCMD.run call. I'm guessing it can't find the file because it is not in your Python executable's working directory when that method is called.


问:
Stop a HTML5 canvas animation
How can I stop this html5 canvas animation after 5 sec?

I'm a beginner with html5 canvas. I have tried all the code I know but it keeps playing or break.

Maybe there is a easy solution for this.

EDIT:      after 5 sec the cycle production should stop but the animation
  should continue.

Any help is highly appreciated!

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

var c = document.getElementById('canv'),
    $ = c.getContext('2d');

    c.width = window.innerWidth;
    c.height = window.innerHeight;

window.addEventListener('resize', function(){
    c.width = window.innerWidth;
    c.height = window.innerHeight;
}, false);

var arr = [];

var go = function() {
  $.fillStyle = "hsla(0,0%,10%,.8)";
  $.fillRect(0, 0, c.width, c.height);

  var p = new Part(c.width/2 , c.height);
  p.vx = Math.random() * 10-5;
  arr.push(p);

  for (var i in arr) {
    var p = arr[i];
    p.disp($);
    p.upd();
  }

  if (arr.length > 500) {
    arr.shift();
  }
}

var rnd = function(min, max) {
  return Math.random() * (max - min) + min;
}

var Part = function(px, py) {
  this.px = px;
  this.py = py;
  this.vy = rnd(1.1, 2)*-8*1.1;
  this.vx = rnd(1.1, 2)*5*1.1;

  this.grav = 0.1;
  this.col = 0;
  this.rad = rnd(5,30);
  this.disp = function($) {
    $.fillStyle = "hsla(" + this.col + ", 95%, 60%, .8)";
    $.beginPath();
    $.arc(this.px, this.py, this.rad, 0, Math.PI*2);
    $.fill();
  }

    this.upd = function() {
      this.vy += this.grav;
      this.py += this.vy*1.1;
      this.px += this.vx* 1.1;
      this.col += 2;
  }
}

var run = function() {
  window.requestAnimFrame(run);
  go();

}
run();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  width:100%;
  margin:0;
  overflow:hidden;
  background:hsla(0,0%,10%,1);
}</code>```

<canvas id = 'canv'></canvas>```

答:
This snippet will stop new bubbles from being created after 5 seconds yet will still show the remaining animation.

The key is to create a condition around the code where you call the generation of new items. With a global variable time_switch the condition can be used in other functions. The timer and function are as follows:

```<code>var time_switch = 0;
window.setTimeout("pauser();",5000);
function pauser() {
  time_switch = 1;
}
</code>```

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000);
    };
})();

var c = document.getElementById('canv'),
    $ = c.getContext('2d');

    c.width = window.innerWidth;
    c.height = window.innerHeight;

window.addEventListener('resize', function(){
    c.width = window.innerWidth;
    c.height = window.innerHeight;
}, false);

var arr = [];

var go = function() {

    $.fillStyle = "hsla(0,0%,10%,.8)";
    $.fillRect(0, 0, c.width, c.height);

   if (time_switch !== 1) {
      var p = new Part(c.width/2 , c.height);
      p.vx = Math.random() * 10-5;
      arr.push(p);
    }

    for (var i in arr) {
      var p = arr[i];
      p.disp($);
      p.upd();
    }

    if (arr.length > 500) {
      arr.shift();
    }

}

var rnd = function(min, max) {
  return Math.random() * (max - min) + min;
}

var Part = function(px, py) {
  this.px = px;
  this.py = py;
  this.vy = rnd(1.1, 2)*-8*1.1;
  this.vx = rnd(1.1, 2)*5*1.1;

  this.grav = 0.1;
  this.col = 0;
  this.rad = rnd(5,30);
  this.disp = function($) {
    $.fillStyle = "hsla(" + this.col + ", 95%, 60%, .8)";
    $.beginPath();
    $.arc(this.px, this.py, this.rad, 0, Math.PI*2);
    $.fill();
  }

    this.upd = function() {
      this.vy += this.grav;
      this.py += this.vy*1.1;
      this.px += this.vx* 1.1;
      this.col += 2;
  }
}
var time_switch = 0;
window.setTimeout("pauser();",5000);
function pauser() {
  time_switch = 1;
}
var run = function() {
  //if (time_switch !== 1) {
    window.requestAnimFrame(run);
  //}

  go();

}
run();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  width:100%;
  margin:0;
  overflow:hidden;
  background:hsla(0,0%,10%,1);
}</code>```

<canvas id = 'canv'></canvas>```

Title: Stop a HTML5 canvas animation

Body:
How can I stop this html5 canvas animation after 5 sec?

I'm a beginner with html5 canvas. I have tried all the code I know but it keeps playing or break.

Maybe there is a easy solution for this.

EDIT:      after 5 sec the cycle production should stop but the animation
  should continue.

Any help is highly appreciated!

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

var c = document.getElementById('canv'),
    $ = c.getContext('2d');

    c.width = window.innerWidth;
    c.height = window.innerHeight;

window.addEventListener('resize', function(){
    c.width = window.innerWidth;
    c.height = window.innerHeight;
}, false);

var arr = [];

var go = function() {
  $.fillStyle = "hsla(0,0%,10%,.8)";
  $.fillRect(0, 0, c.width, c.height);

  var p = new Part(c.width/2 , c.height);
  p.vx = Math.random() * 10-5;
  arr.push(p);

  for (var i in arr) {
    var p = arr[i];
    p.disp($);
    p.upd();
  }

  if (arr.length > 500) {
    arr.shift();
  }
}

var rnd = function(min, max) {
  return Math.random() * (max - min) + min;
}

var Part = function(px, py) {
  this.px = px;
  this.py = py;
  this.vy = rnd(1.1, 2)*-8*1.1;
  this.vx = rnd(1.1, 2)*5*1.1;

  this.grav = 0.1;
  this.col = 0;
  this.rad = rnd(5,30);
  this.disp = function($) {
    $.fillStyle = "hsla(" + this.col + ", 95%, 60%, .8)";
    $.beginPath();
    $.arc(this.px, this.py, this.rad, 0, Math.PI*2);
    $.fill();
  }

    this.upd = function() {
      this.vy += this.grav;
      this.py += this.vy*1.1;
      this.px += this.vx* 1.1;
      this.col += 2;
  }
}

var run = function() {
  window.requestAnimFrame(run);
  go();

}
run();

body{
  width:100%;
  margin:0;
  overflow:hidden;
  background:hsla(0,0%,10%,1);
}

<canvas id = 'canv'></canvas>

Body:
This snippet will stop new bubbles from being created after 5 seconds yet will still show the remaining animation.

The key is to create a condition around the code where you call the generation of new items. With a global variable time_switch the condition can be used in other functions. The timer and function are as follows:

var time_switch = 0;
window.setTimeout("pauser();",5000);
function pauser() {
  time_switch = 1;
}

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000);
    };
})();

var c = document.getElementById('canv'),
    $ = c.getContext('2d');

    c.width = window.innerWidth;
    c.height = window.innerHeight;

window.addEventListener('resize', function(){
    c.width = window.innerWidth;
    c.height = window.innerHeight;
}, false);

var arr = [];

var go = function() {

    $.fillStyle = "hsla(0,0%,10%,.8)";
    $.fillRect(0, 0, c.width, c.height);

   if (time_switch !== 1) {
      var p = new Part(c.width/2 , c.height);
      p.vx = Math.random() * 10-5;
      arr.push(p);
    }

    for (var i in arr) {
      var p = arr[i];
      p.disp($);
      p.upd();
    }

    if (arr.length > 500) {
      arr.shift();
    }

}

var rnd = function(min, max) {
  return Math.random() * (max - min) + min;
}

var Part = function(px, py) {
  this.px = px;
  this.py = py;
  this.vy = rnd(1.1, 2)*-8*1.1;
  this.vx = rnd(1.1, 2)*5*1.1;

  this.grav = 0.1;
  this.col = 0;
  this.rad = rnd(5,30);
  this.disp = function($) {
    $.fillStyle = "hsla(" + this.col + ", 95%, 60%, .8)";
    $.beginPath();
    $.arc(this.px, this.py, this.rad, 0, Math.PI*2);
    $.fill();
  }

    this.upd = function() {
      this.vy += this.grav;
      this.py += this.vy*1.1;
      this.px += this.vx* 1.1;
      this.col += 2;
  }
}
var time_switch = 0;
window.setTimeout("pauser();",5000);
function pauser() {
  time_switch = 1;
}
var run = function() {
  //if (time_switch !== 1) {
    window.requestAnimFrame(run);
  //}

  go();

}
run();

body{
  width:100%;
  margin:0;
  overflow:hidden;
  background:hsla(0,0%,10%,1);
}

<canvas id = 'canv'></canvas>


问:
Ruby - producing a combination from two arrays *produces headache*
What I'm trying to do is take an array of service names and apply a service response of either true of false to each.

Basically I'm getting an xml with a set of booleans for each of the services checked.  So for this example they all came back as true.

I put them into an array using Nokogiri like so:

```<code>doc = Nokogiri::XML.parse(xml)
service_state = doc.css("HeartBeat Status").map(&:text)
</code>```

This results in an array with 3 ["true"] items.

What I need to is apply each of them sequentially with an array I have in the code.

```<code>name = ['svc1', 'svc2', 'svc3']
</code>```

To do this I used the following code:

```<code>status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status.each {|state| print state.to_s + "\n"}
</code>```

This does what I want... sort of...

I do get an output of:

["svc1", "true"]
["svc2", "true"]
["svc3", "true"]

However, it repeats all the possible combinations.
When applying this to the actual array I have a total of 13 services that have a response 17 times so I end up with an array with 221 items.

Question: How do I do what I'm doing now but without repeating for each item in both arrays?

Thanks!

答:
I was looking for a much more complicated answer than I needed.

This snippet gave me what I needed.  :P

```<code>status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status = status.uniq
status.each {|state| print state.to_s + "\n"}
</code>```

Body:
What I'm trying to do is take an array of service names and apply a service response of either true of false to each.

Basically I'm getting an xml with a set of booleans for each of the services checked.  So for this example they all came back as true.

I put them into an array using Nokogiri like so:

doc = Nokogiri::XML.parse(xml)
service_state = doc.css("HeartBeat Status").map(&:text)

This results in an array with 3 ["true"] items.

What I need to is apply each of them sequentially with an array I have in the code.

name = ['svc1', 'svc2', 'svc3']

To do this I used the following code:

status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status.each {|state| print state.to_s + "\n"}

This does what I want... sort of...

I do get an output of:

["svc1", "true"]
["svc2", "true"]
["svc3", "true"]

However, it repeats all the possible combinations.
When applying this to the actual array I have a total of 13 services that have a response 17 times so I end up with an array with 221 items.

Question: How do I do what I'm doing now but without repeating for each item in both arrays?

Thanks!

Body:
I was looking for a much more complicated answer than I needed.

This snippet gave me what I needed.  :P

status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status = status.uniq
status.each {|state| print state.to_s + "\n"}


问:
User inserting pictures in excel with macro
I'm a bit stuck on this one, since I couldn't find much on the web. Basically, I'd like the user to be able to click a button which formats some cells, and then opens a box which makes the user navigate through windows explorer in order to insert one or two pictures in the newly formatted cells.

This is what I have so far:

```<code>Private Sub AddPic_Click()
    Dim lastCell As Range
    Dim newCell1 As Range
    Dim newCell2 As Range
    Dim newCellMergePic1 As Range
    Dim newCellMergePic2 As Range
    Dim myRange As Range

    Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

    For Each r In myRange
        If r.MergeCells Then
            Set lastCell = r
        End If
    Next r

    Set newCell1 = lastCell.Offset(1, 0)
    Set newCell2 = newCell1.Offset(0, 5)

    Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
    Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))

    newCellMergePic1.Merge
    newCellMergePic2.Merge

    With newCellMergePic1
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With

    With newCellMergePic2
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With
End Sub
</code>```

It works, but I don't know how to integrate the feature which allows the user to navigate through their folders in order to select the picture(s) they want to add. Thank you for the taking the time to read my post.

答:
Problem solved, here is the final result</p>

```<code>Private Sub AddPic_Click()

Dim lastCell As Range

Dim newCell1 As Range
Dim newCell2 As Range

Dim newCellMergePic1 As Range
Dim newCellMergePic2 As Range

Dim myRange As Range

Dim fd As Office.FileDialog

Dim Pic1 As Picture
Dim Pic2 As Picture

Dim Pic1Path As String
Dim Pic2Path As String

Set fd = Application.FileDialog(msoFileDialogFilePicker)

Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

For Each r In myRange
    If r.MergeCells Then
        Set lastCell = r
    End If
Next r

Set newCell1 = lastCell.Offset(1, 0)
Set newCell2 = newCell1.Offset(0, 5)

Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))

newCellMergePic1.Merge
newCellMergePic2.Merge

With newCellMergePic1
    .Font.Name = "Calibri"
    .Font.Color = vbBlack
    .VerticalAlignment = xlVAlignCenter
    .HorizontalAlignment = xlHAlignCenter
    .Font.Bold = True
    .Value = "Picture Here"
End With

With newCellMergePic2
    .Font.Name = "Calibri"
    .Font.Color = vbBlack
    .VerticalAlignment = xlVAlignCenter
    .HorizontalAlignment = xlHAlignCenter
    .Font.Bold = True
    .Value = "Picture Here"
End With

With fd

    .AllowMultiSelect = True
    .Title = "Please select picture(s). Maximum of two pictures per insert."
    .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1

    If .Show = True Then

        If .SelectedItems.Count > 2 Then

            MsgBox "Please select no more than 2 pictures at once.", vbExclamation, Conflict

                        Dim delRange1 As Excel.Range
                        Dim delRange2 As Excel.Range

                        Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

                        For Each r In myRange
                            If r.MergeCells Then
                                Set lastCell = r
                            End If
                        Next r

                        If lastCell.Address <> Range("A2").Address Then

                            Set lastCell2 = lastCell.Offset(0, 5)

                            Set delRange1 = lastCell.MergeArea
                            Set delRange2 = lastCell2.MergeArea

                            delRange1.ClearContents
                            delRange2.ClearContents

                            lastCell.UnMerge
                            lastCell2.UnMerge

                            Exit Sub

            End If

        End If

        Pic1Path = .SelectedItems(1)

        Set Pic1 = Pictures.Insert(Pic1Path)

        With Pic1.ShapeRange
            .LockAspectRatio = msoTrue
            .Height = newCellMergePic1.Height - 2
            .Top = newCellMergePic1.Top + 1
            .Left = newCellMergePic1.Left
        End With

        If .SelectedItems.Count = 2 Then
            Pic2Path = .SelectedItems(2)
            Set Pic2 = Pictures.Insert(Pic2Path)

            With Pic2.ShapeRange
                .LockAspectRatio = msoTrue
                .Height = newCellMergePic2.Height - 2
                .Top = newCellMergePic2.Top + 1
                .Left = newCellMergePic2.Left
            End With

        End If

    End If

End With

End Sub
</code>```

Body:
I'm a bit stuck on this one, since I couldn't find much on the web. Basically, I'd like the user to be able to click a button which formats some cells, and then opens a box which makes the user navigate through windows explorer in order to insert one or two pictures in the newly formatted cells.

This is what I have so far:

Private Sub AddPic_Click()
    Dim lastCell As Range
    Dim newCell1 As Range
    Dim newCell2 As Range
    Dim newCellMergePic1 As Range
    Dim newCellMergePic2 As Range
    Dim myRange As Range

    Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

    For Each r In myRange
        If r.MergeCells Then
            Set lastCell = r
        End If
    Next r

    Set newCell1 = lastCell.Offset(1, 0)
    Set newCell2 = newCell1.Offset(0, 5)

    Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
    Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))

    newCellMergePic1.Merge
    newCellMergePic2.Merge

    With newCellMergePic1
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With

    With newCellMergePic2
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With
End Sub

It works, but I don't know how to integrate the feature which allows the user to navigate through their folders in order to select the picture(s) they want to add. Thank you for the taking the time to read my post.

Body:
Problem solved, here is the final result

Private Sub AddPic_Click()

Dim lastCell As Range

Dim newCell1 As Range
Dim newCell2 As Range

Dim newCellMergePic1 As Range
Dim newCellMergePic2 As Range

Dim myRange As Range

Dim fd As Office.FileDialog

Dim Pic1 As Picture
Dim Pic2 As Picture

Dim Pic1Path As String
Dim Pic2Path As String

Set fd = Application.FileDialog(msoFileDialogFilePicker)

Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

For Each r In myRange
    If r.MergeCells Then
        Set lastCell = r
    End If
Next r

Set newCell1 = lastCell.Offset(1, 0)
Set newCell2 = newCell1.Offset(0, 5)

Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))

newCellMergePic1.Merge
newCellMergePic2.Merge

With newCellMergePic1
    .Font.Name = "Calibri"
    .Font.Color = vbBlack
    .VerticalAlignment = xlVAlignCenter
    .HorizontalAlignment = xlHAlignCenter
    .Font.Bold = True
    .Value = "Picture Here"
End With

With newCellMergePic2
    .Font.Name = "Calibri"
    .Font.Color = vbBlack
    .VerticalAlignment = xlVAlignCenter
    .HorizontalAlignment = xlHAlignCenter
    .Font.Bold = True
    .Value = "Picture Here"
End With

With fd

    .AllowMultiSelect = True
    .Title = "Please select picture(s). Maximum of two pictures per insert."
    .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1

    If .Show = True Then

        If .SelectedItems.Count > 2 Then

            MsgBox "Please select no more than 2 pictures at once.", vbExclamation, Conflict

                        Dim delRange1 As Excel.Range
                        Dim delRange2 As Excel.Range

                        Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

                        For Each r In myRange
                            If r.MergeCells Then
                                Set lastCell = r
                            End If
                        Next r

                        If lastCell.Address <> Range("A2").Address Then

                            Set lastCell2 = lastCell.Offset(0, 5)

                            Set delRange1 = lastCell.MergeArea
                            Set delRange2 = lastCell2.MergeArea

                            delRange1.ClearContents
                            delRange2.ClearContents

                            lastCell.UnMerge
                            lastCell2.UnMerge

                            Exit Sub

            End If

        End If

        Pic1Path = .SelectedItems(1)

        Set Pic1 = Pictures.Insert(Pic1Path)

        With Pic1.ShapeRange
            .LockAspectRatio = msoTrue
            .Height = newCellMergePic1.Height - 2
            .Top = newCellMergePic1.Top + 1
            .Left = newCellMergePic1.Left
        End With

        If .SelectedItems.Count = 2 Then
            Pic2Path = .SelectedItems(2)
            Set Pic2 = Pictures.Insert(Pic2Path)

            With Pic2.ShapeRange
                .LockAspectRatio = msoTrue
                .Height = newCellMergePic2.Height - 2
                .Top = newCellMergePic2.Top + 1
                .Left = newCellMergePic2.Left
            End With

        End If

    End If

End With

End Sub


问:
Model inheritance in Laravel without plugins
What i am trying to achieve is a base model that has certain fields and sub models that have even more custom fields. I found some hacky solutions that used a field in the table to define the subtype, but that does not feel right.

So here is an example of what i need:
I have a model Pet that has common fields like name, age, gender. However, i do not wanna use this model directly (so it is okay if it is e.g. abstract).

Then i have sub models like for example:

Bird that has the field lengthOfWings

Spider that has numberOfEyes

Dog that has breed

How can this be done cleanly?

答:
If your model Pet extends laravel's model class, you can't define it abstract, and i don't think you want to implement it from scratch

If i understand right, the cleanest way i could think of would be

```<code>Pet Model
    +--------+----------+--------------------+
    |     id | name     | oder_general_field |
    +--------+----------+--------------------+
    |      1 |      dog |               value|
    |      2 |      cat |               value|
    |      3 |     bird |               value|
    +--------+----------+--------------------+

Subtype model

    +------------+----------+
    | subtype_id | name     |
    +------------+----------+
    |      1     |mammal    |
    |      2     |not_mammal|
    +------------+----------+

  Mammal model

  +---+--------+----------+------------+
  |id | pet_id | field1   | field2     |
  +---+--------+----------+------------+
  | 1 |      1 |    value |       value|
  | 2 |      2 |    value |       value|
  +---+--------+----------+------------+

  Not_Mammal model

   +----+--------+----------+------------+
   | id | pet_id | field1   | field2     |
   +----+--------+----------+------------+
   | 1  |      3 |    value |       value|
   +----+--------+----------+------------+
</code>```

The subtype model here is not used in the relationship, but i would recommend to keep it, and whenever you add a new model add it's name there too, if you will have like 100 submodels trust me it will help you

Then you will have to define the relationships between models

```<code>Class Mammal Extends Model{
     public function pet(){
        return $this->belongsTo('App\Pet');
     }
}

Class Not_Mammal Extends Model{
     public function pet(){
        return $this->belongsTo('App\Pet');
     }
}
</code>```

Body:
If your model Pet extends laravel's model class, you can't define it abstract, and i don't think you want to implement it from scratch

If i understand right, the cleanest way i could think of would be

Pet Model
    +--------+----------+--------------------+
    |     id | name     | oder_general_field |
    +--------+----------+--------------------+
    |      1 |      dog |               value|
    |      2 |      cat |               value|
    |      3 |     bird |               value|
    +--------+----------+--------------------+

Subtype model

    +------------+----------+
    | subtype_id | name     |
    +------------+----------+
    |      1     |mammal    |
    |      2     |not_mammal|
    +------------+----------+

  Mammal model

  +---+--------+----------+------------+
  |id | pet_id | field1   | field2     |
  +---+--------+----------+------------+
  | 1 |      1 |    value |       value|
  | 2 |      2 |    value |       value|
  +---+--------+----------+------------+

  Not_Mammal model

   +----+--------+----------+------------+
   | id | pet_id | field1   | field2     |
   +----+--------+----------+------------+
   | 1  |      3 |    value |       value|
   +----+--------+----------+------------+

The subtype model here is not used in the relationship, but i would recommend to keep it, and whenever you add a new model add it's name there too, if you will have like 100 submodels trust me it will help you

Then you will have to define the relationships between models

Class Mammal Extends Model{
     public function pet(){
        return $this->belongsTo('App\Pet');
     }
}

Class Not_Mammal Extends Model{
     public function pet(){
        return $this->belongsTo('App\Pet');
     }
}


问:
MySQL - Delete a row witha condintion
I got a zoo DB and I have to delete a row when a container does not have a animal inside it. I tryied this:

```<code>DELETE FROM container
WHERE (SELECT COUNT(NameAnimal), NameContainer
FROM animal, container
WHERE container.CodContainer =
animal.CodContainer AND
animal.CodContainer =
container.CodContainer
GROUP BY container.CodContainer) = 0;`
</code>```

And i got this error:

```<code>`Operand should contain 2 column(s)e`
</code>```

Any ideas?

答: Your problem is your where clause. You are getting the count of NameAnimal and the NameContainer and checking if they are equal to 0. This cannot work as you are taking two columns and then seeing if they are equal to a single 0. I assume you probably want to delete the part of the select statement with NameContainer to fix your problem.</p>

Title: MySQL - Delete a row witha condintion

Body:
I got a zoo DB and I have to delete a row when a container does not have a animal inside it. I tryied this:

DELETE FROM container
WHERE (SELECT COUNT(NameAnimal), NameContainer
FROM animal, container
WHERE container.CodContainer =
animal.CodContainer AND
animal.CodContainer =
container.CodContainer
GROUP BY container.CodContainer) = 0;`

And i got this error:

`Operand should contain 2 column(s)e`

Any ideas?


问:
How to filter on most recent value for specific column
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

```<code>Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC
</code>```

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

```<code>    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40
</code>```

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

答:
Are you looking for most recent batch and rundate record then you can query as below:

```<code>Select top 1 [batchNum], [RunDate], [tableName], [numberofRows], [dataSize]
   From yourtable
   Order by BatchNum desc, RunDate desc
</code>```

If you are looking for recent RunDate record for every batch then you can query as below:

```<code>Select top(1) with ties [batchNum], [RunDate], [tableName], [numberofRows], [dataSize] From yourtable
   Order by row_number() over(partition by BatchNum order by RunDate desc)
</code>```

Body:
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

Body:
Are you looking for most recent batch and rundate record then you can query as below:

Select top 1 [batchNum], [RunDate], [tableName], [numberofRows], [dataSize]
   From yourtable
   Order by BatchNum desc, RunDate desc

If you are looking for recent RunDate record for every batch then you can query as below:

Select top(1) with ties [batchNum], [RunDate], [tableName], [numberofRows], [dataSize] From yourtable
   Order by row_number() over(partition by BatchNum order by RunDate desc)


问:
Select multiple/random elements from an arraylist
How would I select random elements from an array list, except for one element?
Here's my arraylist:

```<code>ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");
</code>```

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

```<code> for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }
</code>```

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

答:
```<code>ArrayList <String> provinces = new ArrayList<>();
String removeValue = null;
Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");

for (Iterator<String> iterator = provinces.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.equals("Saskatchewan")) {
        removeValue = value;
        iterator.remove();
    }
}

Collections.shuffle(provinces);

for(String p: provinces){
    System.out.println(p);
}

provinces.add(removeValue);
</code>```

I used Iterator because enhanced for loop did not work with remove() but without Iterator you can also loop using indexes(numbers).

Without Iterator:

```<code>for (int j = 0; j<provinces.size(); j++) {
    if(provinces.get(j).equals("Saskatchewan")){
        removeValue = provinces.get(j);
        provinces.remove(provinces.get(j));
    }
}
</code>```

Also without using Collections.shuffle() you can create your own method. To do that have a look at this question.

Body:
How would I select random elements from an array list, except for one element?
Here's my arraylist:

ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

 for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

Body:
ArrayList <String> provinces = new ArrayList<>();
String removeValue = null;
Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");

for (Iterator<String> iterator = provinces.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.equals("Saskatchewan")) {
        removeValue = value;
        iterator.remove();
    }
}

Collections.shuffle(provinces);

for(String p: provinces){
    System.out.println(p);
}

provinces.add(removeValue);

I used Iterator because enhanced for loop did not work with remove() but without Iterator you can also loop using indexes(numbers).

Without Iterator:

for (int j = 0; j<provinces.size(); j++) {
    if(provinces.get(j).equals("Saskatchewan")){
        removeValue = provinces.get(j);
        provinces.remove(provinces.get(j));
    }
}

Also without using Collections.shuffle() you can create your own method. To do that have a look at this question.


问:
How to copy a file on the FTP server to a directory on the same server in Java?
I'm using Apache Commons FTP to upload a file. Before uploading I want to check if the file already exists on the server and make a backup from it to a backup directory on the same server.

Does anyone know how to copy a file from a FTP server to a backup directory on the same server?

```<code>public static void uploadWithCommonsFTP(File fileToBeUpload){
    FTPClient f = new FTPClient();
    FTPFile backupDirectory;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        FTPFile[] files = f.listFiles();
        for(FTPFile file:directories){
            if (!file.getName().equalsIgnoreCase("backup")) {
                backupDirectory=file;
            } else {
               f.makeDirectory("backup");
            }
        }
        for(FTPFile file: files){
            if(file.getName().equals(fileToBeUpload.getName())){
                //copy file to backupDirectory
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}
</code>```

Edited code: still there is a problem,  when i backup zip file, the backup-ed file is corrupted.

Does any body know the reason for it?

```<code> public static void backupUploadWithCommonsFTP(File fileToBeUpload) {
    FTPClient f = new FTPClient();
    boolean backupDirectoryExist = false;
    boolean fileToBeUploadExist = false;
    FTPFile backupDirectory = null;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        // Check for existence of backup directory
        for (FTPFile file : directories) {
            String filename = file.getName();
            if (file.isDirectory() && filename.equalsIgnoreCase("backup")) {
                backupDirectory = file;
                backupDirectoryExist = true;
                break;
            }
        }
        if (!backupDirectoryExist) {
            f.makeDirectory("backup");
        }
        // Check if file already exist on the server
        f.changeWorkingDirectory("files");
        FTPFile[] files = f.listFiles();
        f.changeWorkingDirectory("backup");
        String filePathToBeBackup="/home/user/backup/";
        String prefix;
        String suffix;
        String fileNameToBeBackup;
        FTPFile fileReadyForBackup = null;
        f.setFileType(FTP.BINARY_FILE_TYPE);
        f.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        for (FTPFile file : files) {
            if (file.isFile() && file.getName().equals(fileToBeUpload.getName())) {
                prefix = FilenameUtils.getBaseName(file.getName());
                suffix = ".".concat(FilenameUtils.getExtension(file.getName()));
                fileNameToBeBackup = prefix.concat(Calendar.getInstance().getTime().toString().concat(suffix));
                filePathToBeBackup = filePathToBeBackup.concat(fileNameToBeBackup);
                fileReadyForBackup = file;
                fileToBeUploadExist = true;
                break;
            }
        }
        // If file already exist on the server create a backup from it otherwise just upload the file.
        if(fileToBeUploadExist){
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            f.retrieveFile(fileReadyForBackup.getName(), outputStream);
            InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
            if(f.storeUniqueFile(filePathToBeBackup, is)){
                JOptionPane.showMessageDialog(null, "Backup succeeded.");
                f.changeWorkingDirectory("files");
                boolean reply = f.storeFile(fileToBeUpload.getName(), new FileInputStream(fileToBeUpload));
                if(reply){
                    JOptionPane.showMessageDialog(null,"Upload succeeded.");
                }else{
                    JOptionPane.showMessageDialog(null,"Upload failed after backup.");
                }
            }else{
                JOptionPane.showMessageDialog(null,"Backup failed.");
            }
        }else{
            f.changeWorkingDirectory("files");
            f.setFileType(FTP.BINARY_FILE_TYPE);
            f.enterLocalPassiveMode();
            InputStream inputStream = new FileInputStream(fileToBeUpload);
            ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(fileToBeUpload));
            boolean reply = f.storeFile(fileToBeUpload.getName(), in);
            System.out.println("Reply code for storing file to server: " + reply);
            if(!f.completePendingCommand()) {
                f.logout();
                f.disconnect();
                System.err.println("File transfer failed.");
                System.exit(1);
            }
            if(reply){

                JOptionPane.showMessageDialog(null,"File uploaded successfully without making backup." +
                        "\nReason: There wasn't any previous version of this file.");
            }else{
                JOptionPane.showMessageDialog(null,"Upload failed.");
            }
        }
        //Logout and disconnect from server
        in.close();
        f.logout();
        f.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
</code>```

答:
To backup at same Server (move), can you use:</p>

```<code>String source="/home/user/some";
String goal  ="/home/user/someOther";
FTPFile[] filesFTP = cliente.listFiles(source);

clientFTP.changeWorkingDirectory(goal);  // IMPORTANT change to final directory

for (FTPFile f : archivosFTP)
   {
    if(f.isFile())
       {
        cliente.rename(source+"/"+f.getName(), f.getName());
       }
   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Apache Commons FTP to upload a file. Before uploading I want to check if the file already exists on the server and make a backup from it to a backup directory on the same server.

Does anyone know how to copy a file from a FTP server to a backup directory on the same server?

public static void uploadWithCommonsFTP(File fileToBeUpload){
    FTPClient f = new FTPClient();
    FTPFile backupDirectory;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        FTPFile[] files = f.listFiles();
        for(FTPFile file:directories){
            if (!file.getName().equalsIgnoreCase("backup")) {
                backupDirectory=file;
            } else {
               f.makeDirectory("backup");
            }
        }
        for(FTPFile file: files){
            if(file.getName().equals(fileToBeUpload.getName())){
                //copy file to backupDirectory
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

Edited code: still there is a problem,  when i backup zip file, the backup-ed file is corrupted.

Does any body know the reason for it?

 public static void backupUploadWithCommonsFTP(File fileToBeUpload) {
    FTPClient f = new FTPClient();
    boolean backupDirectoryExist = false;
    boolean fileToBeUploadExist = false;
    FTPFile backupDirectory = null;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        // Check for existence of backup directory
        for (FTPFile file : directories) {
            String filename = file.getName();
            if (file.isDirectory() && filename.equalsIgnoreCase("backup")) {
                backupDirectory = file;
                backupDirectoryExist = true;
                break;
            }
        }
        if (!backupDirectoryExist) {
            f.makeDirectory("backup");
        }
        // Check if file already exist on the server
        f.changeWorkingDirectory("files");
        FTPFile[] files = f.listFiles();
        f.changeWorkingDirectory("backup");
        String filePathToBeBackup="/home/user/backup/";
        String prefix;
        String suffix;
        String fileNameToBeBackup;
        FTPFile fileReadyForBackup = null;
        f.setFileType(FTP.BINARY_FILE_TYPE);
        f.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        for (FTPFile file : files) {
            if (file.isFile() && file.getName().equals(fileToBeUpload.getName())) {
                prefix = FilenameUtils.getBaseName(file.getName());
                suffix = ".".concat(FilenameUtils.getExtension(file.getName()));
                fileNameToBeBackup = prefix.concat(Calendar.getInstance().getTime().toString().concat(suffix));
                filePathToBeBackup = filePathToBeBackup.concat(fileNameToBeBackup);
                fileReadyForBackup = file;
                fileToBeUploadExist = true;
                break;
            }
        }
        // If file already exist on the server create a backup from it otherwise just upload the file.
        if(fileToBeUploadExist){
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            f.retrieveFile(fileReadyForBackup.getName(), outputStream);
            InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
            if(f.storeUniqueFile(filePathToBeBackup, is)){
                JOptionPane.showMessageDialog(null, "Backup succeeded.");
                f.changeWorkingDirectory("files");
                boolean reply = f.storeFile(fileToBeUpload.getName(), new FileInputStream(fileToBeUpload));
                if(reply){
                    JOptionPane.showMessageDialog(null,"Upload succeeded.");
                }else{
                    JOptionPane.showMessageDialog(null,"Upload failed after backup.");
                }
            }else{
                JOptionPane.showMessageDialog(null,"Backup failed.");
            }
        }else{
            f.changeWorkingDirectory("files");
            f.setFileType(FTP.BINARY_FILE_TYPE);
            f.enterLocalPassiveMode();
            InputStream inputStream = new FileInputStream(fileToBeUpload);
            ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(fileToBeUpload));
            boolean reply = f.storeFile(fileToBeUpload.getName(), in);
            System.out.println("Reply code for storing file to server: " + reply);
            if(!f.completePendingCommand()) {
                f.logout();
                f.disconnect();
                System.err.println("File transfer failed.");
                System.exit(1);
            }
            if(reply){

                JOptionPane.showMessageDialog(null,"File uploaded successfully without making backup." +
                        "\nReason: There wasn't any previous version of this file.");
            }else{
                JOptionPane.showMessageDialog(null,"Upload failed.");
            }
        }
        //Logout and disconnect from server
        in.close();
        f.logout();
        f.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Body:
To backup at same Server (move), can you use:

String source="/home/user/some";
String goal  ="/home/user/someOther";
FTPFile[] filesFTP = cliente.listFiles(source);

clientFTP.changeWorkingDirectory(goal);  // IMPORTANT change to final directory

for (FTPFile f : archivosFTP)
   {
    if(f.isFile())
       {
        cliente.rename(source+"/"+f.getName(), f.getName());
       }
   }


问:
Render Javascript in Angular2
I am new to angular and am trying to configure paypal. This is the javascript that I want to use.

https://developer.paypal.com/demo/checkout/#/pattern/client

When I copy paste the script body into html, nothing comes up.

I tried to put the script in the ng-onit function but I'm not really sure how to do it..

component.js

```<code>    ngOnInit = function ()
    {
    paypal.Button.render({

        ...
</code>```

html

```<code>  <script src="https://www.paypalobjects.com/api/checkout.js"></script>
 div id="paypal-button-container"></div
</code>```

Am I suppose to put the script reference somewhere else in component.js??

Thanks

答:
Here is working Plunker

You can't simply import stuff (in this case PayPal API) when you include JavaScript in HTML page as script. But once you do that, browser will load that script when page is being loaded. As per documentation example, it is said that after script is loaded global paypal object will be available. To use global object which is available before or not managed by Angular, we can hack it like:

```<code>declare var paypal: any;
</code>```

Then you can use it in your TypeScripts. Since this 3rd party script will do some rendering, may be it is good idea to put its initialization in ngAfterViewInit life-cycle hook.

Title: Render Javascript in Angular2

Body:
I am new to angular and am trying to configure paypal. This is the javascript that I want to use.

https://developer.paypal.com/demo/checkout/#/pattern/client

When I copy paste the script body into html, nothing comes up.

I tried to put the script in the ng-onit function but I'm not really sure how to do it..

component.js

    ngOnInit = function ()
    {
    paypal.Button.render({

        ...

html

 div id="paypal-button-container"></div

Am I suppose to put the script reference somewhere else in component.js??

Thanks

Body:
Here is working Plunker

You can't simply import stuff (in this case PayPal API) when you include JavaScript in HTML page as script. But once you do that, browser will load that script when page is being loaded. As per documentation example, it is said that after script is loaded global paypal object will be available. To use global object which is available before or not managed by Angular, we can hack it like:

declare var paypal: any;

Then you can use it in your TypeScripts. Since this 3rd party script will do some rendering, may be it is good idea to put its initialization in ngAfterViewInit life-cycle hook.


问:
Adb over wireless without usb cable at all for not rooted phones
I want to debug Android APPs on my phone (LG nexus 4). I'm travelling and I forgot my USB cable. When I work at home I can do it just connecting the USB cable and executing the command 'adb tcpip 5555'. Then I can unplug the USB cable and connect via 'adb connect IP'.

But now I cannot execute the first command because I don't have a cable. I don't understand why I have to do it every time, since I already execute the 'adb tcpip' command before.

What I tried now:

I installed a terminal application on my Android and tried to execute that command there, but I received a "device not found" error. Maybe he cannot see himself...

I search for any reasonable option in "Android Development Options" and enabled everything seemed to have relation with Wifi. But nothing helped.

I search StackOverflow, but all answers I found involving connect via USB cable before. Is there I way to do this connection without the need of a cable at all?

Some info:
My Nexus 4 isn't rooted.
The android version is 5.1.1.

答:
For your question

Adb over wireless without USB cable at all for not rooted phones.

Old Answer:

You need to connect your device to your computer via USB cable. Make sure USB debugging is working. You can check if it shows up when running adb devices.

Open cmd in ...\AppData\Local\Android\sdk\platform-tools

Step1: Run adb devices

Ex: C:\pathToSDK\platform-tools>adb devices

You can check if it shows up when running adb devices.

Step2: Run adb tcpip 5555

Ex: C:\pathToSDK\platform-tools>adb tcpip 5555

Disconnect your device (remove the USB cable).

Step3: Go to the Settings -> About phone -> Status to view the IP address of your phone.

Step4: Run adb connect <IP address of your device>:5555

Ex: C:\pathToSDK\platform-tools>adb connect 192.168.0.2

Step5: Run adb devices again, you should see your device.

Now you can execute adb commands or use your favorite IDE for android development - wireless!

Now you might ask, what do I have to do when I move into a different workspace and change WiFi networks? You do not have to repeat steps 1 to 3 (these set your phone into WiFi-debug mode). You do have to connect to your phone again by executing steps 4 to 6.

Unfortunately, the android phones lose the WiFi-debug mode when restarting. Thus, if your battery died, you have to start over. Otherwise, if you keep an eye on your battery and do not restart your phone, you can live without a cable for weeks!

See here for more

Ref: https://futurestud.io/tutorials/how-to-debug-your-android-app-over-wifi-without-root

UPDATE 1:

If you set C:\pathToSDK\platform-tools this path in Environment variables then there is no need to repeat all steps, you can simply use only Step 4 that's it, it will connect to your device.

To set a path:
My Computer-> Right click--> properties -> Advanced system settings -> Environment variables -> edit path in System variables -> paste the platform-tools path in variable value -> ok -> ok -> ok

UPDATE 2:

Go to the android terminal

adb tcpip 5555

adb connect your_ip_address

We can do it without a USB cable at all in the following ways.

NEW UPDATE 1: (Latest Answer without using USB cable at all)

Note: It will work only when your laptop and mobile should connect to the same WiFi.

Step 1: In Android studio choose "Pair Devices Using Wi-Fi" from the Device Connections dropdown.

Step 2: In Mobile go to settings and search for "Pair using QR code" and scan the QR code

NEW UPDATE 2: (Latest Answer without using USB cable at all)

Note: It will work only when your laptop and mobile should connect to the same WiFi.

Go to developer options from the mobile settings and enable Wireless Debugging

That's it!


Title: transforming a string into a list in python

Body:
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

['[', '1', ',', '2', ',', '3', ',', '4', ']']

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

[1,2,3,4]

but I don't know how to get that output into a variable, can someone help?

Body:
In [1]: import json

In [2]: s = "[1,2,3,4]"

In [3]: json.loads(s)
Out[3]: [1, 2, 3, 4]