问:
Ionic Framework - Angular html include
I'm building an app with the Ionic Framework. I'm using a tab navigation.

```<code>angular.module('myapp', ['ionic'])

.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider
    .state('tabs', {
        url: "/tab",
        abstract: true,
        templateUrl: "templates/tabs.html"
    })
    .state('tabs.home', {
        url: "/home",
        views: {
            'home-tab': {
                templateUrl: "templates/home.html",
                controller: 'HomeTabCtrl'
            }
        }
    })
    .state('tabs.news', {
        url: "/news",
        views: {
            'news-tab': {
                templateUrl: "templates/news.html"
            }
        }
    })....
</code>```

First I wrote all code in 1 html file, then for better oversight I wanted to use html include:

```<code><body>
<!-- Layout Setup -->
<ion-nav-bar class="bar-app"></ion-nav-bar>
<ion-nav-view></ion-nav-view>

<script id="templates/tabs.html" type="text/ng-template">
    <div ng-include="'sub/tabs.html'"></div>
</script>

<script id="templates/home.html" type="text/ng-template">
    <div ng-include="'sub/home.html'"></div>
</script>

<script id="templates/news.html" type="text/ng-template">
    <div ng-include="'sub/news.html'"></div>
</script>
....
</code>```

home.html:

```<code><ion-view view-title="" hide-nav-bar="true">
    <ion-content class="padding app-home" scroll="false">
        <div class="app-image">
            <img class="full-image" src="img/app-logo.svg">
        </div>
        <div class="row app-home-buttons">
            <div class="col">
                <a href="#/tab/news">
                    <button class="button button-balanced button-block icon-top"><i class='icon ion-ios-paper-outline'></i><span>News</span>
                    </button>
                </a>
            </div>
    </ion-content>
</ion-view>
</code>```

news.html:

```<code><ion-view view-title="News" ng-controller="NewsRefreshCtrl">
    <ion-content class="">
        <ion-refresher on-refresh="doRefresh()">

        </ion-refresher>
        <div class="list">

            <a class="item item-thumbnail-left item-text-wrap" href="#">
                <img src="img/tile-icon.png">
                <h2>Lorem consetetur sadipscing</h2>
                <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At v</p>
            </a>
            </a>

        </div>

    </ion-content>
</ion-view>
</code>```

Now I have the problem that the bar with the site title isn't working anymore. It doesn't show the title and the included html content is laying on top under the bar.
Maybe thats because due to the include it's in a div tag now?

How can I solve this?

答:
This is old, but the best solution was not posted.  I found the solution while I still had this open so I figured I'd contribute in case anyone else finds this.  You can simply use the ng-include directive as it's own tag

```<code><ion-slide-box>
                <ion-slide>
                    <ng-include src="'templates/slide1.html'"></ng-include>
                </ion-slide>
                <ion-slide>
                    <ng-include src="'templates/slide2.html'"></ng-include>
                </ion-slide>
                <ion-slide>
                    <ng-include src="'templates/slide3.html'"></ng-include>
                </ion-slide>
                <ion-slide>
                    <ng-include src="'templates/slide4.html'"></ng-include>
                </ion-slide>
</ion-slide-box>
</code>```

No need for ion-view in each slide.

Title: Ionic Framework - Angular html include

Body:
I'm building an app with the Ionic Framework. I'm using a tab navigation.

angular.module('myapp', ['ionic'])

.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider
    .state('tabs', {
        url: "/tab",
        abstract: true,
        templateUrl: "templates/tabs.html"
    })
    .state('tabs.home', {
        url: "/home",
        views: {
            'home-tab': {
                templateUrl: "templates/home.html",
                controller: 'HomeTabCtrl'
            }
        }
    })
    .state('tabs.news', {
        url: "/news",
        views: {
            'news-tab': {
                templateUrl: "templates/news.html"
            }
        }
    })....

First I wrote all code in 1 html file, then for better oversight I wanted to use html include:

<ion-nav-bar class="bar-app"></ion-nav-bar>
<ion-nav-view></ion-nav-view>

....

home.html:

<ion-view view-title="" hide-nav-bar="true">
    <ion-content class="padding app-home" scroll="false">

                    <button class="button button-balanced button-block icon-top">News
                    </button>

    </ion-content>
</ion-view>

news.html:

<ion-view view-title="News" ng-controller="NewsRefreshCtrl">
    <ion-content class="">
        <ion-refresher on-refresh="doRefresh()">

        </ion-refresher>

Lorem consetetur sadipscing

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At v

    </ion-content>
</ion-view>

Now I have the problem that the bar with the site title isn't working anymore. It doesn't show the title and the included html content is laying on top under the bar.
Maybe thats because due to the include it's in a div tag now?

How can I solve this?

Body:
This is old, but the best solution was not posted.  I found the solution while I still had this open so I figured I'd contribute in case anyone else finds this.  You can simply use the ng-include directive as it's own tag

<ion-slide-box>
                <ion-slide>
                    <ng-include src="'templates/slide1.html'"></ng-include>
                </ion-slide>
                <ion-slide>
                    <ng-include src="'templates/slide2.html'"></ng-include>
                </ion-slide>
                <ion-slide>
                    <ng-include src="'templates/slide3.html'"></ng-include>
                </ion-slide>
                <ion-slide>
                    <ng-include src="'templates/slide4.html'"></ng-include>
                </ion-slide>
</ion-slide-box>

No need for ion-view in each slide.


来源: stackexchange

问:
Change ng-click function attribute. In Angular.js
I have a function defined in a directive called old(), currently the button executes this function when clicking. I want when the directive is loaded, the old() function was changed to the new() function. The new function, would receive by parameter (this.form) ("form" is the name of my form).
I've tried this, but it

```<code>attrs.$set('ngClick', 'new(this.form)');
</code>```

but the new() function is not executed. How can I do it?.
I need to do this inside a directive, maybe it can be achieved in a controller, but I need to do it in a directive, and I put this example doubt to apply it in my real project. Thank you very much.

http://jsfiddle.net/mg8g138x/

```<code>    app.directive('validation', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel',

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;
              }

              scope.old= function(){
                alert("old")
              }
             //attrs.$set('ngClick', 'new(this.form)');
              scope.new= function(form){
                alert("new");
                console.log(form)
              }

           }

        };
    });
</code>```

答:
I am not sure why you would want to do it. Implement a function that will use both the use cases of the two functions you need to implement. Say for example if you want some x function during start then trigger functionx and then when an action has happened then trigger functiony which are called within the function old().

I definitely do not recommend change of attributes. But if you really wish t do it this is how you may want to for it..

```<code>app.directive('validation', function ($timeout) {

            return {
                restrict: 'AE',
                require: 'ngModel',

                link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                    return;
                  }

                  scope.previous= function(){
                    alert("old")
                  }

                 scope.old= scope.previous

                  scope.new= function(form){
                    alert("new");
                    console.log(form)
                  }
                 // Do this action may be within a function after an action
                 // or an event $emit/$broadcast rather than directly in code.
                 attrs.$set('ngClick', scope.old = scope.new);
               }

            };
        });
</code>```

Please have a look at this stackoverflow as well.
attrs.$set('ngClick', functionName + '()'); no longer working in angular 1.2rc3

ContentLicense: CC BY-SA 3.0

Body:
I have a function defined in a directive called old(), currently the button executes this function when clicking. I want when the directive is loaded, the old() function was changed to the new() function. The new function, would receive by parameter (this.form) ("form" is the name of my form).
I've tried this, but it

attrs.$set('ngClick', 'new(this.form)');

but the new() function is not executed. How can I do it?.
I need to do this inside a directive, maybe it can be achieved in a controller, but I need to do it in a directive, and I put this example doubt to apply it in my real project. Thank you very much.

http://jsfiddle.net/mg8g138x/

    app.directive('validation', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel',

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;
              }

              scope.old= function(){
                alert("old")
              }
             //attrs.$set('ngClick', 'new(this.form)');
              scope.new= function(form){
                alert("new");
                console.log(form)
              }

           }

        };
    });

Body:
I am not sure why you would want to do it. Implement a function that will use both the use cases of the two functions you need to implement. Say for example if you want some x function during start then trigger functionx and then when an action has happened then trigger functiony which are called within the function old().

I definitely do not recommend change of attributes. But if you really wish t do it this is how you may want to for it..

app.directive('validation', function ($timeout) {

            return {
                restrict: 'AE',
                require: 'ngModel',

                link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                    return;
                  }

                  scope.previous= function(){
                    alert("old")
                  }

                 scope.old= scope.previous

                  scope.new= function(form){
                    alert("new");
                    console.log(form)
                  }
                 // Do this action may be within a function after an action
                 // or an event $emit/$broadcast rather than directly in code.
                 attrs.$set('ngClick', scope.old = scope.new);
               }

            };
        });

Please have a look at this stackoverflow as well.
attrs.$set('ngClick', functionName + '()'); no longer working in angular 1.2rc3


问:
How to crawl with breadth-first search using Scrapy (Python3)?
I want to run the crawler as breadth-first search.

So, I wrote the following code.

```<code>from scrapy.spider import BaseSpider
from scrapy.http   import Request

class MySpider(BaseSpider):
    start_urls = ['http://example.com/a']

    def parse(self, response):
        next_a = response.css('.next::attr(href)').extract_first()
        if next_a:
            yield Request(next_a, callback=self.parse, priority = 3)

        for b in response.css('.b::attr("href")'):
            yield Request(b, callback=self.parse_b, priority = 2)

    def parse_b(self, response):
        pass
</code>```

I am hoping that this crawler will move as follows.

a1, a2, a3, ..., an, b1, b2, b3, ...., bn

But actually it will be like this.

a1, b1, b2, ...., b_n1, a2, b_n1+1, b_n1+2, ....

How can I run as expected?

答:
Quoting from here

Does Scrapy crawl in breadth-first or depth-first order?

By default, Scrapy uses a LIFO queue for storing pending requests, which
basically means that it crawls in DFO order. This order is more convenient
in most cases. If you do want to crawl in true BFO order, you can do it by
setting the following settings:

```DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeues.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.FifoMemoryQueue'
```

Body:
I want to run the crawler as breadth-first search.

So, I wrote the following code.

from scrapy.spider import BaseSpider
from scrapy.http   import Request

class MySpider(BaseSpider):
    start_urls = ['http://example.com/a']

    def parse(self, response):
        next_a = response.css('.next::attr(href)').extract_first()
        if next_a:
            yield Request(next_a, callback=self.parse, priority = 3)

        for b in response.css('.b::attr("href")'):
            yield Request(b, callback=self.parse_b, priority = 2)

    def parse_b(self, response):
        pass

I am hoping that this crawler will move as follows.

a1, a2, a3, ..., an, b1, b2, b3, ...., bn

But actually it will be like this.

a1, b1, b2, ...., b_n1, a2, b_n1+1, b_n1+2, ....

How can I run as expected?

Body:
Quoting from here

Does Scrapy crawl in breadth-first or depth-first order?

By default, Scrapy uses a LIFO queue for storing pending requests, which
basically means that it crawls in DFO order. This order is more convenient
in most cases. If you do want to crawl in true BFO order, you can do it by
setting the following settings:

DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeues.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.FifoMemoryQueue'

ContentLicense: CC BY-SA 4.0


问:
Help about file accessing with dropbox API and Javascript
I'm  having trouble doing basic stuff with dropbox js API such as uploading and deleting a file. I would like to see a simple example doing that or at least a basic structure of what i should do. Thanks</p>

答:
Be careful as the API v1 is depreciated.

This is the Official Javascript Library API v2: https://github.com/dropbox/dropbox-sdk-js


问:
flash send request to another server
hi i am sending a flash reqesut to a url when i make request from local computer its working but when i upload on my server its not working i think flash is not sending request from my server to another server

```<code>//it working
myvars.sendAndLoad("http://mywebsite.com",myvars,"GET");
gotoAndPlay("thankYou");

//its not working
myvars.sendAndLoad("http://anotherwebsite.com",myvars,"GET");
gotoAndPlay("thankYou");
</code>```

any ideas thanks

答:
You need a crossdomain file on your server
http://kb2.adobe.com/cps/142/tn_14213.html</p>

ContentLicense: CC BY-SA 2.5

Title: flash send request to another server

Body:
hi i am sending a flash reqesut to a url when i make request from local computer its working but when i upload on my server its not working i think flash is not sending request from my server to another server

//it working
myvars.sendAndLoad("http://mywebsite.com",myvars,"GET");
gotoAndPlay("thankYou");

//its not working
myvars.sendAndLoad("http://anotherwebsite.com",myvars,"GET");
gotoAndPlay("thankYou");

any ideas thanks


问:
Understanding char * to int * conversion and its meaning
I have the following simple piece of code,

```<code>unsigned long the_function(const char* p){
        int* ip = (int*)p;
        printf("%d\n",ip);
}
</code>```

I know that the first line cast is meaning less but that the code given to me.

Now when i just pass "a" to the function i get the constant output

```<code>4196024
</code>```

could someone explain to me what is the meaning.

答:
You're attempting to print the address of the pi pointer which is of type (int *). The address is represented with 8 bytes, but ints may be represented with 4 bytes, so when you attempt to print pi using %d only a portion of the pointer is printed. As Remy Lebeau pointed out using %p is the correct way to print a pointer address.

As an aside, you're converting the char * pointer to a type of int * but you never try to access the value of what int * is pointing at, in case that's what you were trying to do.

Body:
I have the following simple piece of code,

unsigned long the_function(const char* p){
        int* ip = (int*)p;
        printf("%d\n",ip);
}

I know that the first line cast is meaning less but that the code given to me.

Now when i just pass "a" to the function i get the constant output

4196024

could someone explain to me what is the meaning.


问:
Ruby: Avoiding infinite loop in an array that doubles each number
So there is an infinte loop here, but I'm not seeing it.

```<code># Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers
</code>```

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

答:
You're adding elements to an array while iterating over that array. It's therefore impossible to reach the end.

What you need to do is use the map function:

```<code>numbers.map! do |n|
  n * 2
end
</code>```

That updates each entry in place with its value times two.

If you're looking to add on a single set of doubled numbers:

```<code>numbers += numbers.map do |n|
  n * 2
end
</code>```

That adds on a copy of the array that's been doubled.

Edit: Instead of using map, for academic illustration purposes, you can try using a copy with dup:

```<code>numbers.dup.each do |n|
  numbers << n * 2
end
</code>```

You can also iterate over it sequentially:

```<code>numbers.each_index do |i|
  numbers << numbers[i] * 2
end
</code>```

These are all far less efficient and are much harder to read than the map version.

Body:
So there is an infinte loop here, but I'm not seeing it.

# Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

Body:
You're adding elements to an array while iterating over that array. It's therefore impossible to reach the end.

What you need to do is use the map function:

numbers.map! do |n|
  n * 2
end

That updates each entry in place with its value times two.

If you're looking to add on a single set of doubled numbers:

numbers += numbers.map do |n|
  n * 2
end

That adds on a copy of the array that's been doubled.

Edit: Instead of using map, for academic illustration purposes, you can try using a copy with dup:

numbers.dup.each do |n|
  numbers << n * 2
end

You can also iterate over it sequentially:

numbers.each_index do |i|
  numbers << numbers[i] * 2
end

These are all far less efficient and are much harder to read than the map version.


问:
Do I need to know SQL when I work with Django
I am directing this question to experienced, Django developers, so as in subject, I have been learning Django since September 2016, but I've started to learn it without any knowledge about databases syntax. I know basic concepts and definitions, so I can easily implement in Django models. Summarizing, have I to know SQL to create web apps in Django? Thanks in advance.</p>

答:
You do not have to be a wizard at it but understanding relations between data sets can be extremely helpful especially if you have a complicated data hierarchy.

Just learn as you go. If you want you can look at the SQL code Django executes for you in the migrations.py file of each app.


问:
./count:78: syntax error, unexpected keyword_end, expecting end-of-input
I modified my post and managed to copy/paste the code here. I know it's ugly but really hope it's going to help to find the error.
Error message is: "./v_c:2:in ': undefined local variable or method  ' for main:Object (NameError)"</p>

```<code>#!/usr/bin/env ruby

#
# This program is used for collecting web server visit information.
#
# Author: A. Genius
#

require 'optparse'

def print_usage
    puts "USAGE: v_c -d DNS_NAME"
    exit
end

# add option switch and handler

options = {}

option_parser = OptionParser.new do |opts|

# DNS_NAME argument
 options[:dns_name] = nil
    opts.on('-d', '--dns-name DNS_NAME', 'Specify a DNS NAME') { |dns_name| options[:dns_name] = dns_name }

# HELP argument
    options[:help] = nil
    opts.on('-h', '--help', 'Display usage') { |help| options[:help] = help }
end

option_parser.parse!

# verify arguments

if options[:dns_name] then
    dns_name = options[:dns_name]
else
  puts "Please set a balancer's DNS."
  print_usage
  exit
end

if options[:help] then
    print_usage
    exit
end

# Keep STDOUT
# orig_stdout = $stdout

# redirect stdout to /dev/null
# $stdout = File.new('/dev/null', 'w')

    server1_visit_count = 0
    server2_visit_count = 0
    server3_visit_count = 0
    server4_visit_count = 0

# starting to visit load balancing server

puts "Starting to visit load balancing server"

2000.times do

# visit load balancer
# o = "curl #{dns_name}"

o = "curl -s #{dns_name}"
if o =~ /server\s*1/i
    server1_visit_count += 1
elsif o =~ /server\s*2/i
    server2_visit_count += 1
elsif o =~ /server\s*3/i
    server3_visit_count += 1
elsif o =~ /server\s*4/i
    server4_visit_count += 1
end

    print "."
end

puts
puts '-------------------------'
puts ' Summary'
puts '-------------------------'
puts "Server1 visit counts : " + server1_visit_count.to_s
puts "Server2 visit counts : " + server2_visit_count.to_s
puts "Server3 visit counts : " + server3_visit_count.to_s
puts "Server4 visit counts : " + server4_visit_count.to_s
puts "total is: " +  (server1_visit_count + server2_visit_count +

server3_visit_count + server4_visit_count).to_s
</code>```

答:
Oh... String interpolation, once again... Replace this line
#o = 'curl #{dns_name}' with:

```<code>#o = "curl #{dns_name}"
</code>```

I explained why it was the problem below.

You can see from editor that end is not recognised. Maybe you copy/pasted some code before and some characters (like quotation marks) are not the same format as your editor uses. So rewriting this short peace of code might save your ###. And paste whats rewritten here :)

elsif writes as a single word, but Ruby probably understands it, since no error I got using it this way..

String interpolation is used with double quotes

'curl -s #{dns}'

Supposed to be:

"curl -s #{dns}"

(Expect you really want to output this as "curl -s #{dns}")

Was the problem one of these?

I just pasted this into repl.it and it works well. Please check if it meets your code (I have added a value to dns_name variable since I do not have it defined in my case):

```<code>dns_name = 10
10.times do

# visit load balancer
#o = "curl #{dns_name}"

o = "curl -s #{dns_name}"
if o =~ /server\s*1/i
  server1_visit_count += 1
elsif o =~ /server\s*2/i
  server2_visit_count += 1
elsif o =~ /server\s*3/i
  server3_visit_count += 1
elsif o =~ /server\s*4/i
  server4_visit_count += 1
end

print "."
end
</code>```

Try to copy/paste this and tell if any errors:

```<code>#!/usr/bin/env ruby

#
# This program is used for collecting web server visit information.
#
# Author: A. Genius
#

require 'optparse'

def print_usage
    puts "USAGE: v_c -d DNS_NAME"
    exit
end

# add option switch and handler

options = {}

option_parser = OptionParser.new do |opts|

# DNS_NAME argument
 options[:dns_name] = nil
    opts.on('-d', '--dns-name DNS_NAME', 'Specify a DNS NAME') { |dns_name| options[:dns_name] = dns_name }

# HELP argument
    options[:help] = nil
    opts.on('-h', '--help', 'Display usage') { |help| options[:help] = help }
end

option_parser.parse!

# verify arguments

if options[:dns_name] then
    dns_name = options[:dns_name]
else
  puts "Please set a balancer's DNS."
  print_usage
  exit
end

if options[:help] then
    print_usage
    exit
end

# Keep STDOUT
# orig_stdout = $stdout

# redirect stdout to /dev/null
# $stdout = File.new('/dev/null', 'w')

    server1_visit_count = 0
    server2_visit_count = 0
    server3_visit_count = 0
    server4_visit_count = 0

# starting to visit load balancing server

puts "Starting to visit load balancing server"

2000.times do

# visit load balancer
# o = "curl #{dns_name}"

o = "curl -s #{dns_name}"
if o =~ /server\s*1/i
    server1_visit_count += 1
elsif o =~ /server\s*2/i
    server2_visit_count += 1
elsif o =~ /server\s*3/i
    server3_visit_count += 1
elsif o =~ /server\s*4/i
    server4_visit_count += 1
end

    print "."
end

puts
puts '-------------------------'
puts ' Summary'
puts '-------------------------'
puts "Server1 visit counts : " + server1_visit_count.to_s
puts "Server2 visit counts : " + server2_visit_count.to_s
puts "Server3 visit counts : " + server3_visit_count.to_s
puts "Server4 visit counts : " + server4_visit_count.to_s
puts "total is: " +  (server1_visit_count + server2_visit_count + server3_visit_count + server4_visit_count).to_s
</code>```

Body:
I modified my post and managed to copy/paste the code here. I know it's ugly but really hope it's going to help to find the error.
Error message is: "./v_c:2:in ': undefined local variable or method  ' for main:Object (NameError)"

#!/usr/bin/env ruby

#
# This program is used for collecting web server visit information.
#
# Author: A. Genius
#

require 'optparse'

def print_usage
    puts "USAGE: v_c -d DNS_NAME"
    exit
end

# add option switch and handler

options = {}

option_parser = OptionParser.new do |opts|

# DNS_NAME argument
 options[:dns_name] = nil
    opts.on('-d', '--dns-name DNS_NAME', 'Specify a DNS NAME') { |dns_name| options[:dns_name] = dns_name }

# HELP argument
    options[:help] = nil
    opts.on('-h', '--help', 'Display usage') { |help| options[:help] = help }
end

option_parser.parse!

# verify arguments

if options[:dns_name] then
    dns_name = options[:dns_name]
else
  puts "Please set a balancer's DNS."
  print_usage
  exit
end

if options[:help] then
    print_usage
    exit
end

# Keep STDOUT
# orig_stdout = $stdout

# redirect stdout to /dev/null
# $stdout = File.new('/dev/null', 'w')

    server1_visit_count = 0
    server2_visit_count = 0
    server3_visit_count = 0
    server4_visit_count = 0

# starting to visit load balancing server

puts "Starting to visit load balancing server"

2000.times do

# visit load balancer
# o = "curl #{dns_name}"

o = "curl -s #{dns_name}"
if o =~ /server\s*1/i
    server1_visit_count += 1
elsif o =~ /server\s*2/i
    server2_visit_count += 1
elsif o =~ /server\s*3/i
    server3_visit_count += 1
elsif o =~ /server\s*4/i
    server4_visit_count += 1
end

    print "."
end

puts
puts '-------------------------'
puts ' Summary'
puts '-------------------------'
puts "Server1 visit counts : " + server1_visit_count.to_s
puts "Server2 visit counts : " + server2_visit_count.to_s
puts "Server3 visit counts : " + server3_visit_count.to_s
puts "Server4 visit counts : " + server4_visit_count.to_s
puts "total is: " +  (server1_visit_count + server2_visit_count +

server3_visit_count + server4_visit_count).to_s

Body:
Oh... String interpolation, once again... Replace this line
#o = 'curl #{dns_name}' with:

#o = "curl #{dns_name}"

I explained why it was the problem below.

You can see from editor that end is not recognised. Maybe you copy/pasted some code before and some characters (like quotation marks) are not the same format as your editor uses. So rewriting this short peace of code might save your ###. And paste whats rewritten here :)

elsif writes as a single word, but Ruby probably understands it, since no error I got using it this way..

String interpolation is used with double quotes

'curl -s #{dns}'

Supposed to be:

"curl -s #{dns}"

(Expect you really want to output this as "curl -s #{dns}")

Was the problem one of these?

I just pasted this into repl.it and it works well. Please check if it meets your code (I have added a value to dns_name variable since I do not have it defined in my case):

dns_name = 10
10.times do

# visit load balancer
#o = "curl #{dns_name}"

o = "curl -s #{dns_name}"
if o =~ /server\s*1/i
  server1_visit_count += 1
elsif o =~ /server\s*2/i
  server2_visit_count += 1
elsif o =~ /server\s*3/i
  server3_visit_count += 1
elsif o =~ /server\s*4/i
  server4_visit_count += 1
end

print "."
end

Try to copy/paste this and tell if any errors:

#!/usr/bin/env ruby

#
# This program is used for collecting web server visit information.
#
# Author: A. Genius
#

require 'optparse'

def print_usage
    puts "USAGE: v_c -d DNS_NAME"
    exit
end

# add option switch and handler

options = {}

option_parser = OptionParser.new do |opts|

# DNS_NAME argument
 options[:dns_name] = nil
    opts.on('-d', '--dns-name DNS_NAME', 'Specify a DNS NAME') { |dns_name| options[:dns_name] = dns_name }

# HELP argument
    options[:help] = nil
    opts.on('-h', '--help', 'Display usage') { |help| options[:help] = help }
end

option_parser.parse!

# verify arguments

if options[:dns_name] then
    dns_name = options[:dns_name]
else
  puts "Please set a balancer's DNS."
  print_usage
  exit
end

if options[:help] then
    print_usage
    exit
end

# Keep STDOUT
# orig_stdout = $stdout

# redirect stdout to /dev/null
# $stdout = File.new('/dev/null', 'w')

    server1_visit_count = 0
    server2_visit_count = 0
    server3_visit_count = 0
    server4_visit_count = 0

# starting to visit load balancing server

puts "Starting to visit load balancing server"

2000.times do

# visit load balancer
# o = "curl #{dns_name}"

o = "curl -s #{dns_name}"
if o =~ /server\s*1/i
    server1_visit_count += 1
elsif o =~ /server\s*2/i
    server2_visit_count += 1
elsif o =~ /server\s*3/i
    server3_visit_count += 1
elsif o =~ /server\s*4/i
    server4_visit_count += 1
end

    print "."
end

puts
puts '-------------------------'
puts ' Summary'
puts '-------------------------'
puts "Server1 visit counts : " + server1_visit_count.to_s
puts "Server2 visit counts : " + server2_visit_count.to_s
puts "Server3 visit counts : " + server3_visit_count.to_s
puts "Server4 visit counts : " + server4_visit_count.to_s
puts "total is: " +  (server1_visit_count + server2_visit_count + server3_visit_count + server4_visit_count).to_s


问:
How to close all opened drivers in Selenium?
I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

```<code>WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);
</code>```

How I tried to close both drivers:

First try:

```<code>driver.close();
</code>```

Second try:

```<code>driver.quit();
</code>```

Third try:

```<code>driver.close();
driver.close();
</code>```

Fourth try:

```<code>driver.quit();
driver.quit();
</code>```

答:
I have a couple suggestions for you.

1: Naming Convention

In your post, you said:

"...in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle."

This is not a very good approach and here's why: let's say that you have two WebDrivers, each named "driverX". You need the first driver to go to "www.google.com", and you need the second driver to go to "www.yahoo.com". As such, your code looks like this:

```<code>driverX.get("www.google.com");
driverX.get("www.yahoo.com");
</code>```

This becomes a problem, as instead of telling the second WebDriver to go to Yahoo, you have actually rerouted the first WebDriver from Google to Yahoo.

What is the solution to this problem? Name each of your WebDrivers with a unique name (googleDriver or yahooDriver for example). Then, your code will look like this and you should not have any conflicts:

```<code>googleDriver.get("www.google.com");
yahooDriver.get("www.yahoo.com");
</code>```

2: WebDriver Grouping

Now that we have each of your WebDrivers with a unique name, we are able to reference them individually. This is great, however, some applications require that we reference several of them at once. This is where ArrayLists can come in. In the code below, I used an ArrayList to solve your original question.

```<code>ArrayList<WebDriver> activeDrivers = new ArrayList<>();
activeDrivers.add(googleDriver);
activeDrivers.add(yahooDriver);

for(WebDriver driver : activeDrivers){
    if(driver.getCurrentUrl().equals("Some predefined exit page"){
       driver.quit();
    }
}
</code>```

Feel free to leave a comment if you still do not understand or if you have any questions.

Body:
I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);

How I tried to close both drivers:

First try:

driver.close();

Second try:

driver.quit();

Third try:

driver.close();
driver.close();

Fourth try:

driver.quit();
driver.quit();

Body:
I have a couple suggestions for you.

1: Naming Convention

In your post, you said:

"...in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle."

This is not a very good approach and here's why: let's say that you have two WebDrivers, each named "driverX". You need the first driver to go to "www.google.com", and you need the second driver to go to "www.yahoo.com". As such, your code looks like this:

driverX.get("www.google.com");
driverX.get("www.yahoo.com");

This becomes a problem, as instead of telling the second WebDriver to go to Yahoo, you have actually rerouted the first WebDriver from Google to Yahoo.

What is the solution to this problem? Name each of your WebDrivers with a unique name (googleDriver or yahooDriver for example). Then, your code will look like this and you should not have any conflicts:

googleDriver.get("www.google.com");
yahooDriver.get("www.yahoo.com");

2: WebDriver Grouping

Now that we have each of your WebDrivers with a unique name, we are able to reference them individually. This is great, however, some applications require that we reference several of them at once. This is where ArrayLists can come in. In the code below, I used an ArrayList to solve your original question.

ArrayList<WebDriver> activeDrivers = new ArrayList<>();
activeDrivers.add(googleDriver);
activeDrivers.add(yahooDriver);

for(WebDriver driver : activeDrivers){
    if(driver.getCurrentUrl().equals("Some predefined exit page"){
       driver.quit();
    }
}

Feel free to leave a comment if you still do not understand or if you have any questions.


问:
android determine if device is in right to left language/layout
Is there a way to determine if the device is in a right to left language (something like Arabic) as opposed to something that's left to right (English)?

Something compatible with older API levels (down to 10) is necessary

SOLUTION

i ended up using the xml method in the accepted answer. Farther down the line, i also added the code indicated here for instances where I didn't have access to getResources()

Identifying RTL language in Android

more info

This question still gets a lot of traffic; something else I wanted to point out: When I originally asked this I think it was partially to help address showing different pointing chevrons in RTL vs LTR -- another slick way of accomplishing this is by placing drawable resources in the standard and ldrtl directories -- means no code required to determine which one to show!

答: If this is still getting considerable traffic, people should also consider Configuration.getLayoutDirection(), for API 17+. It will return either LayoutDirection.LTR or LayoutDirection.RTL. I imagine ViewCompat.getLayoutDirection(android.view.View) returns the direction that was actually used to layout a particular view. If you're doing something weird, such as trying to determine which person should be on which side of a chat screen (like me), this might be of use.</p>


问:
Do add-in and its popup browser window share a same localStorage?
I am building an Excel add-in with JavaScript API.

The add-in can popup a browser window by

```<code>popup = window.open("https://localhost:3000/#/new", "popup", "status=1, location=1, width=1000, height=1200");
</code>```

I have tested that the add-in and the popup browser window could communicate by postMessage.

However, it seems that they do NOT share the same localStorage. For exemple, if i set localStorage.setItem("item", "content") in the webpage, localStorage.getItem("item") in the add-in returns null.

Does anyone know if the add-in and the popup browser window share the same localStorage?

PS: I have tested that an add-in itself can set an item in localStorage and get the value. Also, webpages can set and get items in localStorage even though they may be in the same browser window.

答: I think you could use something like SignalR to communicate between the two, if you're working in asp.net.  If you are working in a different environment like node a standard websocket approach should work.</p>

Body:
I am building an Excel add-in with JavaScript API.

The add-in can popup a browser window by

popup = window.open("https://localhost:3000/#/new", "popup", "status=1, location=1, width=1000, height=1200");

I have tested that the add-in and the popup browser window could communicate by postMessage.

However, it seems that they do NOT share the same localStorage. For exemple, if i set localStorage.setItem("item", "content") in the webpage, localStorage.getItem("item") in the add-in returns null.

Does anyone know if the add-in and the popup browser window share the same localStorage?

PS: I have tested that an add-in itself can set an item in localStorage and get the value. Also, webpages can set and get items in localStorage even though they may be in the same browser window.


问:
HTML connection to MySQL
I want to create a login script on HTML page. I read that I need to use an intermediate script so that I can let my HTML use the database. So, I`ve written a PHP page that checks the username/password regarding the database.

I also read that I should use AJAX to connect to the database.

I would like to know how to write the AJAX code to return the value of the login either true or false.

答:
AJAX is really nothing more than JavaScript which connects to a server-side resource (such as a PHP-backed page), receives a result, and likely does some UI manipulation of the HTML as a response to that result.  A good place to get started is the jQuery ajax method.  Using the jQuery JavaScript library will make the process much simpler.  But, ultimately, it'll connect to your PHP code on the server to perform the actual database interaction.

Beyond that, it sounds like you're lacking a good bit of design oversight in this project.  The statement "I also read that I should use AJAX to connect to the database." is particularly troubling.  Where did you read that?  Why did you read that?  There seems to be little value in that suggestion beyond someone somewhere thinking that "AJAX is cool and people should use it for stuff."

Is there a specific design concern for using AJAX vs. just posting a form to some PHP code?

Title: HTML connection to MySQL


答:
by pushing the doubled value in the array you are increasing the array size each time by 1. hence infinite loop is occurring. I think what you really want to do is</p>

```<code>numbers.each do |num|
  puts num *2
end
</code>```

Title: Ruby: Avoiding infinite loop in an array that doubles each number

Body:
by pushing the doubled value in the array you are increasing the array size each time by 1. hence infinite loop is occurring. I think what you really want to do is

numbers.each do |num|
  puts num *2
end


问:
extract specific data from numpy ndarray
New to pandas any help is appreciated

```<code>def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io
</code>```

Output row of io['payload']:

```<code>{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}
</code>```

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

```<code>"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"
</code>```

答:
Using @jezrael's sample df

```<code>d = {'_id__$oid': ['542f8', '542f8', '542f8'], 'channel': ['snort_alert', 'snort_alert', 'snort_alert'], 'payload': ['{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}']}
df = pd.DataFrame(d)
</code>```

solution

Smash all payloads together with a vecorized str.cat

Parse the whole thing at once with pd.read_json

```<code>cols = 'destination_ip proto source_ip date sensor'.split()
df.drop(
    'payload', 1
).join(
    pd.read_json('[{}]'.format(df.payload.str.cat(sep=',')))[cols]
)
</code>```

Body:
New to pandas any help is appreciated

def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io

Output row of io['payload']:

{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"

Body:
Using @jezrael's sample df

d = {'_id__$oid': ['542f8', '542f8', '542f8'], 'channel': ['snort_alert', 'snort_alert', 'snort_alert'], 'payload': ['{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}']}
df = pd.DataFrame(d)

solution

Smash all payloads together with a vecorized str.cat

Parse the whole thing at once with pd.read_json

cols = 'destination_ip proto source_ip date sensor'.split()
df.drop(
    'payload', 1
).join(
    pd.read_json('[{}]'.format(df.payload.str.cat(sep=',')))[cols]
)


问:
NoCredentialsError : Unable to locate credentials - python module boto3
I am running django in a python virtual environment(virtualenv). The django website is served by apache2 from an amazon ec2 instance(ubuntu 16.04). I use boto3 module to write to amazon s3.

I installed awscli and ran aws configure and set up my aws access keys correctly. ( I know I configured it correctly, because $ aws s3 ls returns the correct lists of my s3 buckets.)

However, when I try to write some objects to s3 from django application, it fails producing the error as described in the title.

I recently moved to a new instance and started using python virtual environments. Before that, it used to work fine. I have read the questions on SO and the docs from aws. Below is the stack trace.

```<code>Environment:

Request Method: POST
Request URL: http://*******/product/4

Django Version: 1.10.6
Python Version: 3.5.2
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'abc.apps.abcdirectConfig')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/ubuntu/abcdirect/abcdirect/views.py" in view_product
  385.             s3.Bucket('abccms').put_object(Key=s3_file_name, Body=s3_file_data)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/boto3/resources/factory.py" in do_action
  520.                 response = action(self, *args, **kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/boto3/resources/action.py" in __call__
  83.         response = getattr(parent.meta.client, operation_name)(**params)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/client.py" in _api_call
  253.             return self._make_api_call(operation_name, kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/client.py" in _make_api_call
  530.                 operation_model, request_dict)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/endpoint.py" in make_request
  141.         return self._send_request(request_dict, operation_model)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/endpoint.py" in _send_request
  166.         request = self.create_request(request_dict, operation_model)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/endpoint.py" in create_request
  150.                                      operation_name=operation_model.name)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/hooks.py" in emit
  227.         return self._emit(event_name, kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/hooks.py" in _emit
  210.             response = handler(**kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/signers.py" in handler
  90.         return self.sign(operation_name, request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/signers.py" in sign
  147.             auth.add_auth(request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/auth.py" in add_auth
  679.             raise NoCredentialsError

Exception Type: NoCredentialsError at /product/4
Exception Value: Unable to locate credentials
</code>```

答:
I figured out the reason I was getting the error. I am posting the answer just in case someone else encounters this issue.

tl;dr : aws config files did not live in apache's home directory

The django app was running under the user www-data(apache2). When I configured my credentials using aws configure, my settings were stored in .aws/config file.

Now this is where the problem was.

The .aws/configure file was stored in my home directory and not in the home directory of www-data(apache2),which is /var/www by default. So when the django app called boto3 module, the module was looking for the config file in /var/www/.aws/config but my files were in /home/ubuntu/.aws/config.

Simply copying the relevant files to /var/www/ fixed the problem for me.

Body:
I am running django in a python virtual environment(virtualenv). The django website is served by apache2 from an amazon ec2 instance(ubuntu 16.04). I use boto3 module to write to amazon s3.

I installed awscli and ran aws configure and set up my aws access keys correctly. ( I know I configured it correctly, because $ aws s3 ls returns the correct lists of my s3 buckets.)

However, when I try to write some objects to s3 from django application, it fails producing the error as described in the title.

I recently moved to a new instance and started using python virtual environments. Before that, it used to work fine. I have read the questions on SO and the docs from aws. Below is the stack trace.

Environment:

Request Method: POST
Request URL: http://*******/product/4

Django Version: 1.10.6
Python Version: 3.5.2
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'abc.apps.abcdirectConfig')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/ubuntu/abcdirect/abcdirect/views.py" in view_product
  385.             s3.Bucket('abccms').put_object(Key=s3_file_name, Body=s3_file_data)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/boto3/resources/factory.py" in do_action
  520.                 response = action(self, *args, **kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/boto3/resources/action.py" in __call__
  83.         response = getattr(parent.meta.client, operation_name)(**params)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/client.py" in _api_call
  253.             return self._make_api_call(operation_name, kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/client.py" in _make_api_call
  530.                 operation_model, request_dict)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/endpoint.py" in make_request
  141.         return self._send_request(request_dict, operation_model)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/endpoint.py" in _send_request
  166.         request = self.create_request(request_dict, operation_model)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/endpoint.py" in create_request
  150.                                      operation_name=operation_model.name)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/hooks.py" in emit
  227.         return self._emit(event_name, kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/hooks.py" in _emit
  210.             response = handler(**kwargs)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/signers.py" in handler
  90.         return self.sign(operation_name, request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/signers.py" in sign
  147.             auth.add_auth(request)

File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/botocore/auth.py" in add_auth
  679.             raise NoCredentialsError

Exception Type: NoCredentialsError at /product/4
Exception Value: Unable to locate credentials


问:
Context menu on grid rows does not open
I search in the forums and could not find that one thing that I am missing.

I have a simple grid implementation from your examples which I wanted to

add a context menu on it but it just does not do the job (I get the regular browser context menu).

here is my code (ASP.NET MVC)

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-xs-18 col-md-12">

            <script type="text/x-kendo-template" id="rowTemplate">
                <div class="orderRow">
                    <tr>
                        <td>
                            #:OrderID#
                        </td>
                        <td>
                            #:Freight#
                        </td>
                        <td>
                            #:OrderDate#
                        </td>
                        <td>
                            #:ShipName#
                        </td>
                        <td>
                            #:ShipCity#
                        </td>
                    </tr>
                </div>
            </script>

            <script>
                var rowTemplate = kendo.template($('#rowTemplate').html());
            </script>

            @(Html.Kendo().Grid<APDashboard.Models.OrderViewModel>()
                .Name("AgilePointDashboardGrid")
                .Columns(columns =>
                {
                    columns.Bound(p => p.OrderID).Filterable(false);
                    columns.Bound(p => p.Freight);
                    columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
                    columns.Bound(p => p.ShipName);
                    columns.Bound(p => p.ShipCity);
                })
                .ClientRowTemplate("#=rowTemplate(data)#")
                .Pageable()
                .Sortable()
                .Scrollable()
                .Filterable()
                .HtmlAttributes(new { style = "height:550px;" })
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(20)
                    .Read(read => read.Action("Orders_Read", "Grid"))
                )
            )

            @(Html.Kendo().ContextMenu()
                .Name("menu")
                .Target("#AgilePointDashboardGrid")
                .Filter(".orderRow")
                .Orientation(ContextMenuOrientation.Horizontal)
                .Items(items =>
                {
                    items.Add()
                         .Text("Forward");
                })
            )
      </div>
    </div>

    <script>
    $(document).ready(function() {
        var menu = $("#menu");
        var original = menu.clone(true);
        original.find(".k-state-active").removeClass("k-state-active");

        var initMenu = function () {

            menu = $("#menu").kendoContextMenu({
                target: "#AgilePointDashboardGrid",
                filter: ".orderRow",
                select: function(e) {
                    // Do something on select
                }
            });
        };
        initMenu();
    });
    </script>
</div>
</code>```

I would love to know what am I missing here

Thanks

答:
Eventually I "solved" it using the JavaScript way instead of the MVC way. If I`ll find the reason why it did not work above I will update this answer to show both ways.

Here is how I solved it:

```<code>    <ul id="context-menu">
        <li>Edit</li>
        <li>
            Delete
            <ul>
                <li>Logical deletion</li>
                <li>Permanent deletion</li>
            </ul>
        </li>
    </ul>

    <script>
    $("#context-menu").kendoContextMenu({
        target: "#grid",
        filter: "tr[role='row']",
        select: function(e) {
            var grid = $("#grid").data("kendoGrid");
            var model = grid.dataItem(e.target);
            console.log(model);
        }
    });
    </script>
</code>```

Title: Context menu on grid rows does not open

Body:
I search in the forums and could not find that one thing that I am missing.

I have a simple grid implementation from your examples which I wanted to

add a context menu on it but it just does not do the job (I get the regular browser context menu).

here is my code (ASP.NET MVC)

            @(Html.Kendo().Grid<APDashboard.Models.OrderViewModel>()
                .Name("AgilePointDashboardGrid")
                .Columns(columns =>
                {
                    columns.Bound(p => p.OrderID).Filterable(false);
                    columns.Bound(p => p.Freight);
                    columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
                    columns.Bound(p => p.ShipName);
                    columns.Bound(p => p.ShipCity);
                })
                .ClientRowTemplate("#=rowTemplate(data)#")
                .Pageable()
                .Sortable()
                .Scrollable()
                .Filterable()
                .HtmlAttributes(new { style = "height:550px;" })
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(20)
                    .Read(read => read.Action("Orders_Read", "Grid"))
                )
            )

            @(Html.Kendo().ContextMenu()
                .Name("menu")
                .Target("#AgilePointDashboardGrid")
                .Filter(".orderRow")
                .Orientation(ContextMenuOrientation.Horizontal)
                .Items(items =>
                {
                    items.Add()
                         .Text("Forward");
                })
            )

I would love to know what am I missing here

Thanks

Body:
Eventually I "solved" it using the JavaScript way instead of the MVC way. If I`ll find the reason why it did not work above I will update this answer to show both ways.

Here is how I solved it:

    <ul id="context-menu">
        <li>Edit</li>
        <li>
            Delete
            <ul>
                <li>Logical deletion</li>
                <li>Permanent deletion</li>
            </ul>
        </li>
    </ul>

    <script>
    $("#context-menu").kendoContextMenu({
        target: "#grid",
        filter: "tr[role='row']",
        select: function(e) {
            var grid = $("#grid").data("kendoGrid");
            var model = grid.dataItem(e.target);
            console.log(model);
        }
    });
    </script>


问:
why move Constructor is not call?
please look at the following example code:

```<code>    class testo
{
public:
    testo()
    {
        cout << " default " << endl;
    }

    testo(const testo & src)
    {
        cout << "copy " << endl;
    }
    testo(const testo && src)
    {
        cout << "move" << endl;
    }
    testo & operator=(const testo & rhs)
    {
        cout << " assigment" << endl;
        return *this;
    }
    testo & operator= (const testo && rhs)
    {
        cout << "move" << endl;
    }

};
</code>```

and this is my function and main code :

```<code>testo nothing(testo & input)
{
return input;
}

int main ()
{
testo boj1 ;
testo obj2(nothing(obj1) );
return 1;
}
</code>```

when i compile and run this code i expect to see :

```<code>default    // default constructor

copy       // returning from the function

move       // moving to the obj2
</code>```

but when the code is getting execute it just show :

```<code>default

copy
</code>```

the compiler is Visual C++ 2015

答: Move signatures are supposed to be defined as T&&, not T const &&. While there's nothing in the language stopping you from declaring something T const &&, it makes no sense in practical terms: you mean to move from this object, but it's const and therefore can't have its state changed? It's a contradiction of terms.

Title: why move Constructor is not call?

Body:
please look at the following example code:

    class testo
{
public:
    testo()
    {
        cout << " default " << endl;
    }

    testo(const testo & src)
    {
        cout << "copy " << endl;
    }
    testo(const testo && src)
    {
        cout << "move" << endl;
    }
    testo & operator=(const testo & rhs)
    {
        cout << " assigment" << endl;
        return *this;
    }
    testo & operator= (const testo && rhs)
    {
        cout << "move" << endl;
    }

};

and this is my function and main code :

testo nothing(testo & input)
{
return input;
}

int main ()
{
testo boj1 ;
testo obj2(nothing(obj1) );
return 1;
}

when i compile and run this code i expect to see :

default    // default constructor

copy       // returning from the function

move       // moving to the obj2

but when the code is getting execute it just show :

default

copy

the compiler is Visual C++ 2015


问:
Realm version Migration renaming property not existed
Hi I have Realm migration but have meet error

below is my situation error scenario

first

I have a simple User Model of schemeVersion 0 (default)

```<code>class User: Object {
    dynamic var username = ""
    dynamic var date = NSDate()
}
</code>```

add date2 in version 1

```<code>class User: Object {
    dynamic var username = ""
    dynamic var date = NSDate()
    dynamic var date2 = NSDate()
}
</code>```

and migrate

```<code>Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if oldSchemaVersion < 1 {
                migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
                    newObject!["date2"] = oldObject!["date"] as! NSDate
                })
            }
}
</code>```

and add date3 in version 3 and rename date3 to date 4 in version 4

```<code>class User: Object {
    dynamic var username = ""
    dynamic var date = NSDate()
    dynamic var date2 = NSDate()
    dynamic var date4 = NSDate()
}
</code>```

and migrate

```<code>Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 4,
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if oldSchemaVersion < 1 {
                migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
                    newObject!["date2"] = oldObject!["date"] as! NSDate
                })
            }

            if oldSchemaVersion < 2 {
                migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
                    newObject!["date3"] = oldObject!["date2"] as! NSDate
                })
            }

            if oldSchemaVersion < 3 {
                migration.renameProperty(onType: User.className(), from: "date3", to: "date4")
            }
}
</code>```

When I have migrated sequencely 0 -> 1 -> 2 -> 3 -> 4 work fine

but when migrate from 0 version to 4 version cause fatal error: 'try!' expression unexpectedly raised an error

"Cannot rename property 'User.date3' because it does not exist."

in this case how can i migrate 0 ~ 3 version to 4 without above not exist exeption ?

答:
If schemaVersion 3 is only one that has "date3", version 3 has to be handled separately (I don't know what happen in schemaVersion 2). And you can't insert oldObject["date2"] to newObject["date3"], because newObject does not have date3 as error. The purpose of migration is matching the oldscheme with the present scheme. Try it in your project, it worked with me!

```<code> Realm.Configuration.defaultConfiguration = Realm.Configuration(
       schemaVersion: 4,
       migrationBlock: { migration, oldSchemaVersion in
       migration.enumerateObjects(ofType: User.className(), { (oldObject, newObject) in
           if oldSchemaVersion < 1 {
               newObject?["date2"] = oldObject!["date"] as! NSDate
           }
           // use newObject["date2"] instead of oldObject["date2"] for schemaVerion 0
           if oldSchemaVersion < 2 {
               newObject?["date4"] = newObject?["date2"] as! NSDate
           }
      })
      // separate version 3 for "date3"
      if oldSchemaVersion == 3 {
          migration.renameProperty(onType: User.className(), from: "date3", to: "date4")
      }
})
</code>```

And I recommend you use func enumerateObjects once. You don't need to fetch all objects every time. I hope it will work!

Body:
Hi I have Realm migration but have meet error

below is my situation error scenario

first

I have a simple User Model of schemeVersion 0 (default)

class User: Object {
    dynamic var username = ""
    dynamic var date = NSDate()
}

add date2 in version 1

class User: Object {
    dynamic var username = ""
    dynamic var date = NSDate()
    dynamic var date2 = NSDate()
}

and migrate

Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if oldSchemaVersion < 1 {
                migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
                    newObject!["date2"] = oldObject!["date"] as! NSDate
                })
            }
}

and add date3 in version 3 and rename date3 to date 4 in version 4

class User: Object {
    dynamic var username = ""
    dynamic var date = NSDate()
    dynamic var date2 = NSDate()
    dynamic var date4 = NSDate()
}

and migrate

Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 4,
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if oldSchemaVersion < 1 {
                migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
                    newObject!["date2"] = oldObject!["date"] as! NSDate
                })
            }

            if oldSchemaVersion < 2 {
                migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
                    newObject!["date3"] = oldObject!["date2"] as! NSDate
                })
            }

            if oldSchemaVersion < 3 {
                migration.renameProperty(onType: User.className(), from: "date3", to: "date4")
            }
}

When I have migrated sequencely 0 -> 1 -> 2 -> 3 -> 4 work fine

but when migrate from 0 version to 4 version cause fatal error: 'try!' expression unexpectedly raised an error

"Cannot rename property 'User.date3' because it does not exist."

in this case how can i migrate 0 ~ 3 version to 4 without above not exist exeption ?

Body:
If schemaVersion 3 is only one that has "date3", version 3 has to be handled separately (I don't know what happen in schemaVersion 2). And you can't insert oldObject["date2"] to newObject["date3"], because newObject does not have date3 as error. The purpose of migration is matching the oldscheme with the present scheme. Try it in your project, it worked with me!

 Realm.Configuration.defaultConfiguration = Realm.Configuration(
       schemaVersion: 4,
       migrationBlock: { migration, oldSchemaVersion in
       migration.enumerateObjects(ofType: User.className(), { (oldObject, newObject) in
           if oldSchemaVersion < 1 {
               newObject?["date2"] = oldObject!["date"] as! NSDate
           }
           // use newObject["date2"] instead of oldObject["date2"] for schemaVerion 0
           if oldSchemaVersion < 2 {
               newObject?["date4"] = newObject?["date2"] as! NSDate
           }
      })
      // separate version 3 for "date3"
      if oldSchemaVersion == 3 {
          migration.renameProperty(onType: User.className(), from: "date3", to: "date4")
      }
})

And I recommend you use func enumerateObjects once. You don't need to fetch all objects every time. I hope it will work!


问:
Limit number of mongodb objects appearing per page and then paginate
I'm working on a blog app using express and Mongodb. I have a show page with the following code:

```<code><% include ./partials/header %>

<div class = "container">
<div class = "jumbotron show">
    <h2><%= blog.title%></h2>
</div>
<div class="showWidth">
    <div class="row">
        <div class ="col-md-12 showDate"><%= blog.created.toDateString()%>  </div>
    </div>
    <div class="row">
            <img class = "center-block showImage" src= "<%= blog.image%>">
    </div>
    <div class="row">
            <div class ="col-md-12 showText"><%- blog.body%></div>
    </div>
    <div class="row">
            <img class = "center-block showImage" src= "<%= blog.imageTwo%>">
    </div>
    <div class="row">
            <div class ="col-md-12 showText"><%- blog.bodyTwo%></div>
    </div>

<% if(currentUser && currentUser.id === "58c9bb76854068369807957c"){ %>
    <a href="/blogs/<%=blog._id%>/edit" class="btn btn-sm btn-info">Edit blog</a>
<div>
<form id="delete" action ="/blogs/<%=blog._id%>?_method=DELETE" method="POST">
    <button class="btn btn-sm btn-danger">Delete blog</button>
</form>
<% } %>

        <hr class = "style-two">

<!--================== COMMENTS DISPLAY SECTION ====================================================================-->
<div id="comments">
    <% blog.comments.forEach(function(comment){ %>
    <div class="comment-container">
        <div class="jumbotron comment">
            <div class="row">
                <div class="col-md-1">
                    <img class="comment-ico" src = "    <%=comment.author.image%>">
                </div>

                <div class="col-md-7">
                    <h4><%=comment.author.username%></h4>
                </div>
                <div class="col-md-4 date">
                     <%= moment(comment.created).fromNow()%>
                </div>
            </div>
        </div>
            <div><p><%=comment.text%></p></div>

<!--=================EDIT COMMENT FORM =========================================================================-->
       <form id="edit-comment-form" action = "/blogs/<%= blog._id %>/comments/<%=comment._id%>?_method=PUT" method = "POST" id="newComment">
            <textarea class = "form-control" rows="4" name = "comment[text]"><%=comment.text%></textarea>
            <button class = "btn btn-lg btn-primary btn-block">Submit</button>
        </form>

    <!--    ==================================================================================================================-->

        <% if(currentUser && currentUser.username == comment.author.username) { %>
            <div class="row">
                <div class="col-md-1 choice">
                    <a class="edit">Edit</a>
                </div>
                <div class="col-md-1">
                    <form id = "delete-form" action = "/blogs/<%= blog._id %>/comments/<%=comment._id%>?_method=DELETE" method = "POST">
                    <input type = "submit" class = "button-delete" value = "Delete"></form>
                </div>
            </div>
        <% } %>
        <hr class = "style-three">
    </div>
    <% }) %>
</div>
</div>

 <% if(currentUser){ %>
 <div class = "container form">
   <form action = "/blogs/<%= blog._id %>/comments" method = "POST" id="newComment">
    <div class="row">
        <div class="col-md-2">
            <img class="newComment-ico" src = "<%=currentUser.image%>">
        </div>
        <div class="col-md-10">
            <label for="comment">Add comment</label>
        </div>
    </div>
        <textarea class = "form-control" rows="4" placeholder = "Type comment here..." name = "comment[text]"></textarea>
        <button class = "btn btn-lg btn-primary btn-block">Submit</button>
    </form>
</div>

<% } %>

<% include ./partials/footer %>
</code>```

I need to display just the first, say, 5 articles on this page and then pass the next 5 onto an identical second page etc, obviously adding some pagination along the way. How do I do this? I've been looking around and can't find a solution

答:
I do not know about the ODM that you used. But with mongo shell. Your problem can be solve with $limit and $skip operator of mongo.

Page 1:
ArticlesModel.find().limit(5)

Page 2:
ArticlesModel.find().skip(5).limit(5)

Body:
I'm working on a blog app using express and Mongodb. I have a show page with the following code:

<% include ./partials/header %>

<%= blog.title%>

<%= blog.created.toDateString()%>

            <img class = "center-block showImage" src= "<%= blog.image%>">

<%- blog.body%>

            <img class = "center-block showImage" src= "<%= blog.imageTwo%>">

<%- blog.bodyTwo%>

<% if(currentUser && currentUser.id === "58c9bb76854068369807957c"){ %>
    <a href="/blogs/<%=blog._id%>/edit" class="btn btn-sm btn-info">Edit blog

<form id="delete" action ="/blogs/<%=blog._id%>?_method=DELETE" method="POST">
    <button class="btn btn-sm btn-danger">Delete blog</button>
</form>
<% } %>

    <% blog.comments.forEach(function(comment){ %>

                    <img class="comment-ico" src = "    <%=comment.author.image%>">

<%=comment.author.username%>

                     <%= moment(comment.created).fromNow()%>

<%=comment.text%>

       <form id="edit-comment-form" action = "/blogs/<%= blog._id %>/comments/<%=comment._id%>?_method=PUT" method = "POST" id="newComment">
            <textarea class = "form-control" rows="4" name = "comment[text]"><%=comment.text%></textarea>
            <button class = "btn btn-lg btn-primary btn-block">Submit</button>
        </form>

        <% if(currentUser && currentUser.username == comment.author.username) { %>

                    Edit

                    <form id = "delete-form" action = "/blogs/<%= blog._id %>/comments/<%=comment._id%>?_method=DELETE" method = "POST">
                    <input type = "submit" class = "button-delete" value = "Delete"></form>

        <% } %>

    <% }) %>

 <% if(currentUser){ %>

   <form action = "/blogs/<%= blog._id %>/comments" method = "POST" id="newComment">

            <img class="newComment-ico" src = "<%=currentUser.image%>">

            Add comment

        <textarea class = "form-control" rows="4" placeholder = "Type comment here..." name = "comment[text]"></textarea>
        <button class = "btn btn-lg btn-primary btn-block">Submit</button>
    </form>

<% } %>

<% include ./partials/footer %>

I need to display just the first, say, 5 articles on this page and then pass the next 5 onto an identical second page etc, obviously adding some pagination along the way. How do I do this? I've been looking around and can't find a solution


问:
MaxLength property for textbox in code behind?
I am trying to use MaxLength function for the textbox in code behind.

How is it possible for textbox txttabname here, which is created dynamically. Any idea? Thanks a lot in advance!!

```<code>for (int i = 0; i < additionalPageCount; i++)
    {
        if (i == 0)
        {
            this.pnlProfilePages.Controls.Add(new LiteralControl("<tr><td colspan=\"4\" style=\"width:100px;font-size:11px; padding-bottom: 10px;\"><h3>Page Tabs</h3></td></tr>"));
        }
        this.pnlProfilePages.Controls.Add(new LiteralControl("<tr><td style=\"font-size:11px; padding-left:6px;\">Tab Name :</td><td style=\"padding-right:10px;font-size:11px;MaxLength:20\">"));
        string txtTabControlID = "txtTabName" + i.ToString();
        TextBox txtTab = new TextBox();
        txtTab.ID = txtTabControlID;
        txtTab.Width = 100;
        txtTab.TabIndex = lastTabIndex++;
    }
}
</code>```

答:
```<code>txtTab.MaxLength = 100;
</code>```

Body:
I am trying to use MaxLength function for the textbox in code behind.

How is it possible for textbox txttabname here, which is created dynamically. Any idea? Thanks a lot in advance!!

for (int i = 0; i < additionalPageCount; i++)
    {
        if (i == 0)
        {
            this.pnlProfilePages.Controls.Add(new LiteralControl("

Page Tabs

"));
        }
        this.pnlProfilePages.Controls.Add(new LiteralControl("
Tab Name :	"));
        string txtTabControlID = "txtTabName" + i.ToString();
        TextBox txtTab = new TextBox();
        txtTab.ID = txtTabControlID;
        txtTab.Width = 100;
        txtTab.TabIndex = lastTabIndex++;
    }
}

Body: txtTab.MaxLength = 100;


问:
regex javascript to look for a string with start and end pattern
I would appreciate if someone can help me to come up with a regex that I can look for a pattern in a href. Pattern is to look for a query string hint=value& and then replace it with a new value hint=value2&. so the pattern should start with hint and end with & if there are more query strings or end of the value for hint.

I dont want to use jquery external library (purl). Any help will be much appreciated.

答:
You could use a positive lookahead and check for & or the end of the string.

```<code>hint=(.*?)(?=&|$)
</code>```

Live preview

Since we're using a lookahead, this means that the replacement doesn't need to include the & at the end. Which might be an important factor if hint=value were to be the last query element.

Which in JavaScript would look like this:

const str = "https://www.sample.com/signup?es=click&hint=m%2A%2A%2A%2A%2A%2A%2Ai%40gmail.com&ru=%2F%22";

const replacement = "hint=newstring";

const regex = /hint=(.*?)(?=&|$)/g;

const result = str.replace(regex, replacement);

console.log(result);```
</div>
</div>
</p>

<p>Given your example url, then <code>console.log(result)</code> would output:</p>

```https://www.sample.com/signup?es=click&hint=newstring&ru=%2F%22
```

Body:
You could use a positive lookahead and check for & or the end of the string.

hint=(.*?)(?=&|$)

Live preview

Since we're using a lookahead, this means that the replacement doesn't need to include the & at the end. Which might be an important factor if hint=value were to be the last query element.

Which in JavaScript would look like this:

const str = "https://www.sample.com/signup?es=click&hint=m%2A%2A%2A%2A%2A%2A%2Ai%40gmail.com&ru=%2F%22";

const replacement = "hint=newstring";

const regex = /hint=(.*?)(?=&|$)/g;

const result = str.replace(regex, replacement);

console.log(result);

Given your example url, then console.log(result) would output:

https://www.sample.com/signup?es=click&hint=newstring&ru=%2F%22


问:
Redux Observables / RxJS: How to make epic that returns different actions based on if / else?
I am trying to hook up my app with in app purchases using this: https://github.com/chirag04/react-native-in-app-utils

I have an epic where I want to emit success if it succeeds, and failure if it fails. Something like this:

```<code>import 'rxjs';
import { InAppUtils } from 'NativeModules';

import * as packagesActions from '../ducks/packages';
import * as subscriptionActions from '../ducks/subscription';

export default function createSubscription(action$, store) {
  return action$.ofType(packagesActions.SELECT)
    .mergeMap(action => {
      const productId = action.payload;
      InAppUtils.purchaseProduct(productId, (error, response) => {
        if(response && response.productIdentifier) {
          return subscriptionActions.subscribeSuccess();
        } else {
          return subscriptionActions.subscribeFailure();
        }
      });
    });
};
</code>```

However I'm not sure how to write the contents of mergeMap. Is there a way to do this?

答:
InAppUtils.purchaseProduct appears to use a Node-style callback. There is an RxJS static method that can be used to create an observable from such an API call: bindNodeCallback.

Within your mergeMap, you should be able to do something like this

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/bindNodeCallback';
import 'rxjs/add/observable/of';

...
.mergeMap(action => {
  const productId = action.payload;
  const bound = Observable.bindNodeCallback((callback) => InAppUtils.purchaseProduct(productId, callback));
  return bound()
    .map(response => subscriptionActions.subscribeSuccess())
    .catch(error => Observable.of(subscriptionActions.subscribeFailure()));
});
```

Body:
I am trying to hook up my app with in app purchases using this: https://github.com/chirag04/react-native-in-app-utils

I have an epic where I want to emit success if it succeeds, and failure if it fails. Something like this:

import 'rxjs';
import { InAppUtils } from 'NativeModules';

import * as packagesActions from '../ducks/packages';
import * as subscriptionActions from '../ducks/subscription';

export default function createSubscription(action$, store) {
  return action$.ofType(packagesActions.SELECT)
    .mergeMap(action => {
      const productId = action.payload;
      InAppUtils.purchaseProduct(productId, (error, response) => {
        if(response && response.productIdentifier) {
          return subscriptionActions.subscribeSuccess();
        } else {
          return subscriptionActions.subscribeFailure();
        }
      });
    });
};

However I'm not sure how to write the contents of mergeMap. Is there a way to do this?


问:
Print a trie in Ocaml
Every function listed below works as expected. (except the last one)

I'm trying to make the to_list work, I want it to return a list of char lists, but I so far I managed only to implement it with simple prints  returning unit

```<code>type trie = Trie of bool * (char * trie) list
let empty = Trie (false, [])

let explode wd = (*breaks up a word in a list of chars*)
    let rec exp i acc =
        if i = -1 then acc else exp (i-1) (wd.[i]::acc) in
        exp (String.length wd - 1) []

let insert tr wd = (*insert a word into the trie*)
let rec insert' wd tr = match wd, tr with
    | [], Trie (_, l) -> Trie (true, l)
    | wh::wt, Trie (b, l) ->
        try Trie(b, (wh, insert' wt (List.assoc wh l))::List.remove_assoc wh l)
        with Not_found -> Trie (b, (wh, insert' wt empty) :: l)
        in insert' (explode wd) tr

let from_list = List.fold_left insert empty  (*makes trie from string list*)

let to_list tr = (*prints all trie words*)
    let rec to_list' (Trie (b, l)) acc =
        if b then
            (
                List.iter print_char (List.rev acc);
                print_char '\n'
            )
        else ();
        List.iter (fun (c, t) -> to_list' t (c::acc)) l in
    to_list' tr []
</code>```

EDIT : Thanks to @Goswin von Brederlow I made my to_list printing function clearer.

What I tried :

```<code>let to_list tr = (*fails at compile time*)
    let rec to_list' acc = function
        | Trie(_, []) -> [List.rev acc]
        | Trie(true, (c, h)::_) -> (List.rev acc) :: to_list' (c::acc) h
        | Trie(_, l) -> List.map (fun (c, t) -> to_list' (c::acc) t) in
        to_list' [] a tr
</code>```

Example :

```<code>let t = from_list ["hello"; "hell"; "helsinki"; "here"];;
# to_list t;;
here
helsinki
hell
hello
- : unit = ()
</code>```

Does it fail because List.map can return only type 'a list and not any n-depth nested lists ?

答:
There's two reasonable ways of doing this: to have map return a list of lists and then flatten it, or to thread an accumulator. I'll give the second, since it is more efficient and not much more complicated:

```<code>let to_list trie =
  let rec recur acc chars (Trie (word_here, entries)) =
    let acc =
      match entries with
      | [] -> acc
      | _ ->
        List.fold_left (fun acc (char, trie) ->
            recur acc (char::chars) trie)
          acc entries in
    if word_here then List.rev chars::acc
    else acc in
  recur [] [] trie
</code>```

Title: Print a trie in Ocaml

Body:
Every function listed below works as expected. (except the last one)

I'm trying to make the to_list work, I want it to return a list of char lists, but I so far I managed only to implement it with simple prints  returning unit

type trie = Trie of bool * (char * trie) list
let empty = Trie (false, [])

let explode wd = (*breaks up a word in a list of chars*)
    let rec exp i acc =
        if i = -1 then acc else exp (i-1) (wd.[i]::acc) in
        exp (String.length wd - 1) []

let insert tr wd = (*insert a word into the trie*)
let rec insert' wd tr = match wd, tr with
    | [], Trie (_, l) -> Trie (true, l)
    | wh::wt, Trie (b, l) ->
        try Trie(b, (wh, insert' wt (List.assoc wh l))::List.remove_assoc wh l)
        with Not_found -> Trie (b, (wh, insert' wt empty) :: l)
        in insert' (explode wd) tr

let from_list = List.fold_left insert empty  (*makes trie from string list*)

let to_list tr = (*prints all trie words*)
    let rec to_list' (Trie (b, l)) acc =
        if b then
            (
                List.iter print_char (List.rev acc);
                print_char '\n'
            )
        else ();
        List.iter (fun (c, t) -> to_list' t (c::acc)) l in
    to_list' tr []

EDIT : Thanks to @Goswin von Brederlow I made my to_list printing function clearer.

What I tried :

let to_list tr = (*fails at compile time*)
    let rec to_list' acc = function
        | Trie(_, []) -> [List.rev acc]
        | Trie(true, (c, h)::_) -> (List.rev acc) :: to_list' (c::acc) h
        | Trie(_, l) -> List.map (fun (c, t) -> to_list' (c::acc) t) in
        to_list' [] a tr

Example :

let t = from_list ["hello"; "hell"; "helsinki"; "here"];;
# to_list t;;
here
helsinki
hell
hello
- : unit = ()

Does it fail because List.map can return only type 'a list and not any n-depth nested lists ?

Body:
There's two reasonable ways of doing this: to have map return a list of lists and then flatten it, or to thread an accumulator. I'll give the second, since it is more efficient and not much more complicated:

let to_list trie =
  let rec recur acc chars (Trie (word_here, entries)) =
    let acc =
      match entries with
      | [] -> acc
      | _ ->
        List.fold_left (fun acc (char, trie) ->
            recur acc (char::chars) trie)
          acc entries in
    if word_here then List.rev chars::acc
    else acc in
  recur [] [] trie


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: Mine was goto in basic. I thought it was incredible you could make the program jump where ever you wanted it to. Only later did I realize with great power comes great responsibility.</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: Jared


答:
```<code>txtTab.MaxLength = 20;
</code>```

Is that what you're trying to do?

Title: MaxLength property for textbox in code behind?

Body:
txtTab.MaxLength = 20;

Is that what you're trying to do?