问:
Promise returns empty list
I have written a function that gets a list of hyperlink anchors through webscraping.

I want to push all these anchors onto an object array, which will later be serialized to a Json string.

The Api.GetCourseSubmenuUrl method and the Api.FilterSubmenuContentList both return promises.

The following code however keeps running without waiting for the array to be filled in the .each() cheerio function. Why does this happen?

Please note that the each method in cheerio is synchronous.

My code uses the packages:

Bluebird (https://github.com/petkaantonov/bluebird)

Cheerio (https://github.com/cheeriojs/cheerio)

Request (https://github.com/request/request)

Code:

```<code>Connection.prototype.FillCourseWithSubmenuContent = function(course){
    var self = this; //This class
    var submenuItems = [];
    return new BPromise(function(resolve, reject){
      return Api.GetCourseSubmenuUrl(ApiConnection.authToken).then(function(response){
        return request.get({url: self.url + response.url + course.id, followRedirect: false, jar: cookiejar}, function(err,httpResponse,body){
          if(err){
            reject(err);
          }
          var cheerio = require('cheerio');
          var dashboardhtml = cheerio.load(body, {
                  normalizeWhitespace: true,
                  decodeEntities: true
              }
          );
          //Find all the links on the page
          dashboardhtml('a').each(function(i, elem) {
              console.log("Object:");
              console.log({"text":dashboardhtml(elem).text(), "url":dashboardhtml(elem).attr('href')});
              submenuItems.push({"text":dashboardhtml(elem).text().trim(), "url":dashboardhtml(elem).attr('href')});
          });
          resolve();
        });
      }).then(function(){
        console.log(submenuItems);
        return Api.FilterSubmenuContentList(ApiConnection.authToken, submenuItems);
      });
    }).catch(function(error){
      return reject(error);
    });
};
</code>```

答:
The problem was fixed by taking the Promise constructor antipattern into account, pointed out by @Bergi.

Since the Request library doesn't have promise support, I still had to wrap it inside a (Bluebird) promise.

Please note that it is also possible to promisify libraries, which makes life a lot easier. But for the demonstration of the solution I went the promise wrapping route.

The solution:

```<code>Connection.prototype.FillCourseWithSubmenuContent = function(course){
    var self = this; //This class
    var submenuItems = [];
    return Api.GetCourseSubmenuUrl(ApiConnection.authToken).then(function(response){
      console.log(self.url + response.url + course.id);
      return new BPromise(function(resolve, reject){
        request.get({url: self.url + response.url + course.id, followRedirect: false, jar: cookiejar}, function(err,httpResponse,body){
          if(err){
            reject(err);
          }
          var cheerio = require('cheerio');
          var dashboardhtml = cheerio.load(body, {
                  normalizeWhitespace: true,
                  decodeEntities: true
              }
          );
          //Find all the links on the page
          dashboardhtml('a').each(function(i, elem) {
              // console.log("Object");
              // console.log({"text":dashboardhtml(elem).text(), "url":dashboardhtml(elem).attr('href')});
              submenuItems.push({"text":dashboardhtml(elem).text().trim(), "url":dashboardhtml(elem).attr('href')});
          });
          return resolve();
        });
      });
    }).then(function(){
      console.log(submenuItems);
      return Api.FilterSubmenuContentList(ApiConnection.authToken, submenuItems);
    });
};
</code>```

Title: Promise returns empty list

Body:
I have written a function that gets a list of hyperlink anchors through webscraping.

I want to push all these anchors onto an object array, which will later be serialized to a Json string.

The Api.GetCourseSubmenuUrl method and the Api.FilterSubmenuContentList both return promises.

The following code however keeps running without waiting for the array to be filled in the .each() cheerio function. Why does this happen?

Please note that the each method in cheerio is synchronous.

My code uses the packages:

Bluebird (https://github.com/petkaantonov/bluebird)

Cheerio (https://github.com/cheeriojs/cheerio)

Request (https://github.com/request/request)

Code:

Connection.prototype.FillCourseWithSubmenuContent = function(course){
    var self = this; //This class
    var submenuItems = [];
    return new BPromise(function(resolve, reject){
      return Api.GetCourseSubmenuUrl(ApiConnection.authToken).then(function(response){
        return request.get({url: self.url + response.url + course.id, followRedirect: false, jar: cookiejar}, function(err,httpResponse,body){
          if(err){
            reject(err);
          }
          var cheerio = require('cheerio');
          var dashboardhtml = cheerio.load(body, {
                  normalizeWhitespace: true,
                  decodeEntities: true
              }
          );
          //Find all the links on the page
          dashboardhtml('a').each(function(i, elem) {
              console.log("Object:");
              console.log({"text":dashboardhtml(elem).text(), "url":dashboardhtml(elem).attr('href')});
              submenuItems.push({"text":dashboardhtml(elem).text().trim(), "url":dashboardhtml(elem).attr('href')});
          });
          resolve();
        });
      }).then(function(){
        console.log(submenuItems);
        return Api.FilterSubmenuContentList(ApiConnection.authToken, submenuItems);
      });
    }).catch(function(error){
      return reject(error);
    });
};

Body:
The problem was fixed by taking the Promise constructor antipattern into account, pointed out by @Bergi.

Since the Request library doesn't have promise support, I still had to wrap it inside a (Bluebird) promise.

Please note that it is also possible to promisify libraries, which makes life a lot easier. But for the demonstration of the solution I went the promise wrapping route.

The solution:

Connection.prototype.FillCourseWithSubmenuContent = function(course){
    var self = this; //This class
    var submenuItems = [];
    return Api.GetCourseSubmenuUrl(ApiConnection.authToken).then(function(response){
      console.log(self.url + response.url + course.id);
      return new BPromise(function(resolve, reject){
        request.get({url: self.url + response.url + course.id, followRedirect: false, jar: cookiejar}, function(err,httpResponse,body){
          if(err){
            reject(err);
          }
          var cheerio = require('cheerio');
          var dashboardhtml = cheerio.load(body, {
                  normalizeWhitespace: true,
                  decodeEntities: true
              }
          );
          //Find all the links on the page
          dashboardhtml('a').each(function(i, elem) {
              // console.log("Object");
              // console.log({"text":dashboardhtml(elem).text(), "url":dashboardhtml(elem).attr('href')});
              submenuItems.push({"text":dashboardhtml(elem).text().trim(), "url":dashboardhtml(elem).attr('href')});
          });
          return resolve();
        });
      });
    }).then(function(){
      console.log(submenuItems);
      return Api.FilterSubmenuContentList(ApiConnection.authToken, submenuItems);
    });
};


来源: stackexchange

问:
Extract all allowed characters from a regular expression
I need to extract a list of all allowed characters from a given regular expression.

So for example, if the regex looks like this (some random example):

```<code>[A-Z]*\s+(4|5)+
</code>```

the output should be

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ45
</code>```

(omitting the whitespace)

One obvious solution would be to define a complete set of allowed characters, and use a find method, to return the corresponding subsequence for each character. This seems to be a bit of a dull solution though.

Can anyone think of a (possibly simple) algorithm on how to implement this?

答:
One thing you can do is:

split the regex by subgroup

test the char panel against the subgroup

See the following example (not perfect yet) c#:

```<code>static void Main(String[] args)
{
    Console.WriteLine($"-->{TestRegex(@"[A-Z]*\s+(4|5)+")}<--");
}

public static string TestRegex(string pattern)
{
    string result = "";
    foreach (var subPattern in Regex.Split(pattern, @"[*+]"))
    {
        if(string.IsNullOrWhiteSpace(subPattern))
            continue;
        result += GetAllCharCoveredByRegex(subPattern);
    }

    return result;
}

public static string GetAllCharCoveredByRegex(string pattern)
{
    Console.WriteLine($"Testing {pattern}");
    var regex = new Regex(pattern);
    var matches = new List<char>();
    for (var c = char.MinValue; c < char.MaxValue; c++)
    {

        if (regex.IsMatch(c.ToString()))
        {
            matches.Add(c);
        }
    }
    return string.Join("", matches);
}
</code>```

Which outputs:

Testing [A-Z]

Testing \s

Testing (4|5)

-->ABCDEFGHIJKLMNOPQRSTUVWXYZ

? ?       ???????? 45<--

ContentLicense: CC BY-SA 3.0

Body:
I need to extract a list of all allowed characters from a given regular expression.

So for example, if the regex looks like this (some random example):

[A-Z]*\s+(4|5)+

the output should be

ABCDEFGHIJKLMNOPQRSTUVWXYZ45

(omitting the whitespace)

One obvious solution would be to define a complete set of allowed characters, and use a find method, to return the corresponding subsequence for each character. This seems to be a bit of a dull solution though.

Can anyone think of a (possibly simple) algorithm on how to implement this?

Body:
One thing you can do is:

split the regex by subgroup

test the char panel against the subgroup

See the following example (not perfect yet) c#:

static void Main(String[] args)
{
    Console.WriteLine($"-->{TestRegex(@"[A-Z]*\s+(4|5)+")}<--");
}

public static string TestRegex(string pattern)
{
    string result = "";
    foreach (var subPattern in Regex.Split(pattern, @"[*+]"))
    {
        if(string.IsNullOrWhiteSpace(subPattern))
            continue;
        result += GetAllCharCoveredByRegex(subPattern);
    }

    return result;
}

public static string GetAllCharCoveredByRegex(string pattern)
{
    Console.WriteLine($"Testing {pattern}");
    var regex = new Regex(pattern);
    var matches = new List<char>();
    for (var c = char.MinValue; c < char.MaxValue; c++)
    {

        if (regex.IsMatch(c.ToString()))
        {
            matches.Add(c);
        }
    }
    return string.Join("", matches);
}

Which outputs:

Testing [A-Z]

Testing \s

Testing (4|5)

-->ABCDEFGHIJKLMNOPQRSTUVWXYZ

? ?       ???????? 45<--


问:
magento 2: get blank page when checking if category exists in sidebar
my current code in sidebar.phtml

```<code>  <?php

  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category

  if($category->getId()==503){
 echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('automation_tissue_processors')->toHtml();
}
?>
</code>```

when I am on a page with category in breadcrumbs it works fine

```<code>Home > Instruments > automation-tissue-processors-embedders.html
</code>```

the problem is when there is no category in the breadcrumbs I get a blank page

```<code>Home > automation-tissue-processors-embedders.html
</code>```

this happens when I click on a product from search result

any way to fix this?

答:
You are accesing the category>getId() on null object $category that's why it leads to blank page. Just use this code in if codition

if(!empty($category) && $category->getId()==503){
  echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('automation_tissue_processors')->toHtml();
}

Body:
my current code in sidebar.phtml

  <?php

  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category

  if($category->getId()==503){
 echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('automation_tissue_processors')->toHtml();
}
?>

when I am on a page with category in breadcrumbs it works fine

Home > Instruments > automation-tissue-processors-embedders.html

the problem is when there is no category in the breadcrumbs I get a blank page

Home > automation-tissue-processors-embedders.html

this happens when I click on a product from search result

any way to fix this?


问:
Pointer container class which can't be copied by value
I need a smart pointer for my project which can be send to several methods as parameter. I have checked auto_ptr and shared_ptr from boost. But IMO, that is not suitable for my requirements. Following are my findings

auto_ptr : When passed to another method, ownership will be transferred and underlying pointer will get deleted when that method's scope ends. We can workaround this by passing auto_ptr by reference, but there is no compile time mechanism to ensure it is always passed by reference. If by mistake, user forgot to pass a reference, it will make problems.

boost::shared_ptr : This looks promising and works correctly for my need. But I feel this is overkill for my project as it is a very small one.

So I decided to write a trivial templated pointer container class which can't be copied by value and take care about deleting the underlying pointer. Here it is

```<code>template <typename T>
class simple_ptr{
public:
    simple_ptr(T* t){
       pointer = t;
    }
    ~simple_ptr(){
       delete pointer;
    }
    T* operator->(){
       return pointer;
    }
private:
    T* pointer;
    simple_ptr(const simple_ptr<T>& t);
};
</code>```

Is this implementation correct? I have made copy constructor as private, so that compiler will alert when someone tries to pass it by value.

If by chance the pointer is deleted, delete operation on the destructor will throw assertion error. How can I workaround this?

I am pretty new to C++ and your suggestion are much appreciated.

Thanks

答:
You should user a boost::scoped_ptr<> as has been mentioned already.

In general though, if you need to make a class non-copyable, you should inherit from boost::noncopyable, i.e.

```<code>#include <boost/utility.hpp>

class myclass : boost::noncopyable
{
    ...
};
</code>```

This does all the work of making it non-copyable and is nicely self-documenting.

OwnerDisplayName: Appu

ContentLicense: CC BY-SA 2.5

Body:
I need a smart pointer for my project which can be send to several methods as parameter. I have checked auto_ptr and shared_ptr from boost. But IMO, that is not suitable for my requirements. Following are my findings

auto_ptr : When passed to another method, ownership will be transferred and underlying pointer will get deleted when that method's scope ends. We can workaround this by passing auto_ptr by reference, but there is no compile time mechanism to ensure it is always passed by reference. If by mistake, user forgot to pass a reference, it will make problems.

boost::shared_ptr : This looks promising and works correctly for my need. But I feel this is overkill for my project as it is a very small one.

So I decided to write a trivial templated pointer container class which can't be copied by value and take care about deleting the underlying pointer. Here it is

template <typename T>
class simple_ptr{
public:
    simple_ptr(T* t){
       pointer = t;
    }
    ~simple_ptr(){
       delete pointer;
    }
    T* operator->(){
       return pointer;
    }
private:
    T* pointer;
    simple_ptr(const simple_ptr<T>& t);
};

Is this implementation correct? I have made copy constructor as private, so that compiler will alert when someone tries to pass it by value.

If by chance the pointer is deleted, delete operation on the destructor will throw assertion error. How can I workaround this?

I am pretty new to C++ and your suggestion are much appreciated.

Thanks

Body:
You should user a boost::scoped_ptr<> as has been mentioned already.

In general though, if you need to make a class non-copyable, you should inherit from boost::noncopyable, i.e.

#include <boost/utility.hpp>

class myclass : boost::noncopyable
{
    ...
};

This does all the work of making it non-copyable and is nicely self-documenting.

OwnerDisplayName: Ferruccio


问:
Why is there a warning on this Java generic method definition?
I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

```<code>interface Car {
    <T extends Car> T getCar();
}

class MazdaRX8 implements Car {
    public MazdaRX8 getCar() { // "Unchecked overriding" warning
        return this;
    }
}
</code>```

With the code above, my IDE gives the warning: "Unchecked overriding: return type requires unchecked conversion. Found: 'MazdaRX8', required 'T'"

What does this warning mean?

It makes little sense to me, and Google didn't bring up anything useful.  Why doesn't this serve as a warning-free replacement for the following interface (which is also warning free, as co-variant return types are allowed by Java)?

```<code>interface Car {
    Car getCar();
}
</code>```

答:
You've made the method generic, so the caller gets to say what type should be returned (because the caller can specify the type argument). That's a pretty hard interface to implement properly in Java, where you don't get to find out the type argument at execution time.

For example, consider this:

```<code>Car mazda = new MazdaRX8();
FordGalaxy galaxy = mazda.<FordGalaxy>getCar();
</code>```

That's perfectly legal as far as the interface is concerned... but it's obviously not going to work.

Any reason why the interface isn't generic instead of the method? Then MazdaRX8 would implement Car<MazdaRX8>:

```<code>interface Car<T extends Car> {
    T getCar();
}

class MazdaRX8 implements Car<MazdaRX8 > {
    public MazdaRX8 getCar() {
        return this;
    }
}
</code>```

Body:
I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

interface Car {
    <T extends Car> T getCar();
}

class MazdaRX8 implements Car {
    public MazdaRX8 getCar() { // "Unchecked overriding" warning
        return this;
    }
}

With the code above, my IDE gives the warning: "Unchecked overriding: return type requires unchecked conversion. Found: 'MazdaRX8', required 'T'"

What does this warning mean?

It makes little sense to me, and Google didn't bring up anything useful.  Why doesn't this serve as a warning-free replacement for the following interface (which is also warning free, as co-variant return types are allowed by Java)?

interface Car {
    Car getCar();
}

Body:
You've made the method generic, so the caller gets to say what type should be returned (because the caller can specify the type argument). That's a pretty hard interface to implement properly in Java, where you don't get to find out the type argument at execution time.

For example, consider this:

Car mazda = new MazdaRX8();
FordGalaxy galaxy = mazda.<FordGalaxy>getCar();

That's perfectly legal as far as the interface is concerned... but it's obviously not going to work.

Any reason why the interface isn't generic instead of the method? Then MazdaRX8 would implement Car<MazdaRX8>:

interface Car<T extends Car> {
    T getCar();
}

class MazdaRX8 implements Car<MazdaRX8 > {
    public MazdaRX8 getCar() {
        return this;
    }
}


问:
Spout is not reading/emitting data in storm cluster mode
I am using apache storm 1.0.0 both in local as well as cluster mode. For the spout, I am reading the data from kafka topic (I am using kafka 2.11-0.8.2.1). Spout is reading the data from kafka topic and also emitting the data when I am using storm in local mode but the storm spout is not emitting any data when I am running storm in cluster mode.

My topology implementation for reading kafka data is as follow:

```<code>brokerHosts = new ZkHosts(kafkaZookeeper);
SpoutConfig kafkaConfig = new SpoutConfig(brokerHosts, kafkaTopicIn, "", "storm");
kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new KafkaSpout(kafkaConfig), 2);
</code>```

My storm configuration file (conf/storm.yaml):

```<code>storm.zookeeper.servers:
- "localhost"
storm.zookeeper.port: 2181
nimbus.seeds: ["localhost"]

storm.local.dir: "/tmp/storm"
</code>```

I am also not getting any error while submitting Storm topology in cluster mode.

Any idea why topology spout is not emitting any data in cluster mode ??
Any help would be greatly appreciated.

答:
Before submitting topology to cluster u need to start nimbus and supervior.
If that is done u will find logs folder in storm. You can check log files from there and go ahead.</p>

Body:
I am using apache storm 1.0.0 both in local as well as cluster mode. For the spout, I am reading the data from kafka topic (I am using kafka 2.11-0.8.2.1). Spout is reading the data from kafka topic and also emitting the data when I am using storm in local mode but the storm spout is not emitting any data when I am running storm in cluster mode.

My topology implementation for reading kafka data is as follow:

brokerHosts = new ZkHosts(kafkaZookeeper);
SpoutConfig kafkaConfig = new SpoutConfig(brokerHosts, kafkaTopicIn, "", "storm");
kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new KafkaSpout(kafkaConfig), 2);

My storm configuration file (conf/storm.yaml):

storm.zookeeper.servers:
- "localhost"
storm.zookeeper.port: 2181
nimbus.seeds: ["localhost"]

storm.local.dir: "/tmp/storm"

I am also not getting any error while submitting Storm topology in cluster mode.

Any idea why topology spout is not emitting any data in cluster mode ??
Any help would be greatly appreciated.


问:
RecyclerView, different divider dependently on type of row
So I have a ListView with different types of rows. I would like to disable divider for the first row and have another style of a divider for the second one.

What's the best practice to do that?

I'm adding dividers currently by:

```<code>    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getDrawable(R.drawable.divider));
    recyclerView.addItemDecoration(dividerItemDecoration);
</code>```

答:
try to add  in your row xml file at bottom of layout and define required layout_height and set layout_width="match_parent"  and hide view at particular index that you want

eg-

```<code>`<View
   android:id="@+id/view_divider"
    android:layout_width="match_parent"
    android:layout_height="@dimen/one"
    android:background="@color/grey_divider_color"/>`
</code>```

Body:
So I have a ListView with different types of rows. I would like to disable divider for the first row and have another style of a divider for the second one.

What's the best practice to do that?

I'm adding dividers currently by:

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getDrawable(R.drawable.divider));
    recyclerView.addItemDecoration(dividerItemDecoration);

Body:
try to add  in your row xml file at bottom of layout and define required layout_height and set layout_width="match_parent"  and hide view at particular index that you want

eg-

`<View
   android:id="@+id/view_divider"
    android:layout_width="match_parent"
    android:layout_height="@dimen/one"
    android:background="@color/grey_divider_color"/>`


问:
Setting probability of getting a random number 1 or 2
Is there a way to set a probability control on getting a random value either 1 or 2? Suppose if I want more than 70% of the time it should be 1 and only 30% should be the chance of getting 2 in rand(1,2). Is it possible?

答:
This should do the trick:</p>

```<code>function yourrand($prob) {
      $r = rand();
      if ($r < $prob) { return 1; }
      else { return 2; }
}
</code>```

Body:
This should do the trick:

function yourrand($prob) {
      $r = rand();
      if ($r < $prob) { return 1; }
      else { return 2; }
}


问:
How to know when two conditions are true
I have a app that comunicates with another phone (with the same app) via wifi direct  and both phone have to establish a conection with a bluetooh bridge .When both devices have a bluetooth connection , i want to start a countdown timer.

My problem .

I am using two booleans :

```<code>    private final AtomicBoolean cnoadv = new AtomicBoolean(false);//represents the other user connection
    boolean conexao = false ;// represents my connection
</code>```

when my connection is done , boolean is "conexao" is  true and i start the method "verificar " in order to verify both connections and send "pronto" to the other user in order for him to know i am connected:

```<code> conexao = true;
 verificar();
 chatManager.write("pronto".getBytes());
</code>```

On other user end , when i receive the message "pronto "   the boolean "cnoadv" that represents the other user connection becomes true and also starts the method "verificar"

```<code>public void pushMessage(String readMessage) {
    if(readMessage.equals("pronto")){

        Log.d("recebido", "pronto");

        cnoadv.getAndSet(true);

            verificar();

        }
</code>```

My verificar() method that  verifies both connections :

```<code>public void verificar() {

    if (  cnoadv && conexao) { // error here saying i cant use "&&" in atomic boolean

        Toast.makeText(getActivity().getApplicationContext(), "both connections done", Toast.LENGTH_SHORT).show();

}}
</code>```

My problem : In my  "verificar()" method that verifies both connections i want to check if both booleans are true . How do i do this ? I am doing this verification the wrong way? I would apreciate a good but simple as possible explanation since i inexperienced , thank you very much.

答:
You should get simple boolean to use &&, so try:

```<code>public void verificar() {

    if (  cnoadv.get() && conexao) { // error here saying i cant use "&&" in atomic boolean

        Toast.makeText(getActivity().getApplicationContext(), "both connections done", Toast.LENGTH_SHORT).show();

}}
</code>```

Body:
I have a app that comunicates with another phone (with the same app) via wifi direct  and both phone have to establish a conection with a bluetooh bridge .When both devices have a bluetooth connection , i want to start a countdown timer.

My problem .

I am using two booleans :

    private final AtomicBoolean cnoadv = new AtomicBoolean(false);//represents the other user connection
    boolean conexao = false ;// represents my connection

when my connection is done , boolean is "conexao" is  true and i start the method "verificar " in order to verify both connections and send "pronto" to the other user in order for him to know i am connected:

 conexao = true;
 verificar();
 chatManager.write("pronto".getBytes());

On other user end , when i receive the message "pronto "   the boolean "cnoadv" that represents the other user connection becomes true and also starts the method "verificar"

public void pushMessage(String readMessage) {
    if(readMessage.equals("pronto")){

        Log.d("recebido", "pronto");

        cnoadv.getAndSet(true);

            verificar();

        }

My verificar() method that  verifies both connections :

public void verificar() {

    if (  cnoadv && conexao) { // error here saying i cant use "&&" in atomic boolean

        Toast.makeText(getActivity().getApplicationContext(), "both connections done", Toast.LENGTH_SHORT).show();

}}

My problem : In my  "verificar()" method that verifies both connections i want to check if both booleans are true . How do i do this ? I am doing this verification the wrong way? I would apreciate a good but simple as possible explanation since i inexperienced , thank you very much.

Body:
You should get simple boolean to use &&, so try:

public void verificar() {

    if (  cnoadv.get() && conexao) { // error here saying i cant use "&&" in atomic boolean

        Toast.makeText(getActivity().getApplicationContext(), "both connections done", Toast.LENGTH_SHORT).show();

}}


问:
Longitude and Latitude of polyline : Leaflet
Is their a way to get latitude and longitude of polyline? </p>

```<code>var firstpolyline = new L.Polyline(pointList, {
    color: 'black',
    opacity: 5,
    smoothFactor: 1,
    weight: 3,
})

map.addLayer(firstpolyline);
firstpolyline.getLatLng();
</code>```

<p>here firstpolyline is givng an error that "getLatLng() is not a function". I want to check if polyline is within the map bound or not like this </p>

```<code>var bounds = map.getBounds();
if(bounds.contains(firstpolyline.getLatLng())){
    ......
}
</code>```

答:
You have to use getLatLngs() function. So try this:

```<code>var firstpolyline = new L.Polyline(pointList, {
    color: 'black',
    opacity: 5,
    smoothFactor: 1,
    weight: 3,
})
map.addLayer(firstpolyline);
var arrayOfPoints = firstpolyline.getLatLngs();
</code>```

Then you can easily iterate over an array of points and get latitude and logitude or check if point is in bounds of polygon.

```<code>for(var i=0; i < arrayOfPoints.length; i++) {
    if(map.getBounds().contains(arrayOfPoints[i])) {
        console.log('is in bounds');
    };
}
</code>```

Body:
Is their a way to get latitude and longitude of polyline?

var firstpolyline = new L.Polyline(pointList, {
    color: 'black',
    opacity: 5,
    smoothFactor: 1,
    weight: 3,
})

map.addLayer(firstpolyline);
firstpolyline.getLatLng();

here firstpolyline is givng an error that "getLatLng() is not a function". I want to check if polyline is within the map bound or not like this

var bounds = map.getBounds();
if(bounds.contains(firstpolyline.getLatLng())){
    ......
}

Body:
You have to use getLatLngs() function. So try this:

var firstpolyline = new L.Polyline(pointList, {
    color: 'black',
    opacity: 5,
    smoothFactor: 1,
    weight: 3,
})
map.addLayer(firstpolyline);
var arrayOfPoints = firstpolyline.getLatLngs();

Then you can easily iterate over an array of points and get latitude and logitude or check if point is in bounds of polygon.

for(var i=0; i < arrayOfPoints.length; i++) {
    if(map.getBounds().contains(arrayOfPoints[i])) {
        console.log('is in bounds');
    };
}


问:
How to get data from database to view page in laravel?
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

```<code><div class="table-responsive">
  <table class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th><strong>No</strong></th>
        <th><strong>Nama Petani</strong></th>
        <th><strong>Alamat</strong></th>
        <th><strong>No. Handphone</strong></th>
        <th><strong>Lokasi</strong></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </tbody>
  </table>
</div>
</code>```

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

```<code>Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});
</code>```

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

答:
[SOLVE]

Thank you guys, I already solve this problem

This is the solved code

web.php (routes)

```<code>Route::get('listpetani', function () {

    $petani = DB::table('tbl_user')->get();

    return view('listpetani', ['petani' => $petani]);
});
</code>```

and in my listpetani.blade.php

```<code>@foreach($petani as $key => $data)
    <tr>
      <th>{{$data->id_user}}</th>
      <th>{{$data->nama_user}}</th>
      <th>{{$data->alamat}}</th>
      <th>{{$data->no_telp}}</th>
      <th>{{$data->id_lokasi}}</th>
    </tr>
@endforeach
</code>```

Body:
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

        No
        Nama Petani
        Alamat
        No. Handphone
        Lokasi

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

Body:
[SOLVE]

Thank you guys, I already solve this problem

This is the solved code

web.php (routes)

Route::get('listpetani', function () {

    $petani = DB::table('tbl_user')->get();

    return view('listpetani', ['petani' => $petani]);
});

and in my listpetani.blade.php

@foreach($petani as $key => $data)
    <tr>
      <th>{{$data->id_user}}</th>
      <th>{{$data->nama_user}}</th>
      <th>{{$data->alamat}}</th>
      <th>{{$data->no_telp}}</th>
      <th>{{$data->id_lokasi}}</th>
    </tr>
@endforeach

ContentLicense: CC BY-SA 4.0


问:
What would cause an IE 8 user to not be able to execute jQuery getJSON calls?
A test user of my site (running jQuery 1.4.4) is not able to execute any of the JSONP jQuery getJSON calls.

He's using the Internet Explorer 8 on Windows XP.

Any ideas what would cause this or how to work around it?

答:
This question is a bit vague for me to be of any more help than to point you in this direction:

Internet Explorer VPC Images

Using the VPC image you will be able to test in XP / IE8 if you think this is an OS / Browser specific issue.


问:
How to modify and add words sequentially in a list - Python
I don't know if this is possible as I'm a newbie to Python, but I wanted to create a list that has a sequential order to it. So I have two lists as follows:

```<code>stock_list = ['MSFT', 'YHOO']
ret = [0, 1, 2, 3]

returns = ["ret{}".format(*ret) for ret in enumerate(ret)]
</code>```

returns

```<code>['ret0', 'ret1', 'ret2', 'ret3']
</code>```

From the above lists of returns and stock_list, I can create the following:

```<code>for index, ret_stock in enumerate(returns):
    returns[index] += "_MSFT"
returns
</code>```

Output:

```<code>['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT']
</code>```

Ideally, what I'm trying to get is this using the stock_list for both tickers, MSFT and YHOO:

```<code>  ['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT',
       'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']
</code>```

So, I could do the previous method with enumerate, but that would become increasingly time consuming if, say instead of just two tickers, MSFT and YHOO, I had 100.

By creating a list of say, 100 or more tickers, and applying it to a list of returns such as this one already shown.

```<code>['ret0', 'ret1', 'ret2', 'ret3']
</code>```

Is it possible? Maybe I'm asking the wrong question or approaching from the wrong angle.

答:
If I got it right, maybe this approach would work.

```<code>stock_list = ['MSFT', 'YHOO']
rets = range(4)

for stock in stock_list:
    stock_returns = ['ret{}_{}'.format(ret, stock) for ret in rets]
</code>```

This way, for every stock on your list, you will create a new separated list with the order you want.

Body:
I don't know if this is possible as I'm a newbie to Python, but I wanted to create a list that has a sequential order to it. So I have two lists as follows:

stock_list = ['MSFT', 'YHOO']
ret = [0, 1, 2, 3]

returns = ["ret{}".format(*ret) for ret in enumerate(ret)]

returns

['ret0', 'ret1', 'ret2', 'ret3']

From the above lists of returns and stock_list, I can create the following:

for index, ret_stock in enumerate(returns):
    returns[index] += "_MSFT"
returns

Output:

['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT']

Ideally, what I'm trying to get is this using the stock_list for both tickers, MSFT and YHOO:

  ['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT',
       'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']

So, I could do the previous method with enumerate, but that would become increasingly time consuming if, say instead of just two tickers, MSFT and YHOO, I had 100.

By creating a list of say, 100 or more tickers, and applying it to a list of returns such as this one already shown.

['ret0', 'ret1', 'ret2', 'ret3']

Is it possible? Maybe I'm asking the wrong question or approaching from the wrong angle.

Body:
If I got it right, maybe this approach would work.

stock_list = ['MSFT', 'YHOO']
rets = range(4)

for stock in stock_list:
    stock_returns = ['ret{}_{}'.format(ret, stock) for ret in rets]

This way, for every stock on your list, you will create a new separated list with the order you want.


问:
How to run a mixed language program
I want to write a mixed language program where part of the code will be written in C, and part of the code in assembly. I was given a sample code, so i know what should my work look like.

```<code> .globl _addArrayinA

_addArrayinA:
    pushl %ebp
    movl  %esp,%ebp
    subl  $8,%esp
    movl  8(%ebp), %ebx
    xorl  %esi,%esi
    xor   %eax,%eax

bak:
    addl  (%ebx),%eax
    addl  $4,%ebx
    incl  %esi
    cmpl  $10, %esi
    jne   bak

    movl %ebp, %esp
    popl  %ebp
    ret
 # Return value is in %ea
</code>```

Above is the assembly part.

```<code>int  addArrayinC(int *myArray, int num)
{
    int c;
    int i;

    c = 0;

    for (i=0; i<num; i++)
        {c += *myArray;
        myArray++;
        }

    return (c);

}
</code>```

This is the second function written in C.
And below is the main file, which is supposed to use two functions above.

```<code>#include <stdio.h>
#include <stdlib.h>

extern int addArrayinC(int *numbers,int count);
extern int addArrayinA(int *numbers, int count);

    int main(void) {
        int mynumbers[10]={1,2,3,4,5,6,7,8,9,0};
        int sum;

        sum = addArrayinC(mynumbers, 10);
        printf("\nThe sum of array computed in C  is : %d ",sum);

        sum = addArrayinA(mynumbers, 10);
        printf("\nThe sum of array computed in assembly is : %d ",sum);

        return EXIT_SUCCESS;
    }
</code>```

I tried to open these three files in codeblocks, but could not get to run them. I have no idea how to run a mixed language program. Generally, I use cloud9 for compilations of code. Anyways... How can i run code like this?

答: No problem here. Please note: the extension of the assembler source file has to be .s or .S(upper case if you want the file to be preprocessed e.g. for #define).

Title: How to run a mixed language program

Body:
I want to write a mixed language program where part of the code will be written in C, and part of the code in assembly. I was given a sample code, so i know what should my work look like.

 .globl _addArrayinA

_addArrayinA:
    pushl %ebp
    movl  %esp,%ebp
    subl  $8,%esp
    movl  8(%ebp), %ebx
    xorl  %esi,%esi
    xor   %eax,%eax

bak:
    addl  (%ebx),%eax
    addl  $4,%ebx
    incl  %esi
    cmpl  $10, %esi
    jne   bak

    movl %ebp, %esp
    popl  %ebp
    ret
 # Return value is in %ea

Above is the assembly part.

int  addArrayinC(int *myArray, int num)
{
    int c;
    int i;

    c = 0;

    for (i=0; i<num; i++)
        {c += *myArray;
        myArray++;
        }

    return (c);

}

This is the second function written in C.
And below is the main file, which is supposed to use two functions above.

#include <stdio.h>
#include <stdlib.h>

extern int addArrayinC(int *numbers,int count);
extern int addArrayinA(int *numbers, int count);

    int main(void) {
        int mynumbers[10]={1,2,3,4,5,6,7,8,9,0};
        int sum;

        sum = addArrayinC(mynumbers, 10);
        printf("\nThe sum of array computed in C  is : %d ",sum);

        sum = addArrayinA(mynumbers, 10);
        printf("\nThe sum of array computed in assembly is : %d ",sum);

        return EXIT_SUCCESS;
    }

I tried to open these three files in codeblocks, but could not get to run them. I have no idea how to run a mixed language program. Generally, I use cloud9 for compilations of code. Anyways... How can i run code like this?


问:
Ruby Waitir Gem, getting unexpected results
2 weeks ago I put up post about my watir script timing out on me, I was able to get a solution but I realized to late the results I was getting was different than the person that helped me out. Here is the original post: Ruby Watir Gem, Timing Out on Form Input

```<code>require 'watir'

browser = Watir::Browser.new

browser.goto('https://tripadvisor.com/CheapFlightsHome')
browser.text_field(name: 'orig').set('Boston, MA - Logan International Airport (BOS)')
browser.text_field(name: 'dest').set('Milan, Italy - All Airports (MIL)')
browser.execute_script('document.querySelector(".in_date").click()')
browser.execute_script('document.querySelector(".day_28").click()')
browser.execute_script('document.querySelector(".out_date").click()')
browser.execute_script('document.querySelector(".day_2").click()')
browser.span(id: "CHECK_FARES_BUTTON").fire_event :click
puts browser.url
browser.quit
</code>```

The person who wrote that code got this as a result:
https://www.tripadvisor.com/CheapFlightsSearchResults-g187849-a_airport0.BOS-a_airport1.MIL-a_cos.0-a_date0.20170328-a_date1.20170402-a_nearby0.no-a_nearby1.no-a_nonstop.no-a_pax0.a-a_travelers.1-Milan_Lombardy.html

I have the same code in my script and for some reason I'm only getting:
https://www.tripadvisor.com/CheapFlightsHome

It seems as though the button click isn't happening for me, not sure. I tried both chrome and firefox.

答:
Firstly, I changed .fire_event :click to .click.

Then there was an error that appeared.

Please enter a valid airport code or city.

Secondly, I tried this:

```<code>browser.span(id: "CHECK_FARES_BUTTON").click
browser.span(id: "CHECK_FARES_BUTTON").click
puts browser.url
</code>```

And it redirected me to:
https://www.tripadvisor.com/CheapFlightsSearchResults-g187849-a_airport0.BOS-a_airport1.MIL-a_cos.0-a_date0.20170401-a_date1.20170402-a_nearby0.no-a_nearby1.no-a_nonstop.no-a_pax0.a-a_travelers.1-Milan_Lombardy.html

To be honest I have no idea why it does not register the input during the first click...

I am using chrome.

Body:
2 weeks ago I put up post about my watir script timing out on me, I was able to get a solution but I realized to late the results I was getting was different than the person that helped me out. Here is the original post: Ruby Watir Gem, Timing Out on Form Input

require 'watir'

browser = Watir::Browser.new

browser.goto('https://tripadvisor.com/CheapFlightsHome')
browser.text_field(name: 'orig').set('Boston, MA - Logan International Airport (BOS)')
browser.text_field(name: 'dest').set('Milan, Italy - All Airports (MIL)')
browser.execute_script('document.querySelector(".in_date").click()')
browser.execute_script('document.querySelector(".day_28").click()')
browser.execute_script('document.querySelector(".out_date").click()')
browser.execute_script('document.querySelector(".day_2").click()')
browser.span(id: "CHECK_FARES_BUTTON").fire_event :click
puts browser.url
browser.quit

The person who wrote that code got this as a result:
https://www.tripadvisor.com/CheapFlightsSearchResults-g187849-a_airport0.BOS-a_airport1.MIL-a_cos.0-a_date0.20170328-a_date1.20170402-a_nearby0.no-a_nearby1.no-a_nonstop.no-a_pax0.a-a_travelers.1-Milan_Lombardy.html

I have the same code in my script and for some reason I'm only getting:
https://www.tripadvisor.com/CheapFlightsHome

It seems as though the button click isn't happening for me, not sure. I tried both chrome and firefox.

Body:
Firstly, I changed .fire_event :click to .click.

Then there was an error that appeared.

Please enter a valid airport code or city.

Secondly, I tried this:

browser.span(id: "CHECK_FARES_BUTTON").click
browser.span(id: "CHECK_FARES_BUTTON").click
puts browser.url

And it redirected me to:
https://www.tripadvisor.com/CheapFlightsSearchResults-g187849-a_airport0.BOS-a_airport1.MIL-a_cos.0-a_date0.20170401-a_date1.20170402-a_nearby0.no-a_nearby1.no-a_nonstop.no-a_pax0.a-a_travelers.1-Milan_Lombardy.html

To be honest I have no idea why it does not register the input during the first click...

I am using chrome.


问:
How to count rows with specific value?
I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 1?

```<code>SELECT
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore,
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM
    Match A
INNER JOIN
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId
</code>```

答:
Use this.</p>

```<code>LEFT JOIN (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
        FROM PlayerMatch
        INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
        GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId =C1.TeamId
        Having COUNT(Goal) = 1
</code>```

Title: How to count rows with specific value?

Body:
I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 1?

SELECT
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore,
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM
    Match A
INNER JOIN
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId

Body:
Use this.

LEFT JOIN (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
        FROM PlayerMatch
        INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
        GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId =C1.TeamId
        Having COUNT(Goal) = 1


问:
Android volley implementing custom request with getParams that accepts JSONArray param
I am using Google's Volley to make GET and POST requests using the following custom request class:

```<code>public class GsonRequest<T> extends Request<T> {

    private static final int SOCKET_TIMEOUT_MS = 30000;
    private static final int MAX_RETRIES = 3;

    private final Gson gson = new Gson();
    private final Type type;
    private final Map<String, String> params;
    private final Response.Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url    URL of the request to make
     * @param type   Relevant type object, for Gson's reflection
     * @param params Map of request params
     */
    public GsonRequest(int method, String url, Type type, Map<String, String> params,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.type = type;
        this.params = params;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        // Here is my question, can I add a param value as JSONArray? like this:
        params.put("orderValue", "35");
        params.put("price", ""price": ["13.00", "22.00"]");
        return params != null ? params : super.getParams();
    }

    @Override
    public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
        final RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        return super.setRetryPolicy(policy);
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            Log.i("" + gson.toJson(params).getBytes("utf-8"));
            return gson.toJson(params).getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", gson.toJson(params), "utf-8");
            return super.getBody();
        }
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            final String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return (Response<T>) Response.success(gson.fromJson(json, type), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}
</code>```

The Json I'm trying to send:

```<code>{
  "orderValue": "35",
  "price": [
    "13.00",
    "22.00"
  ]
}
</code>```

What is really sent as I get from getBody() method log is:

```<code>{
  "price": "[\"23.00\",\"55.00\"]",
  "orderValue": "35"
}
</code>```

Any help with this issue?

答:
You need change extends Request to ** JsonObjectRequest** or create JSONArrayRequest object.

```<code>public class VolleyJSONObjectRequest extends JsonObjectRequest {

    private Context context;
    private int timeOut = 10000;
    private int maxRetries = 1;

    public VolleyJSONObjectRequest(int method, Context context, String url, JSONObject jsonObject, Listener<JSONObject> listener, ErrorListener errorListener) {
        super(method, url, jsonObject, listener, errorListener);
        super.setRetryPolicy(new DefaultRetryPolicy(timeOut, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public void startRequest() {
        VolleyHandler.get(context).addToRequestQueue(this);
    }
}
</code>```

Example method:

```<code>private void saveItems(){
        if  (itens != null && itens.size() > 0) {
            try {
                JSONArray itensJson = new JSONArray();

                for (SalesOrderItem item : itens) { // your loop

                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("price", this.priceOne);
                    jsonObject.put("price", this.priceTwo);

                    itensJson.put(jsonObject);
                }

                JSONObject headerJSON = new JSONObject();
                headerJSON.put("price", itensJson);

                VolleyJSONObjectRequest request = new VolleyJSONObjectRequest(Request.Method.POST, context, context.getString(R.string.URL_SALES_ORDER_ITENS_INSERT), headerJSON, onResponseItem, onErrorResponseItem);
                request.startRequest();

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

  request = new VolleyStringRequest(context, context.getString(R.string.URL_FINISH_SALES_ORDER_DRAFT), onResponseFinishSalesOrderDraft, onErrorResponseFinishSalesOrderDraft);
  request.startRequest();
</code>```

Body:
I am using Google's Volley to make GET and POST requests using the following custom request class:

public class GsonRequest<T> extends Request<T> {

    private static final int SOCKET_TIMEOUT_MS = 30000;
    private static final int MAX_RETRIES = 3;

    private final Gson gson = new Gson();
    private final Type type;
    private final Map<String, String> params;
    private final Response.Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url    URL of the request to make
     * @param type   Relevant type object, for Gson's reflection
     * @param params Map of request params
     */
    public GsonRequest(int method, String url, Type type, Map<String, String> params,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.type = type;
        this.params = params;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        // Here is my question, can I add a param value as JSONArray? like this:
        params.put("orderValue", "35");
        params.put("price", ""price": ["13.00", "22.00"]");
        return params != null ? params : super.getParams();
    }

    @Override
    public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
        final RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        return super.setRetryPolicy(policy);
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            Log.i("" + gson.toJson(params).getBytes("utf-8"));
            return gson.toJson(params).getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", gson.toJson(params), "utf-8");
            return super.getBody();
        }
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            final String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return (Response<T>) Response.success(gson.fromJson(json, type), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

The Json I'm trying to send:

{
  "orderValue": "35",
  "price": [
    "13.00",
    "22.00"
  ]
}

What is really sent as I get from getBody() method log is:

{
  "price": "[\"23.00\",\"55.00\"]",
  "orderValue": "35"
}

Any help with this issue?

Body:
You need change extends Request to ** JsonObjectRequest** or create JSONArrayRequest object.

public class VolleyJSONObjectRequest extends JsonObjectRequest {

    private Context context;
    private int timeOut = 10000;
    private int maxRetries = 1;

    public VolleyJSONObjectRequest(int method, Context context, String url, JSONObject jsonObject, Listener<JSONObject> listener, ErrorListener errorListener) {
        super(method, url, jsonObject, listener, errorListener);
        super.setRetryPolicy(new DefaultRetryPolicy(timeOut, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public void startRequest() {
        VolleyHandler.get(context).addToRequestQueue(this);
    }
}

Example method:

private void saveItems(){
        if  (itens != null && itens.size() > 0) {
            try {
                JSONArray itensJson = new JSONArray();

                for (SalesOrderItem item : itens) { // your loop

                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("price", this.priceOne);
                    jsonObject.put("price", this.priceTwo);

                    itensJson.put(jsonObject);
                }

                JSONObject headerJSON = new JSONObject();
                headerJSON.put("price", itensJson);

                VolleyJSONObjectRequest request = new VolleyJSONObjectRequest(Request.Method.POST, context, context.getString(R.string.URL_SALES_ORDER_ITENS_INSERT), headerJSON, onResponseItem, onErrorResponseItem);
                request.startRequest();

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

  request = new VolleyStringRequest(context, context.getString(R.string.URL_FINISH_SALES_ORDER_DRAFT), onResponseFinishSalesOrderDraft, onErrorResponseFinishSalesOrderDraft);
  request.startRequest();


问:
Class vs. static method in JavaScript
I know this will work:

```<code>function Foo() {};
Foo.prototype.talk = function () {
    alert('hello~\n');
};

var a = new Foo;
a.talk(); // 'hello~\n'
</code>```

But if I want to call

```<code>Foo.talk() // this will not work
Foo.prototype.talk() // this works correctly
</code>```

I find some methods to make Foo.talk work,

Foo.__proto__ = Foo.prototype

Foo.talk = Foo.prototype.talk

Are there other ways to do this? I don’t know whether it is right to do so. Do you use class methods or static methods in your JavaScript code?

答:
If you have to write static methods in ES5 I found a great tutorial for that:

```<code>//Constructor
var Person = function (name, age){
//private properties
var priv = {};

//Public properties
this.name = name;
this.age = age;

//Public methods
this.sayHi = function(){
    alert('hello');
}
}

// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
   alert("I am a Person object ;)");
};
</code>```

see @https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

Title: Class vs. static method in JavaScript

Body:
I know this will work:

function Foo() {};
Foo.prototype.talk = function () {
    alert('hello~\n');
};

var a = new Foo;
a.talk(); // 'hello~\n'

But if I want to call

Foo.talk() // this will not work
Foo.prototype.talk() // this works correctly

I find some methods to make Foo.talk work,

Foo.__proto__ = Foo.prototype

Foo.talk = Foo.prototype.talk

Are there other ways to do this? I don’t know whether it is right to do so. Do you use class methods or static methods in your JavaScript code?

Body:
If you have to write static methods in ES5 I found a great tutorial for that:

//Constructor
var Person = function (name, age){
//private properties
var priv = {};

//Public properties
this.name = name;
this.age = age;

//Public methods
this.sayHi = function(){
    alert('hello');
}
}

// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
   alert("I am a Person object ;)");
};

see @https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/


问:
dropdown load on selection of other dropdown
I have the dropdown trigger an ajax post that sends the selected value of country dropdown .

```<code>       model class

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;

        namespace MVC_4___A_Registration_Form.Models
        {
            public class ModelServices
            {
                private readonly MyCompanyEntities entities = new MyCompanyEntities();

                public IEnumerable<Country> GetCountryList()
                {
                    return entities.Countries.ToList();
                }

                public IEnumerable<countryState> GetStateByCountry(int CountryID)
                {
                    return entities.countryStates.Where(s => s.CountryId == CountryID).ToList();
                }

                public IList<EmployeeRegInfo> GetAllEmployeeList()
                {
                    var myQuery = (from e in entities.Employees
                                   join c in entities.Countries on e.Country equals c.CountryId
                                   join s in entities.countryStates on e.State equals s.StateId
                                   select new EmployeeRegInfo()
                                   {
                                       Id = e.Id,
                                       Emp_ID = e.Emp_ID,
                                       Dept = e.Dept,
                                       Name = e.Name,
                                       CountryName = c.County,
                                       StateName = s.State,
                                       City = e.City,
                                       Mobile = e.Mobile
                                   });

                    return myQuery.ToList();
                }

                public bool IsEmpAlreadyExist(string EMP_CODE)
                {
                    bool IsRecordExist = false;

                    var result = (from t in entities.Employees
                                  where t.Emp_ID == EMP_CODE
                                  select t).SingleOrDefault();

                    if (result != null)
                    {
                        IsRecordExist = true;
                    }
                    return IsRecordExist;
                }

                public void AddNewEmployee(Employee emp)
                {
                    entities.Employees.Add(emp);
                    entities.SaveChanges();
                }
            }
        }

    create.cshtml

    @model MVC_4___A_Registration_Form.Models.EmployeeRegInfo
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        @ViewBag.ErrorMsg
        <table>
            <tr>
                <td>
                    @Html.LabelFor(model => model.Emp_ID)
                </td>
                <td>@Html.EditorFor(model => model.Emp_ID)
                    @Html.ValidationMessageFor(model => model.Emp_ID)</td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.Name)
                </td>
                <td>@Html.EditorFor(model => model.Name)
                    @Html.ValidationMessageFor(model => model.Name)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.Dept)
                </td>
                <td>@Html.EditorFor(model => model.Dept)
                    @Html.ValidationMessageFor(model => model.Dept)</td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.Country)</td>
                <td>@Html.DropDownList("Country", ViewBag.Country as SelectList, new { Styles = "width:300px" })</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.State)
                </td>
                <td>
                    <select id="State" name="State" style="width: 200px"></select>
                    @Html.ValidationMessageFor(model => model.State)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.City)</td>
                <td>@Html.EditorFor(model => model.City)
                    @Html.ValidationMessageFor(model => model.City)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.Mobile)</td>

                <td>@Html.EditorFor(model => model.Mobile)
                    @Html.ValidationMessageFor(model => model.Mobile)
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="Add Employee" /></td>
            </tr>
        </table>
    }

    <script type="text/javascript">
        $(document).ready(function () {
            $("#Country").change(function () {
                var url = "/ManageEmployee/GetStatesByCountry";
                var countryID = $("#Country").val();
                $.post(url, { countryID: countryID }, function (data) {
                    $("#State").empty();
                    var items;
                    $.each(data, function (i, states) {
                        items += "<option value=" + states.StateId + ">" + states.State + "</option>";
                    });
                    $("#State").html(items);
                });
            });
        });
    </script>

 controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVC_4___A_Registration_Form.Models;

    namespace MVC_4___A_Registration_Form.Controllers
    {
        public class ManageEmployeeController : Controller
        {
            ModelServices model = new ModelServices();

            //
            // GET: /ManageEmployee/

            public ActionResult Index()
            {
                IList<EmployeeRegInfo> empList = new List<EmployeeRegInfo>();
                empList = model.GetAllEmployeeList();
                return View(empList);
            }

            public ActionResult Create()
            {
                IEnumerable<Country> country;
                country = model.GetCountryList();
                ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
                        return View();
            }

            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                bool checkEmpCodeExist = false;
                checkEmpCodeExist = model.IsEmpAlreadyExist(collection["Emp_ID"]);
                if (!checkEmpCodeExist)
                {
                    try
                    {
                        Employee emp = new Employee();
                        emp.Emp_ID = collection["Emp_ID"];
                        emp.Name = collection["Name"];
                        emp.Dept = collection["Dept"];
                        emp.Country = Convert.ToInt32(collection["Country"]);
                        emp.State = Convert.ToInt32(collection["State"]);
                        emp.City = collection["City"];
                        emp.Mobile = collection["Mobile"];
                        model.AddNewEmployee(emp);

                        return RedirectToAction("Index");
                    }
                    catch (Exception ex)
                    {
                        return RedirectToAction("Create");
                    }
                }
                else
                {
                    ViewBag.ErrorMsg = "Employee Code Already Exist";
                    return RedirectToAction("Create");
                }

            }

            public JsonResult GetStatesByCountry(int id)
            {
                var states = model.GetStateByCountry(id);
                return Json(states, JsonRequestBehavior.AllowGet);
            }
        }
    }

I want to load state dropdown on selection of country dropdown.But i am unable to do this.
</code>```

Please help to load state dropdown on selection of country dropdown.

```<code>I want to load state dropdown on selection of country dropdown.But i am unable to do this.
</code>```

Please help to load state dropdown on selection of country dropdown.

答:
```<code>    Hey I got the answer
    some change in ajax code and controller

      $(document).ready(function () {
            $("#Country").change(function () {
                var url = "/ManageEmployee/GetStatesByCountry";
                var countryID = $("#Country").val();
             $.ajax({
                    url: url,
                    data: { id: countryID },
                    cache: false,
                    type: "POST",
                    success: function (data) {
                        var markup = "<option value='0'>Select City</option>";
                        for (var x = 0; x < data.length; x++) {
                            markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                        }
                        $("#State").html(markup).show();
                    },
                    error: function (reponse) {
                        alert("error : " + reponse);
                    }
                });
            });

        });

  [HttpPost]
        public JsonResult GetStatesByCountry(string id)
        {
            int ids = Convert.ToInt32(id);
            var states = model.GetStateByCountry(ids);
           SelectList obgcity = new SelectList(states, "StateId", "State", 0);
            return Json(obgcity);
        }
</code>```

Body:
I have the dropdown trigger an ajax post that sends the selected value of country dropdown .

       model class

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;

        namespace MVC_4___A_Registration_Form.Models
        {
            public class ModelServices
            {
                private readonly MyCompanyEntities entities = new MyCompanyEntities();

                public IEnumerable<Country> GetCountryList()
                {
                    return entities.Countries.ToList();
                }

                public IEnumerable<countryState> GetStateByCountry(int CountryID)
                {
                    return entities.countryStates.Where(s => s.CountryId == CountryID).ToList();
                }

                public IList<EmployeeRegInfo> GetAllEmployeeList()
                {
                    var myQuery = (from e in entities.Employees
                                   join c in entities.Countries on e.Country equals c.CountryId
                                   join s in entities.countryStates on e.State equals s.StateId
                                   select new EmployeeRegInfo()
                                   {
                                       Id = e.Id,
                                       Emp_ID = e.Emp_ID,
                                       Dept = e.Dept,
                                       Name = e.Name,
                                       CountryName = c.County,
                                       StateName = s.State,
                                       City = e.City,
                                       Mobile = e.Mobile
                                   });

                    return myQuery.ToList();
                }

                public bool IsEmpAlreadyExist(string EMP_CODE)
                {
                    bool IsRecordExist = false;

                    var result = (from t in entities.Employees
                                  where t.Emp_ID == EMP_CODE
                                  select t).SingleOrDefault();

                    if (result != null)
                    {
                        IsRecordExist = true;
                    }
                    return IsRecordExist;
                }

                public void AddNewEmployee(Employee emp)
                {
                    entities.Employees.Add(emp);
                    entities.SaveChanges();
                }
            }
        }

    create.cshtml

    @model MVC_4___A_Registration_Form.Models.EmployeeRegInfo
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        @ViewBag.ErrorMsg

                    @Html.LabelFor(model => model.Emp_ID)

                @Html.EditorFor(model => model.Emp_ID)
                    @Html.ValidationMessageFor(model => model.Emp_ID)

                    @Html.LabelFor(model => model.Name)

                @Html.EditorFor(model => model.Name)
                    @Html.ValidationMessageFor(model => model.Name)

                @Html.LabelFor(model => model.Dept)

                @Html.EditorFor(model => model.Dept)
                    @Html.ValidationMessageFor(model => model.Dept)

                    @Html.LabelFor(model => model.Country)
                @Html.DropDownList("Country", ViewBag.Country as SelectList, new { Styles = "width:300px" })

                @Html.LabelFor(model => model.State)

                    <select id="State" name="State" style="width: 200px"></select>
                    @Html.ValidationMessageFor(model => model.State)

                @Html.LabelFor(model => model.City)
                @Html.EditorFor(model => model.City)
                    @Html.ValidationMessageFor(model => model.City)

                    @Html.LabelFor(model => model.Mobile)

                @Html.EditorFor(model => model.Mobile)
                    @Html.ValidationMessageFor(model => model.Mobile)

                    <input type="submit" value="Add Employee" />

    }

 controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVC_4___A_Registration_Form.Models;

    namespace MVC_4___A_Registration_Form.Controllers
    {
        public class ManageEmployeeController : Controller
        {
            ModelServices model = new ModelServices();

            //
            // GET: /ManageEmployee/

            public ActionResult Index()
            {
                IList<EmployeeRegInfo> empList = new List<EmployeeRegInfo>();
                empList = model.GetAllEmployeeList();
                return View(empList);
            }

            public ActionResult Create()
            {
                IEnumerable<Country> country;
                country = model.GetCountryList();
                ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
                        return View();
            }

            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                bool checkEmpCodeExist = false;
                checkEmpCodeExist = model.IsEmpAlreadyExist(collection["Emp_ID"]);
                if (!checkEmpCodeExist)
                {
                    try
                    {
                        Employee emp = new Employee();
                        emp.Emp_ID = collection["Emp_ID"];
                        emp.Name = collection["Name"];
                        emp.Dept = collection["Dept"];
                        emp.Country = Convert.ToInt32(collection["Country"]);
                        emp.State = Convert.ToInt32(collection["State"]);
                        emp.City = collection["City"];
                        emp.Mobile = collection["Mobile"];
                        model.AddNewEmployee(emp);

                        return RedirectToAction("Index");
                    }
                    catch (Exception ex)
                    {
                        return RedirectToAction("Create");
                    }
                }
                else
                {
                    ViewBag.ErrorMsg = "Employee Code Already Exist";
                    return RedirectToAction("Create");
                }

            }

            public JsonResult GetStatesByCountry(int id)
            {
                var states = model.GetStateByCountry(id);
                return Json(states, JsonRequestBehavior.AllowGet);
            }
        }
    }

I want to load state dropdown on selection of country dropdown.But i am unable to do this.

Please help to load state dropdown on selection of country dropdown.

I want to load state dropdown on selection of country dropdown.But i am unable to do this.

Please help to load state dropdown on selection of country dropdown.


问:
Custom dependency property not set on initialization
I have UserControl ImageView that I want to add a cutom property called UseOverlay to.

```<code><XAML>

<UserControl x:Class="ImageView" .../>

<XAML.cs>
public partial class ImageView : UserControl
{
    public static DependencyProperty UseOverlayProperty;
    public ImageView()
    {
        InitializeComponent();
        if (UseOverlay)
        {
            AddOverlay();
        }
    }

    static ImageView()
    {
        UseOverlayProperty = DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView), new PropertyMetadata(false));
    }

    public bool UseOverlay
    {
        get { return (bool)GetValue(UseOverlayProperty); }
        set { SetValue(UseOverlayProperty, value); }
    }

}
</code>```

However, when used from another userControl, the property is not set. The ImageView is displayed, but without the overlay, and debugging shows UseOverlay as false.

```<code><ImageView MaxWidth="450" UseOverlay="True"/>
</code>```

What am I missing?

答:
first you must not use it in the constructor (whithout default value) and use the callback to update the layout

```<code>#region --------------------Is playing--------------------
    /// <summary>
    /// Playing status
    /// </summary>
    public static readonly DependencyProperty IsPlayingProperty = DependencyProperty.Register("IsPlaying", typeof(bool), typeof(WaitSpin),
                                        new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsPlayingChanged)));

    /// <summary>
    /// OnIsPlayingChanged callback
    /// </summary>
    /// <param name="d"></param>
    /// <param name="e"></param>
    private static void OnIsPlayingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(d))
            return;

        WaitSpin element = d as WaitSpin;
        element.ChangePlayMode((bool)e.NewValue);
    }

    /// <summary>
    /// IsPlaying
    /// </summary>
    [System.ComponentModel.Category("Loading Animation Properties"), System.ComponentModel.Description("Incates wheter is playing or not.")]
    public bool IsPlaying
    {
        get { return (bool)GetValue(IsPlayingProperty); }
        set { SetValue(IsPlayingProperty, value); }
    }
    #endregion
</code>```

you can add default with this, replace last part of register

```<code>new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                                       RatingValueChanged)
</code>```

Body:
I have UserControl ImageView that I want to add a cutom property called UseOverlay to.

<XAML>

<UserControl x:Class="ImageView" .../>

<XAML.cs>
public partial class ImageView : UserControl
{
    public static DependencyProperty UseOverlayProperty;
    public ImageView()
    {
        InitializeComponent();
        if (UseOverlay)
        {
            AddOverlay();
        }
    }

    static ImageView()
    {
        UseOverlayProperty = DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView), new PropertyMetadata(false));
    }

    public bool UseOverlay
    {
        get { return (bool)GetValue(UseOverlayProperty); }
        set { SetValue(UseOverlayProperty, value); }
    }

}

However, when used from another userControl, the property is not set. The ImageView is displayed, but without the overlay, and debugging shows UseOverlay as false.

<ImageView MaxWidth="450" UseOverlay="True"/>

What am I missing?

Body:
first you must not use it in the constructor (whithout default value) and use the callback to update the layout

#region --------------------Is playing--------------------
    /// <summary>
    /// Playing status
    /// </summary>
    public static readonly DependencyProperty IsPlayingProperty = DependencyProperty.Register("IsPlaying", typeof(bool), typeof(WaitSpin),
                                        new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsPlayingChanged)));

    /// <summary>
    /// OnIsPlayingChanged callback
    /// </summary>
    /// <param name="d"></param>
    /// <param name="e"></param>
    private static void OnIsPlayingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(d))
            return;

        WaitSpin element = d as WaitSpin;
        element.ChangePlayMode((bool)e.NewValue);
    }

    /// <summary>
    /// IsPlaying
    /// </summary>
    [System.ComponentModel.Category("Loading Animation Properties"), System.ComponentModel.Description("Incates wheter is playing or not.")]
    public bool IsPlaying
    {
        get { return (bool)GetValue(IsPlayingProperty); }
        set { SetValue(IsPlayingProperty, value); }
    }
    #endregion

you can add default with this, replace last part of register

new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                                       RatingValueChanged)


问:
Implementing Breakpoint Read/Write on PowerPC
How are breakpoint read/write implemented? Note that this is different from breakpoint execute.

The idea is to start off with a data memory address and then find the assembly instruction(s) which read/write from/to that address. In theory, we would have to check the registers and the next instruction being executed (taking into account displacement offsets) in order to find out whether this is true. Let's say the current instruction is a "store word": stw r0, 4 (r31) so it writes to address r31 + 4. We can find out whether this breaks by reading the value in r31, adding 4 and checking if this is equal to the initial data address.

However, this seems infeasible since with C programming you cannot monitor every instruction execution in assembly I believe. How is this being done in general or specific to PowerPC? Are there any special assembly instructions or debug registers which simplify this?

答:
In the PowerPC, like all other CPUs that have such a feature, this is done with hardware support. There is a special register "Data Address Breakpoint" (DABR), where you can set which memory address that should be checked and if it should be read and/or write access etc.

The CPU will then trigger an interrupt (Data Storage Interrupt) when certain instructions performs reads or writes to that given address. From the ISR, you merely need to check the return address to see how you ended up there, and then you got the program address of the instruction that caused the break.

For details, check the PowerISA manual. (Their site http://www.power.org/ appears to be down atm)


问:
replace multiple spaces by non breaking spaces
How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

```<code>"This is     my text."
</code>```

Should be converted into

```<code>"This is     my text."
</code>```

答:
It seems all you need is to replace each whitespace that is preceded with another whitespace symbol. Use a lookbehind-based approach:

```<code>(?<=\s)\s
</code>```

See the regex demo.

The (?<=\s) is a positive lookbehind that requires the presence of a whitespace immediately before  the current location, but the whitespace is not consumed, and is thus not replaced.

Below is a PHP demo:

```<code>$s = "This is     my text.";
echo preg_replace('~(?<=\s)\s~', ' ', $s);
// => This is     my text.
</code>```

Body:
How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

"This is     my text."

Should be converted into

"This is     my text."

Body:
It seems all you need is to replace each whitespace that is preceded with another whitespace symbol. Use a lookbehind-based approach:

(?<=\s)\s

See the regex demo.

The (?<=\s) is a positive lookbehind that requires the presence of a whitespace immediately before  the current location, but the whitespace is not consumed, and is thus not replaced.

Below is a PHP demo:

$s = "This is     my text.";
echo preg_replace('~(?<=\s)\s~', '&nbsp;', $s);
// => This is &nbsp;&nbsp;&nbsp;&nbsp;my text.


问:
use chromeview in android studio
i want to work with web V.R. in android studio. i found that i should use gecko view or chrome view or something like them. but i cant find anything in the web. all the references are belong to eclipse and don't work with android studio.
alternatively i put my files in external storage and load them with chrome but it didn't work properly.
https://crosswalk-project.org/documentation/downloads.html
https://github.com/pwnall/chromeview
I use these but i cant run my project</p>

答: you can import eclipse library project in android studio as well. Please refer to this link</p>

Title: use chromeview in android studio


问:
Combining events with Chronicle Queue
The chronicle queue doco specifies that it's possible to have Chronicle Sinks on different boxes and the events are distributed to it over the network from a single chronicle queue.  (http://chronicle.software/products/chronicle-queue/)

My question is whether it is possible to do the reverse?

From these chronicle sinks, we would like to generate new events that are then sent to a single new queue. (not update the existing events - as these new events are only generated upon receipt of an appropriate combination of events - otherwise the replicated model would sound appropriate?)
Is it possible to have local queues that are all replicated to a single box in the one queue?

答:
Is it possible to have local queues that are all replicated to a single box in the one queue?

You can use either a remote connection to have multiple servers write to one queue which is on a central machine (Using Chronicle Engine), or you can have a queue on each server replicated (Using Chronicle Queue Enterprise), and a small process to combine these into a single queue.

Title: Combining events with Chronicle Queue


Title: How to substring a given string with specific rules in java

Body:
This is my code and it is showing error at while.Index out of bound exception is coming.The substrings should be such that

Max 50 characters per string

No number should be broken - for example " 4318, 4466, 486," is acceptable but  " 4318, 4466, 48" is not

Substring should always start with one space and end with comma ","

can someone help me out with this please

 public class MyString {

/**
 * @param args

 */
static String input = " 4318, 4466, 486, 1698, 478, 590, 582, 1594, 486, 1690, 702, 378, 486, 586, 486, 1694, 486, 598, 538, 526, 486, 1694, 486, 622, 434, 630, 462, 1730, 422, 1754, 450, 586, 486, 1690, 498, 1682, 486, 586, 502, 606, 454, 1698, 478, 1694, 486, 1718, 458, 1686, 726, 1458, 646, 426, 486, 1694, 482, 1694, 486, 590, 482, 622, 490, 550, 490, 602, 450, 634, 466, 586, 486, 1730, 426, 1714, 494, 622, 446, 590, 494, 618, 450, 586, 490, 586, 486, 1730, 450, 586, 486, 590, 502, 1674, 530, 1650, 482, 1690, 558, 1622, 486, 1690, 486, 5298, 4306, 4466, 530, 1646, 486, 594, 650, 1502, 546, 1650, 490, 586, 486, 622, 522, 1622, 486, 602, 454, 634, 462, 1694, 482, 590, 486, 590, 486, 1694, 482, 1730, 450, 590, 498, 1638, 526, 1690, 498, 606, 458, 586, 486, 1698, 482, 1694, 482, 1690, 486, 1694, 486, 1698, 574, 494, 486, 1714, 462, 1690, 486, 626, 430, 610, 486, 590, 490, 622, 426, 610, 498, 618, 446, 1690, 486, 1734, 446, 590, 482, 590, 502, 606, 454, 590, 502, 582, 478, 1690, 486, 586, 506, 578, 482, 1686, 558, 1622, 674, 1506, 482, 1698, 590, 1606, 462, 1000";
char space=' ';
 static char comma=',';
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int start=0, end=0;
    while (end-1 < input.length()){

    start=end;
    end= start+ 50;

    String output= input.substring(start,end);
    if(output.charAt(start)==' ' && output.charAt(end-1)==',')
    {
    System.out.println(output);
    }
    else
    {

    while(!(output.charAt(end-1)==','))
    {

    end--;

    }
    output= input.substring(start,end);
    System.out.println(output);

    }
    }
    }

}

Body:
public class StringSplitTest
{
    static String input = " 4318, 4466, 486, 1698, 478, 590, 582, 1594, 486, 1690, 702, 378, 486, 586, 486, 1694, 486, 598, 538, 526, 486, 1694, 486, 622, 434, 630, 462, 1730, 422, 1754, 450, 586, 486, 1690, 498, 1682, 486, 586, 502, 606, 454, 1698, 478, 1694, 486, 1718, 458, 1686, 726, 1458, 646, 426, 486, 1694, 482, 1694, 486, 590, 482, 622, 490, 550, 490, 602, 450, 634, 466, 586, 486, 1730, 426, 1714, 494, 622, 446, 590, 494, 618, 450, 586, 490, 586, 486, 1730, 450, 586, 486, 590, 502, 1674, 530, 1650, 482, 1690, 558, 1622, 486, 1690, 486, 5298, 4306, 4466, 530, 1646, 486, 594, 650, 1502, 546, 1650, 490, 586, 486, 622, 522, 1622, 486, 602, 454, 634, 462, 1694, 482, 590, 486, 590, 486, 1694, 482, 1730, 450, 590, 498, 1638, 526, 1690, 498, 606, 458, 586, 486, 1698, 482, 1694, 482, 1690, 486, 1694, 486, 1698, 574, 494, 486, 1714, 462, 1690, 486, 626, 430, 610, 486, 590, 490, 622, 426, 610, 498, 618, 446, 1690, 486, 1734, 446, 590, 482, 590, 502, 606, 454, 590, 502, 582, 478, 1690, 486, 586, 506, 578, 482, 1686, 558, 1622, 674, 1506, 482, 1698, 590, 1606, 462, 1000,";
    static ArrayList chunks = new ArrayList();
    static char comma = ',';
    static String commaString = ",";
    static boolean more = true;
    static int startIndex = 0;
    static String str = null;
    static int splitIndex = 50;
    static int remainingInputLength = 0;

    public static void main(String[] args)
    {
        while (more)
        {
            str = input.substring(startIndex, startIndex + splitIndex);
            if (str.endsWith(commaString))
            {
                startIndex += 50;
            }
            else
            {
                splitIndex = str.lastIndexOf(comma) + 1;
                str = input.substring(startIndex, startIndex + splitIndex);
                startIndex += splitIndex;
            }
            chunks.add(str);

            remainingInputLength = input.substring(startIndex).length();
            if (remainingInputLength == 0)
            {
                more = false;
            }
            else
            {
                if (remainingInputLength >= 50)
                    splitIndex = 50;
                else
                    splitIndex = remainingInputLength;
            }
        }
        for (String s: chunks) System.out.println(s);
    }
}


问:
undefined method `to_date' for nil:NilClass on Heroku App
I have error undefined method `to_date' for nil:NilClass on my heroku server but everything work in local, i dont know how i can fix it

my helper where i call "to_date"

module BiensHelper

```<code>def sell_time(sell_date)
    time = Time.now.to_s
    time = time.to_date
    delai = time - sell_date.to_date
    delai.round
end
</code>```

end

The view where i call my helper

```<code>    <% @biens.each do |bien| %>
    <h3>
    <%= bien[:name] %> <br>
    <%= bien[:adress] %> <br>
    <%= bien[:bien_type] %> <br>
    <%= bien[:url] %> <br>
    <%= bien[:latitude] %> <br>
    <%= bien[:longitude] %> <br>
    Vendu il y a <%= sell_time(bien.sell_date) %> jours<br>
    <%= link_to "Modifier", edit_bien_path(bien), class: "btn btn-warning" %> <br>
    <%= link_to "X", bien_path(bien), method: :delete, class: "btn btn-danger" %> <br>
</h3>
<% end %>
</code>```

答:
You are getting error here :

```<code>delai = time - sell_date.to_date
</code>```

sell_date is nil for your one of record. Please check heorku db. Run heroku run rails db from your console.

Or you can open rails console like this heroku run rails console.

Change code to :

```<code>def sell_time(sell_date)
  time = Time.now.to_s
  time = time.to_date
  if sell_date.present?
    delai = time - sell_date.to_date
    delai.round
  end
end
</code>```

Function will return sell time to current time if sell_date is nil. But in my view you should fix db. and write correct values to db.

Body:
I have error undefined method `to_date' for nil:NilClass on my heroku server but everything work in local, i dont know how i can fix it

my helper where i call "to_date"

module BiensHelper

def sell_time(sell_date)
    time = Time.now.to_s
    time = time.to_date
    delai = time - sell_date.to_date
    delai.round
end

end

The view where i call my helper

    <% @biens.each do |bien| %>

    <%= bien[:name] %>

    <%= bien[:adress] %>

    <%= bien[:bien_type] %>

    <%= bien[:url] %>

    <%= bien[:latitude] %>

    <%= bien[:longitude] %>

    Vendu il y a <%= sell_time(bien.sell_date) %> jours

    <%= link_to "Modifier", edit_bien_path(bien), class: "btn btn-warning" %>

    <%= link_to "X", bien_path(bien), method: :delete, class: "btn btn-danger" %>

<% end %>

Body:
You are getting error here :

delai = time - sell_date.to_date

sell_date is nil for your one of record. Please check heorku db. Run heroku run rails db from your console.

Or you can open rails console like this heroku run rails console.

Change code to :

def sell_time(sell_date)
  time = Time.now.to_s
  time = time.to_date
  if sell_date.present?
    delai = time - sell_date.to_date
    delai.round
  end
end

Function will return sell time to current time if sell_date is nil. But in my view you should fix db. and write correct values to db.


答:
at the moment UseOverlay used only once in constructor (where it is false according to default value). When UseOverlay="True" is applied nothing happens. You need to add DP ChangedCallback:

```<code>DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView),
                            new PropertyMetadata(false, UseOverlayChangedCallback));
</code>```

```<code>private static void UseOverlayChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    if ((bool) e.NewValue)
        ((ImageView)obj).AddOverlay();
    else
        ((ImageView)obj).HideOverlay();
}
</code>```

Title: Custom dependency property not set on initialization

Body:
at the moment UseOverlay used only once in constructor (where it is false according to default value). When UseOverlay="True" is applied nothing happens. You need to add DP ChangedCallback:

DependencyProperty.Register("UseOverlay", typeof(bool), typeof(ImageView),
                            new PropertyMetadata(false, UseOverlayChangedCallback));

private static void UseOverlayChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    if ((bool) e.NewValue)
        ((ImageView)obj).AddOverlay();
    else
        ((ImageView)obj).HideOverlay();
}


问:
How to Use Scanner to do Different Things with the Tokens
```<code>    String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    Scanner l = new Scanner (line);
    int index = line.lastIndexOf(" ");

    while (l.hasNext())
    {
        String name = l.next();
        char ch = name.charAt(0);
        System.out.print(ch);
    }
    System.out.print(" " + line.substring(index + 1));
</code>```

Example:

User enters the following - Fred John Samuel Smith

The output should be - FJS SMITH

The code doesn't work because the output is this:

FJSS SMITH

How do I split the first 3 words from the last word?

答:
This may be the solution to your question.</p>

```<code>String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    String l[] = line.split(" ");
    int index =0;
while(index<4)
{
if(index<3)
 System.out.print(l[index].charAt(0));
else
  System.out.print(" "+l[3]);

index++;
}
</code>```

Body:
    String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    Scanner l = new Scanner (line);
    int index = line.lastIndexOf(" ");

    while (l.hasNext())
    {
        String name = l.next();
        char ch = name.charAt(0);
        System.out.print(ch);
    }
    System.out.print(" " + line.substring(index + 1));

Example:

User enters the following - Fred John Samuel Smith

The output should be - FJS SMITH

The code doesn't work because the output is this:

FJSS SMITH

How do I split the first 3 words from the last word?

Body:
This may be the solution to your question.

String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    String l[] = line.split(" ");
    int index =0;
while(index<4)
{
if(index<3)
 System.out.print(l[index].charAt(0));
else
  System.out.print(" "+l[3]);

index++;
}


问:
How to validate an SSL Certificate
I have a form that users can enter in a copy of their SSL certificate. Users tend to just enter comments instead of the actual certificate. What would the regex syntax be that I can use to ensure they are entering a valid certificate?</p>

答:
The below regular expression will help you to validate a custom field in WHMCS that requires a valid certificate structure.

```<code>/^(?:(?!-{3,}(?:BEGIN|END) CERTIFICATE)[\s\S])*(-{3,}BEGIN CERTIFICATE(?:(?!-{3,}END CERTIFICATE)[\s\S])*?-{3,}END CERTIFICATE-{3,})(?![\s\S]*?-{3,}BEGIN CERTIFICATE[\s\S]+?-{3,}END CERTIFICATE[\s\S]*?$)/
</code>```

Simply paste that in to the Validation field.

I modified the regular expression found on the answer to this question.

The regular expression from that question can also be used if you have a custom field requiring a Certificate Signing Request:

```<code>/^(?:(?!-{3,}(?:BEGIN|END) NEW CERTIFICATE REQUEST)[\s\S])*(-{3,}BEGIN NEW CERTIFICATE REQUEST(?:(?!-{3,}END NEW CERTIFICATE REQUEST)[\s\S])*?-{3,}END NEW CERTIFICATE REQUEST-{3,})(?![\s\S]*?-{3,}BEGIN NEW CERTIFICATE REQUEST[\s\S]+?-{3,}END NEW CERTIFICATE REQUEST[\s\S]*?$)/
</code>```

Title: How to validate an SSL Certificate

Body:
The below regular expression will help you to validate a custom field in WHMCS that requires a valid certificate structure.

/^(?:(?!-{3,}(?:BEGIN|END) CERTIFICATE)[\s\S])*(-{3,}BEGIN CERTIFICATE(?:(?!-{3,}END CERTIFICATE)[\s\S])*?-{3,}END CERTIFICATE-{3,})(?![\s\S]*?-{3,}BEGIN CERTIFICATE[\s\S]+?-{3,}END CERTIFICATE[\s\S]*?$)/

Simply paste that in to the Validation field.

I modified the regular expression found on the answer to this question.

The regular expression from that question can also be used if you have a custom field requiring a Certificate Signing Request:

/^(?:(?!-{3,}(?:BEGIN|END) NEW CERTIFICATE REQUEST)[\s\S])*(-{3,}BEGIN NEW CERTIFICATE REQUEST(?:(?!-{3,}END NEW CERTIFICATE REQUEST)[\s\S])*?-{3,}END NEW CERTIFICATE REQUEST-{3,})(?![\s\S]*?-{3,}BEGIN NEW CERTIFICATE REQUEST[\s\S]+?-{3,}END NEW CERTIFICATE REQUEST[\s\S]*?$)/