问:
How to match one term (word or sentence) from comma separated list using regex and js?
I have a simple list such as:

Health, Health Care, Health Options

My search term is the word "Health". When searching for "Health" I do not want to match "Health Care" and "Health Options" because technically those are different items on the list.

After reading Regex documentation I figured I was supposed to use a lookbehind to check for preceding text. But from what I understand those options are not present in the JS regex.

In summary I need to match a specific value in a group, where the group is a term before/after a comma.

答:
If you really need to use regex, the following would work:

```<code>var str = "Cat Health, Health, Health Care, Health Options",
    reg = /(?:[^,], )*(Health)(?:, [^,])*/;

alert(str.match(reg)[1]);
// -> Health
</code>```

Regex Explanation:

Non-comma stuff followed by a comma and a space -- repeated 0-n times.

"Health"

Comma, space, non-comma stuff -- repeated 0-n times

Note that there is no lookbehind in Javascript Regex, see:

Positive look behind in JavaScript regular expression

To do it programmatically as suggested in comments (assuming the list items are always separated by a comma then a space):

```<code>var str = "Cat Health, Health, Health Care, Health Options"
var list = str.split(/, /);
var a = list.indexOf("Health");
// a = -1 if not found, otherwise contains the index of "Health" in the list
</code>```

Body:
If you really need to use regex, the following would work:

var str = "Cat Health, Health, Health Care, Health Options",
    reg = /(?:[^,], )*(Health)(?:, [^,])*/;

alert(str.match(reg)[1]);
// -> Health

Regex Explanation:

Non-comma stuff followed by a comma and a space -- repeated 0-n times.

"Health"

Comma, space, non-comma stuff -- repeated 0-n times

Note that there is no lookbehind in Javascript Regex, see:

Positive look behind in JavaScript regular expression

To do it programmatically as suggested in comments (assuming the list items are always separated by a comma then a space):

var str = "Cat Health, Health, Health Care, Health Options"
var list = str.split(/, /);
var a = list.indexOf("Health");
// a = -1 if not found, otherwise contains the index of "Health" in the list


来源: stackexchange

问:
How to make button visible with string holding buttons name
Hey I am trying to make a page where different buttons shows up when the amount in an array is bigger than 0. I was kinda hoping i could make the button name as a string, but that dosnt work. I also looked up controllers and tried to find someone with the same problem but i cant. My code:

```<code>        for (int i = 0; i != amount.Length; i++)
    {
        if (amount[i] > 0)
        {
            string button = "Button" + i;
            Button[i].Visible = true;

        }
    }
</code>```

I feel like if I could make it look like the code over it would look much cleaner than:

```<code>        for (int i = 0; i != amount.Length; i++)
    {
        if (amount[0] > 0)
        {

            button.Visible = true;

        }

       else if (amount[1] > 0)
       {

            button.Visible = true;

        }

#And so on (goes up to whatever the amount of numbers are in the array)...
    }
</code>```

答:
although i do not really understand your question do you mean something like that?</p>

```<code>    string[] buttonNames = new string[3] {"button1", "button2", "button3" };
    for (int i = 0; i != amount.Length; i++)
    {
        if (amount[i] > 0)
        {
            Control button = this.Controls[buttonNames[i] ];
            button.Visible = true;
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hey I am trying to make a page where different buttons shows up when the amount in an array is bigger than 0. I was kinda hoping i could make the button name as a string, but that dosnt work. I also looked up controllers and tried to find someone with the same problem but i cant. My code:

        for (int i = 0; i != amount.Length; i++)
    {
        if (amount[i] > 0)
        {
            string button = "Button" + i;
            Button[i].Visible = true;

        }
    }

I feel like if I could make it look like the code over it would look much cleaner than:

        for (int i = 0; i != amount.Length; i++)
    {
        if (amount[0] > 0)
        {

            button.Visible = true;

        }

       else if (amount[1] > 0)
       {

            button.Visible = true;

        }

#And so on (goes up to whatever the amount of numbers are in the array)...
    }

Body:
although i do not really understand your question do you mean something like that?

    string[] buttonNames = new string[3] {"button1", "button2", "button3" };
    for (int i = 0; i != amount.Length; i++)
    {
        if (amount[i] > 0)
        {
            Control button = this.Controls[buttonNames[i] ];
            button.Visible = true;
        }
    }


问:
How to refresh kartik grid view periodically in yii2
I having a yii2 page with ticket information. Example can be seen here
https://github.com/kartik-v/yii2-dynagrid/issues/97

I would like to be able to refresh the page periodically or when a records change or when a new has been added.

I have tried something like this but it does not work by some reason

```<code>$js = '$("#pageReload").on("pjax:end", function() {
       $.pjax.reload({container:".inbox"});  //Reload GridView
   });';
$this->registerJs($js, $this::POS_READY);
$js2 = 'function refresh() {
$.pjax.reload({container:"#dynagrid-1",timeout: 10000});
};
refresh();';
$this->registerJs($js2, $this::POS_READY);
$.pjax.reload({container: '#idGridView'});
$.pjax.reload({container: '#pjax-container', timeout: 2000});
$script = <<< JS
$.pjax.reload({container: '#av_list-1-pjax', timeout: 2000});
//JS;
$this->registerJs($script);
</code>```

答:
this is my solution to refresh the grid every minute</p>

```<code>setInterval(
function refresh()
{
    $.pjax.reload({
    container:'#task-grid',
    timeout:60000,
})
},10000);
</code>```

Body:
I having a yii2 page with ticket information. Example can be seen here
https://github.com/kartik-v/yii2-dynagrid/issues/97

I would like to be able to refresh the page periodically or when a records change or when a new has been added.

I have tried something like this but it does not work by some reason

$js = '$("#pageReload").on("pjax:end", function() {
       $.pjax.reload({container:".inbox"});  //Reload GridView
   });';
$this->registerJs($js, $this::POS_READY);
$js2 = 'function refresh() {
$.pjax.reload({container:"#dynagrid-1",timeout: 10000});
};
refresh();';
$this->registerJs($js2, $this::POS_READY);
$.pjax.reload({container: '#idGridView'});
$.pjax.reload({container: '#pjax-container', timeout: 2000});
$script = <<< JS
$.pjax.reload({container: '#av_list-1-pjax', timeout: 2000});
//JS;
$this->registerJs($script);

Body:
this is my solution to refresh the grid every minute

setInterval(
function refresh()
{
    $.pjax.reload({
    container:'#task-grid',
    timeout:60000,
})
},10000);


问:
Group columns in a dataframe and subset using a condition
I have a dataframe like this

```<code>ID <- c("ID001","ID001","ID001","ID001","ID001","ID001","ID001",
        "ID002","ID002","ID002","ID002","ID002")
Type <- c("A","A","A","A","A","A","A",
          "B","B","B","B","B")
Measurement <- c("Length","Summary","Breadth","Length","Summary","Breadth","Summary",
                 "Length","Summary","Breadth","Breadth","Summary")
PassFail <- c("PASS","PASS","PASS","FAIL_PTS","FAIL","FAIL_AVG_HI","FAIL",
              "PASS","FAIL_PTS","FAIL","FAIL_AVG_LOW","FAIL")
ToolID <- c("SWP","SWP","SWP","ISP","ISP","IKS","IKS",
            "PSX","PSX","PSX","PZY","PZY")

df <- data.frame(ID,Type,Measurement,PassFail,ToolID)
df

      ID Type Measurement     PassFail ToolID
   ID001    A      Length         PASS    SWP
   ID001    A     Summary         PASS    SWP
   ID001    A     Breadth         PASS    SWP
   ID001    A      Length     FAIL_PTS    ISP
   ID001    A     Summary         FAIL    ISP
   ID001    A     Breadth  FAIL_AVG_HI    IKS
   ID001    A     Summary         FAIL    IKS
   ID002    B      Length         PASS    PSX
   ID002    B     Summary     FAIL_PTS    PSX
   ID002    B     Breadth         FAIL    PSX
   ID002    B     Breadth FAIL_AVG_LOW    PZY
   ID002    B     Summary         FAIL    PZY
</code>```

I am trying to subset this data frame using a condition like this: When the  passfail = 'FAIL_AVG_HI' or 'FAIL_AVG_LOW', I would like to remove the rows in that group (ID,Type,ToolID).

My desired output would look like this

```<code>     ID Type Measurement PassFail ToolID
  ID001    A      Length     PASS    SWP
  ID001    A     Summary     PASS    SWP
  ID001    A     Breadth     PASS    SWP
  ID001    A      Length FAIL_PTS    ISP
  ID001    A     Summary     FAIL    ISP
  ID002    B      Length     PASS    PSX
  ID002    B     Summary FAIL_PTS    PSX
  ID002    B     Breadth     FAIL    PSX
</code>```

I am messing it up with the grouping to remove the rows. I can delete the row that has the above passfail values but how to group them and delete any rows that belong to the group?

I am doing it this way to remove 1 row

```<code>df <- subset(df,df$PassFail != 'FAIL_AVG_HI' | df$PassFail != 'FAIL_AVG_LOW')
</code>```

答:
We can use data.table

```<code>library(data.table)
setDT(df)[, if(!any(PassFail %in% c('FAIL_AVG_HI', 'FAIL_AVG_LOW')))
                  .SD, .(ID, Type, ToolID)]
#       ID Type ToolID Measurement PassFail
#1: ID001    A    SWP      Length     PASS
#2: ID001    A    SWP     Summary     PASS
#3: ID001    A    SWP     Breadth     PASS
#4: ID001    A    ISP      Length FAIL_PTS
#5: ID001    A    ISP     Summary     FAIL
#6: ID002    B    PSX      Length     PASS
#7: ID002    B    PSX     Summary FAIL_PTS
#8: ID002    B    PSX     Breadth     FAIL
</code>```

Body:
I have a dataframe like this

ID <- c("ID001","ID001","ID001","ID001","ID001","ID001","ID001",
        "ID002","ID002","ID002","ID002","ID002")
Type <- c("A","A","A","A","A","A","A",
          "B","B","B","B","B")
Measurement <- c("Length","Summary","Breadth","Length","Summary","Breadth","Summary",
                 "Length","Summary","Breadth","Breadth","Summary")
PassFail <- c("PASS","PASS","PASS","FAIL_PTS","FAIL","FAIL_AVG_HI","FAIL",
              "PASS","FAIL_PTS","FAIL","FAIL_AVG_LOW","FAIL")
ToolID <- c("SWP","SWP","SWP","ISP","ISP","IKS","IKS",
            "PSX","PSX","PSX","PZY","PZY")

df <- data.frame(ID,Type,Measurement,PassFail,ToolID)
df

      ID Type Measurement     PassFail ToolID
   ID001    A      Length         PASS    SWP
   ID001    A     Summary         PASS    SWP
   ID001    A     Breadth         PASS    SWP
   ID001    A      Length     FAIL_PTS    ISP
   ID001    A     Summary         FAIL    ISP
   ID001    A     Breadth  FAIL_AVG_HI    IKS
   ID001    A     Summary         FAIL    IKS
   ID002    B      Length         PASS    PSX
   ID002    B     Summary     FAIL_PTS    PSX
   ID002    B     Breadth         FAIL    PSX
   ID002    B     Breadth FAIL_AVG_LOW    PZY
   ID002    B     Summary         FAIL    PZY

I am trying to subset this data frame using a condition like this: When the  passfail = 'FAIL_AVG_HI' or 'FAIL_AVG_LOW', I would like to remove the rows in that group (ID,Type,ToolID).

My desired output would look like this

     ID Type Measurement PassFail ToolID
  ID001    A      Length     PASS    SWP
  ID001    A     Summary     PASS    SWP
  ID001    A     Breadth     PASS    SWP
  ID001    A      Length FAIL_PTS    ISP
  ID001    A     Summary     FAIL    ISP
  ID002    B      Length     PASS    PSX
  ID002    B     Summary FAIL_PTS    PSX
  ID002    B     Breadth     FAIL    PSX

I am messing it up with the grouping to remove the rows. I can delete the row that has the above passfail values but how to group them and delete any rows that belong to the group?

I am doing it this way to remove 1 row

df <- subset(df,df$PassFail != 'FAIL_AVG_HI' | df$PassFail != 'FAIL_AVG_LOW')

Body:
We can use data.table

library(data.table)
setDT(df)[, if(!any(PassFail %in% c('FAIL_AVG_HI', 'FAIL_AVG_LOW')))
                  .SD, .(ID, Type, ToolID)]
#       ID Type ToolID Measurement PassFail
#1: ID001    A    SWP      Length     PASS
#2: ID001    A    SWP     Summary     PASS
#3: ID001    A    SWP     Breadth     PASS
#4: ID001    A    ISP      Length FAIL_PTS
#5: ID001    A    ISP     Summary     FAIL
#6: ID002    B    PSX      Length     PASS
#7: ID002    B    PSX     Summary FAIL_PTS
#8: ID002    B    PSX     Breadth     FAIL


问:
Extracting values from listbox
I created a UserForm in VBA with 2 ListBoxes.

What I want to do is extract values from the right ListBox (and keep them in temp) and delete every row in another sheet which contains these names.

Writing a code to delete rows is not an issues. I have no clue how to use these selected items in another VBA module. Any ideas?

答:
Actually I would like my code to look more like this:</p>

```<code>For Each c In Range
    If c.Value = [any of values from list box] Then
        c.EntireRow.Delete
    End If
Next c
</code>```

Title: Extracting values from listbox

Body:
Actually I would like my code to look more like this:

For Each c In Range
    If c.Value = [any of values from list box] Then
        c.EntireRow.Delete
    End If
Next c


问:
Visual Studio MAC: CSC Errors
I just updated my Visual Studio Mac version to Preview 4 (7.0 build 1566).

I am getting a lot of errors when compiling a project I could correctly compile before the update.
The erros are all like this one:
CSC: Error CS0518: The predefined type `System.Object' is not defined or imported (CS0518)

Is anyone experiencing the same problems? How could I solve them?

答:
Same issue here.
Checking the compilation command, it seems to refer to .Net portable, despite having selected .Net Standard in Options. Not sure how to change it.</p>

Title: Visual Studio MAC: CSC Errors


问:
What is difference between retrieve data in android from .json , .xml extension?
I know it's basis question. but
Is there any difference between retrieve data from extensions end with .xml  and .json or it's depend on the Response only ?

Is there any difference in speed, quality, etc.. ?

I retrieved data with xml,json but i didn't know the difference,

I use json for big applications or xml ? or both ?

I'm searching for Performance , Quality

答:
You are mixing different layers.

PHP is a programming language.
XML and JSON are standard data formats.
A PHP based webservice can return JSON or XML payloads. Since both are basically text, speed should be similar. You can experiment differences based on how big the payload is (JSON format is less verbose than XML), how complex is and how are you processing it.

Another possibility is that you are attempting to read a PHP webpage. In that case, again, you are not reading PHP. You are reading HTML, CSS, etc.  That's called web scraping. That's slower than reading a standard data format for obvious reasons: You have to format the data in the webpage in order to send it for display.

Ideally, you should never rely on web scraping directly on the device. It's slower, and any changes in the webpage will break the app. In that case, perform the scrap in a server and send a standard payload to the app.


问:
Integration of OpenCover with TFS
I am new to TFS and want to integrate OpenCover with TFS. If any has done this please help!</p>

答:
Since the answer doesn't specify the version of TFS, here is an answer for 2015/2017.

OpenCover can be run from TFS using the Powershell build step. You need to get the contents of the OpenCover NuGet package onto TFS and run OpenCover.console.exe from there.

Since TFS doesn't support the format produced by OpenCover, you need to take one additional step and convert the results to Cobertura format. It's possible using the OpenCoverToCoberturaConverter NuGet package.

I've described the whole process in much more detail on my blog:

http://codewithstyle.info/setting-up-coverage-reports-on-vsts-with-opencover/

Title: Integration of OpenCover with TFS


问:
Ruby OpenSSL RSA decryption failing due to padding check failed
I'm trying to replicate the following python code in ruby.  The python code works fine, the ruby code fails due to "padding check failed".  I can encrypt a string and decrypt it with the private key in Ruby, but the encrypted data I need to work with is being retrieved from elsewhere.  I'm unsure of the library and even language used to encrypt it, but the Python code works.

Working Python code:

```<code>def decrypt_secret(encrypted_base64, private_key):
  key = RSA.importKey(open(private_key, "r").read())
  pkey = PKCS1_OAEP.new(key, hashAlgo=SHA256)
  encrypted_blob = base64.urlsafe_b64decode(encrypted_base64)
  decrypted_string = pkey.decrypt(encrypted_blob)
  return decrypted_string
</code>```

Ruby Code fails "padding check failed"

```<code>def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = pkey.private_decrypt(encrypted_blob, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
  return decrypted_string
end
</code>```

答:
It doesn't look like Ruby's OpenSSL wrapper exposes the option to change the hash function for OAEP. You would need to change the Python code to use SHA-1 (default):</p>

```<code>pkey = PKCS1_OAEP.new(key)
</code>```

Body:
I'm trying to replicate the following python code in ruby.  The python code works fine, the ruby code fails due to "padding check failed".  I can encrypt a string and decrypt it with the private key in Ruby, but the encrypted data I need to work with is being retrieved from elsewhere.  I'm unsure of the library and even language used to encrypt it, but the Python code works.

Working Python code:

def decrypt_secret(encrypted_base64, private_key):
  key = RSA.importKey(open(private_key, "r").read())
  pkey = PKCS1_OAEP.new(key, hashAlgo=SHA256)
  encrypted_blob = base64.urlsafe_b64decode(encrypted_base64)
  decrypted_string = pkey.decrypt(encrypted_blob)
  return decrypted_string

Ruby Code fails "padding check failed"

def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = pkey.private_decrypt(encrypted_blob, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
  return decrypted_string
end

Body:
It doesn't look like Ruby's OpenSSL wrapper exposes the option to change the hash function for OAEP. You would need to change the Python code to use SHA-1 (default):

pkey = PKCS1_OAEP.new(key)


问:
Optimizing scala-spark code by removing "for loop"
I wanted to optimize this code ( scala spark) to remove for loop . How do i do it ?</p>

```<code>var varianceExplained = Array[(Int,Double)]();
var varExplained = Array[(Double)]();//{This one contains double values assigned before}
var sums = 0.00
for(x<-0 to varExplained.length-1)
{sums =sums+varExplained(x)
 varianceExplained +:= (x,sums)
}
</code>```

答:
Not really sure how you would parallelize a set which is reliant on its preceding values... only this I can add is how to remove loops and make it a recursive function as per functional programming best practices.</p>

```<code>  def go(acc: Array[(Int, Double)], iter: Int, sums: Double): Array[(Int, Double)] ={
    if (iter == varExplained.length)acc
    else {
      go((iter, sums+varExplained(iter)) +: acc, iter+1, sums+varExplained(iter))
    }
  }
  go(Array[(Int, Double)](), 0, 0)
</code>```

Body:
I wanted to optimize this code ( scala spark) to remove for loop . How do i do it ?

var varianceExplained = Array[(Int,Double)]();
var varExplained = Array[(Double)]();//{This one contains double values assigned before}
var sums = 0.00
for(x<-0 to varExplained.length-1)
{sums =sums+varExplained(x)
 varianceExplained +:= (x,sums)
}

Body:
Not really sure how you would parallelize a set which is reliant on its preceding values... only this I can add is how to remove loops and make it a recursive function as per functional programming best practices.

  def go(acc: Array[(Int, Double)], iter: Int, sums: Double): Array[(Int, Double)] ={
    if (iter == varExplained.length)acc
    else {
      go((iter, sums+varExplained(iter)) +: acc, iter+1, sums+varExplained(iter))
    }
  }
  go(Array[(Int, Double)](), 0, 0)


问:
i need to make i program that prints out a shuffled deck of cards and a sorted deck of cards
Create a array of random card.
Output this array in a formatted print statement using a toString method (unsorted).
Use the selection sort to sort your array.
Sort from highest card in the deck to the lowest.
Ascending alphabetical order: clubs (lowest), followed by diamonds, hearts, and spades (highest)
 The highest card in the deck is the ACE of Spades, the lowest is the 2 of Clubs.
Output a sorted array using the toString method.
Also print out the number iterations

i am a starter coder and need help with this here is some of what i started.

```<code>public class DeckOfCards2 {
  public static void main(String[] args) {
    int[] deck = new int[52];
    String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    // Initialize cards
    for (int i = 0; i < deck.length; i++) {
      deck[i] = i;
    }

    // Shuffle the cards
    for (int i = 0; i < deck.length; i++) {
      int index = (int)(Math.random() * deck.length);
      int temp = deck[i];
      deck[i] = deck[index];
      deck[index] = temp;
    }

    // Display the all the cards
    for (int i = 0; i < 52; i++) {
      String suit = suits[deck[i] / 13];
      String rank = ranks[deck[i] % 13];
      System.out.println( rank + " of " + suit);
    }
  }
}
</code>```

答:
Your method to randomize works :) You just need to add the sorting. Try something like this: </p>

```<code>   public static void main(String[] args) {
        int[] deck = new int[52];
        String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
        String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

        // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");
        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }
    }
</code>```

Body:
Create a array of random card.
Output this array in a formatted print statement using a toString method (unsorted).
Use the selection sort to sort your array.
Sort from highest card in the deck to the lowest.
Ascending alphabetical order: clubs (lowest), followed by diamonds, hearts, and spades (highest)
 The highest card in the deck is the ACE of Spades, the lowest is the 2 of Clubs.
Output a sorted array using the toString method.
Also print out the number iterations

i am a starter coder and need help with this here is some of what i started.

public class DeckOfCards2 {
  public static void main(String[] args) {
    int[] deck = new int[52];
    String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    // Initialize cards
    for (int i = 0; i < deck.length; i++) {
      deck[i] = i;
    }

    // Shuffle the cards
    for (int i = 0; i < deck.length; i++) {
      int index = (int)(Math.random() * deck.length);
      int temp = deck[i];
      deck[i] = deck[index];
      deck[index] = temp;
    }

    // Display the all the cards
    for (int i = 0; i < 52; i++) {
      String suit = suits[deck[i] / 13];
      String rank = ranks[deck[i] % 13];
      System.out.println( rank + " of " + suit);
    }
  }
}

Body:
Your method to randomize works :) You just need to add the sorting. Try something like this:

   public static void main(String[] args) {
        int[] deck = new int[52];
        String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
        String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

        // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");
        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }
    }


问:
Geocoding street addresses with no suffixes
Situation:
I have been tasked with geocoding and plotting addresses to a map of a city for a friend of the family.

I have a list of over 400 addresses. Included in those addresses are PO Boxes and addresses with Street Number, Direction, Street Name, Street Suffix (some do not have this), City, and Zip Code.

I tried to geocode all of the addresses with Geopy and Nominatim.

Issue:

I noticed that those addresses without street suffixes and PO Boxes could not be geocoded.

What I have done:

I have read most posts dealing with addresses, read the Geopy notes and google searched until the cows came home.

I ended up stumbling across a geocoding website that PO boxes could not be mapped and that street suffix is required for mapping.

http://www.gis.harvard.edu/services/blog/geocoding-best-practices

Question:

Is there a way to search for the street suffix of each street that is missing a street suffix?

Is there another free service or library that can be utilized other than Nominatim and Geopy that can utilize the information I have and not require me to look up each individual street suffix in google maps?

Please advise!

答:
First, speaking to the need to find an address that is missing a street suffix, you need to use address completion from an address validation service. Services that do address validation/verification use postal service data (and other data) and match address search inputs to real addresses. If the search input is not sufficiently specific, address validation services may return a handful of potential matches. Here is an example of a non-specific address (missing the State, zip code, and the street suffix) that returns two real addresses that match the search input. SmartyStreets can normally fill in the missing street suffix.

Second, speaking to the PO Box problem: some address services can give you geocode information, as well as other information that you may believe isn't available. For instance, this search shows the SmartyStreets service matching a PO Box number (that I just made up) to the local post office. The latitude and longitude in the response JSON corresponds to the post office when I search it on Google Maps.

Third, speaking to the problem of having a list of addresses: there are various address services that allow batch processes. For instance, it's a fairly common feature to allow a user to upload a spreadsheet of addresses. Here is the information page for SmartyStreets' tool.

There are multiple address services that can help you do all or some of these things. Depending on the service, they will provide some free functionality or have free tiers if you don't do very many searches. I am not aware of a service that does everything you need for free. You could probably use a few services together, like the Google Maps API to Geopy, etc, but it would take effort to code up a script to put them all together.

Full disclosure: I worked for SmartyStreets.


问:
How to get input values to save to variable in Laravel
Kind of confused about how to capture values as an when they are saved to DB. This is laravel 5.4

In the app\Http\Controllers\Auth, I want to capture the input values that are being saved to the DB.

```<code>protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.
}
</code>```

The reason why I want to capture is because I want to send a curl request with the captured input data to a third party application as soon as a user is created.

Thank you.

答:
you can not executes any thing after your returning statement,

If called from within a function, the return statement immediately
  ends execution of the current function,

rather, you will need to store it in a variable then return it after doing your logging, something like follows :

```<code>protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    $createdUser = User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $createdUser->name;

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.

     return $createdUser;
}
</code>```

update

as long as you don't need a returned data from your DB, you may simple move this two lines :

```<code>$name = $data['name'];

Log::info('Showing user profile for user: '.$name);
</code>```

before returning the creation object :

```<code>protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}
</code>```

Body:
Kind of confused about how to capture values as an when they are saved to DB. This is laravel 5.4

In the app\Http\Controllers\Auth, I want to capture the input values that are being saved to the DB.

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.
}

The reason why I want to capture is because I want to send a curl request with the captured input data to a third party application as soon as a user is created.

Thank you.

Body:
you can not executes any thing after your returning statement,

If called from within a function, the return statement immediately
  ends execution of the current function,

rather, you will need to store it in a variable then return it after doing your logging, something like follows :

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    $createdUser = User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $createdUser->name;

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.

     return $createdUser;
}

update

as long as you don't need a returned data from your DB, you may simple move this two lines :

$name = $data['name'];

Log::info('Showing user profile for user: '.$name);

before returning the creation object :

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}


问:
How to downsize my scss code?
I started writing classes such as:

```<code>.small-bottom-margin { margin-bottom: $margin; }
.small-top-margin { margin-top: $margin; }
.medium-bottom-margin { margin-bottom: $margin *2; }
.medium-top-margin { margin-top: $margin *2; }
.large-bottom-margin { margin-bottom: $margin *4; }
.large-top-margin { margin-top: $margin *4; }
</code>```

Soon I wanted to be able to specify what happened on different screens, such as (for the small bottom margin example):

```<code>@media #{$small-only} { .small-bottom-margin-sm { margin-bottom: $margin; }}
@media #{$medium-only} { .small-bottom-margin-md { margin-bottom: $margin; }}
@media #{$large-only} { .small-bottom-margin-lg { margin-bottom: $margin; }}
@media #{$small-up} { .small-bottom-margin-sm-up { margin-bottom: $margin; }}
@media #{$medium-up} { .small-bottom-margin-md-up { margin-bottom: $margin; }}
@media #{$large-up} { .small-bottom-margin-lg-up { margin-bottom: $margin; }}
@media #{$medium-down} { .small-bottom-margin-sm-mp { margin-bottom: $margin; }}
</code>```

... etc for all the margin sizes (medium and large), and for the top margin too.

I find this extremely practical in terms of readability of my html + speed to add margins through my app, which is often a pain when you have a complicated layout, but it seems awfully long to write in my css.

Is it bad practice to do this?
  If not, is there some kind of css function that would allow me to automatically generate all this code?

答:
Iterate through different sizes like this:</p>

```<code>   $sizes: (
      'sm': $small-only,
      'md': $medium-only,
      'lg': $large-only,
      'sm-up': $small-up,
      'md-up': $medium-up,
      'lg-up': $large-up,
      'sm-mp': $medium-down
    );

    @each $key, $value in $sizes {
      @media #{$value} { .small-bottom-margin-#{$key} { margin-bottom: $margin; }}
    }
</code>```

Title: How to downsize my scss code?

Body:
I started writing classes such as:

.small-bottom-margin { margin-bottom: $margin; }
.small-top-margin { margin-top: $margin; }
.medium-bottom-margin { margin-bottom: $margin *2; }
.medium-top-margin { margin-top: $margin *2; }
.large-bottom-margin { margin-bottom: $margin *4; }
.large-top-margin { margin-top: $margin *4; }

Soon I wanted to be able to specify what happened on different screens, such as (for the small bottom margin example):

@media #{$small-only} { .small-bottom-margin-sm { margin-bottom: $margin; }}
@media #{$medium-only} { .small-bottom-margin-md { margin-bottom: $margin; }}
@media #{$large-only} { .small-bottom-margin-lg { margin-bottom: $margin; }}
@media #{$small-up} { .small-bottom-margin-sm-up { margin-bottom: $margin; }}
@media #{$medium-up} { .small-bottom-margin-md-up { margin-bottom: $margin; }}
@media #{$large-up} { .small-bottom-margin-lg-up { margin-bottom: $margin; }}
@media #{$medium-down} { .small-bottom-margin-sm-mp { margin-bottom: $margin; }}

... etc for all the margin sizes (medium and large), and for the top margin too.

I find this extremely practical in terms of readability of my html + speed to add margins through my app, which is often a pain when you have a complicated layout, but it seems awfully long to write in my css.

Is it bad practice to do this?
  If not, is there some kind of css function that would allow me to automatically generate all this code?

Body:
Iterate through different sizes like this:

   $sizes: (
      'sm': $small-only,
      'md': $medium-only,
      'lg': $large-only,
      'sm-up': $small-up,
      'md-up': $medium-up,
      'lg-up': $large-up,
      'sm-mp': $medium-down
    );

    @each $key, $value in $sizes {
      @media #{$value} { .small-bottom-margin-#{$key} { margin-bottom: $margin; }}
    }


问:
Spring Boot Jasper Report Blank PDF
I have an web application. I use Spring Boot 1.3.3, AngularJS, and Jasper 5.6.0. When i try to download jasper report, i get blank PDF page. My code is:

```<code>String jasperAdi = "yillikPlan.jasper";
StringBuffer pathMain = new StringBuffer();
pathMain.append(this.getClass().getResource("/static/jasper").getPath());
String jasperFileName = pathMain.toString() + File.separator + jasperAdi;
File jasperFile = new File(jasperFileName);
JasperReport report = (JasperReport) JRLoader.loadObject(jasperFile);
JasperPrint jasperPrint = JasperFillManager.fillReport(report, param, new JRBeanCollectionDataSource(ckModelList));
if (jasperPrint != null) {
    byte[] pdfReport = JasperExportManager.exportReportToPdf(jasperPrint);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setContentDispositionFormData("yillikPlan.pdf", "yillikPlan.pdf");
    ResponseEntity<byte[]> respon = new ResponseEntity<byte[]>(pdfReport, headers, HttpStatus.OK);
    return respon;

}
</code>```

My jasper file location is /static/jasper. ckModelList is a java.util.List. param is a Hashmap which i push report parameters.

How i fix this problem.

答:
I was with the same issue when I tried to start using jasper in my Spring Boot application but it had nothing wrong with my java code it was just the propertie 'When no Data type' of the report. I was just testing, therefore I don't have any data only a label it took some hours to realize it.

If you have any problem understanding my "improving" english, please let me know that I'll try to explain better.

Report Properties Image

Title: Spring Boot Jasper Report Blank PDF

Body:
I have an web application. I use Spring Boot 1.3.3, AngularJS, and Jasper 5.6.0. When i try to download jasper report, i get blank PDF page. My code is:

String jasperAdi = "yillikPlan.jasper";
StringBuffer pathMain = new StringBuffer();
pathMain.append(this.getClass().getResource("/static/jasper").getPath());
String jasperFileName = pathMain.toString() + File.separator + jasperAdi;
File jasperFile = new File(jasperFileName);
JasperReport report = (JasperReport) JRLoader.loadObject(jasperFile);
JasperPrint jasperPrint = JasperFillManager.fillReport(report, param, new JRBeanCollectionDataSource(ckModelList));
if (jasperPrint != null) {
    byte[] pdfReport = JasperExportManager.exportReportToPdf(jasperPrint);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setContentDispositionFormData("yillikPlan.pdf", "yillikPlan.pdf");
    ResponseEntity<byte[]> respon = new ResponseEntity<byte[]>(pdfReport, headers, HttpStatus.OK);
    return respon;

}

My jasper file location is /static/jasper. ckModelList is a java.util.List. param is a Hashmap which i push report parameters.

How i fix this problem.


问:
Generate a random point on an elliptical curve
I'm writing a program which randomly chooses two integers within a certain interval. I also wrote a class (which I didn't add below) which uses two numbers 'a' and 'b' and creates an elliptical curve of the form:
y^2 = x^3 + ax + b

I've written the following to create the two random numbers.

```<code>def numbers():
n = 1
while n>0:
    a = random.randint(-100,100)
    b = random.randint(-100,100)
    if -16 * (4 * a ** 3 + 27 * b ** 2) != 0:
        result = [a,b]
        return result
    n = n+1
</code>```

Now I would like to generate a random point on this elliptical curve. How do I do that?

答:
The curve has an infinite length, as for every y ϵ ℝ there is at least one x ϵ ℝ so that (x, y) is on the curve. So if we speak of a random point on the curve we cannot hope to have a homogeneous distribution of the random point over the whole curve.

But if that is not important, you could take a random value for y within some range, and then calculate the roots of the following function:

    f(x) = x3 + ax + b - y2

This will result in three roots, of which possibly two are complex (not real numbers). You can take a random real root from that. This will be the x coordinate for the random point.

With the help of numpy, getting the roots is easy, so this is the function for getting a random point on the curve, given values for a and b:

```<code>def randomPoint(a, b):
    y = random.randint(-100,100)
    # Get roots of:  f(x) = x^3 + ax + b - y^2
    roots = numpy.roots([1, 0, a, b - y**2])
    # 3 roots are returned, but ignore potential complex roots
    # At least one will be real
    roots = [val.real for val in roots if val.imag == 0]
    # Choose a random root among those real root(s)
    x = random.choice(roots)
    return [x, y]
</code>```

See it run on repl.it.

Body:
I'm writing a program which randomly chooses two integers within a certain interval. I also wrote a class (which I didn't add below) which uses two numbers 'a' and 'b' and creates an elliptical curve of the form:
y^2 = x^3 + ax + b

I've written the following to create the two random numbers.

def numbers():
n = 1
while n>0:
    a = random.randint(-100,100)
    b = random.randint(-100,100)
    if -16 * (4 * a ** 3 + 27 * b ** 2) != 0:
        result = [a,b]
        return result
    n = n+1

Now I would like to generate a random point on this elliptical curve. How do I do that?

Body:
The curve has an infinite length, as for every y ϵ ℝ there is at least one x ϵ ℝ so that (x, y) is on the curve. So if we speak of a random point on the curve we cannot hope to have a homogeneous distribution of the random point over the whole curve.

But if that is not important, you could take a random value for y within some range, and then calculate the roots of the following function:

    f(x) = x3 + ax + b - y2

This will result in three roots, of which possibly two are complex (not real numbers). You can take a random real root from that. This will be the x coordinate for the random point.

With the help of numpy, getting the roots is easy, so this is the function for getting a random point on the curve, given values for a and b:

def randomPoint(a, b):
    y = random.randint(-100,100)
    # Get roots of:  f(x) = x^3 + ax + b - y^2
    roots = numpy.roots([1, 0, a, b - y**2])
    # 3 roots are returned, but ignore potential complex roots
    # At least one will be real
    roots = [val.real for val in roots if val.imag == 0]
    # Choose a random root among those real root(s)
    x = random.choice(roots)
    return [x, y]

See it run on repl.it.


问:
fiddler websocket unreadable code
I am using fiddler(version v4.6.3.44034) to capture network traffic of websocket,but the content is unreadable code.Like this:

```<code>PayloadString:  �Vr���su��KLNN-(�-K-*��ϳ2�3�1�3���HM,*�MJM,�2413:20:24:4763 WSSession87.WebSocket'WebSocket #87'
MessageID:  Server.3
MessageType:    Text
PayloadString:  J�Vr���suqu��+K-*��ϳ2�3���HM,*�MJM,�2�1��+-N-��K�M�JL��̋�R P�13:20:28:5903 WSSession87.WebSocket'WebSocket #87'
MessageID:  Client.4
MessageType:    Text
PayloadString:  �V
u
v�tr���L�*.M�*HI-.��K,��_�_�������M,)-F613:20:28:5953 WSSession87.WebSocket'WebSocket #87'
MessageID:  Client.5
MessageType:    Text
PayloadString:  t�?o�1ƿ��X��q��ЁnL�c�m+�G՞XP�;>�"e���?���p{����W�����*_��a���t���tw�?/�ߏ�Ա��}�>���x^�L�w�ç�x�է�����p:�2�z֌}N�WΛ�o�2y�   ��m0�TXM��u�E�����з2��u��<P��>H�V�С��tp_�eR��z�*�\�*Ў]��z��Z��a�b�J,�
�����w��}�m��
W�fPԦb!-Ev��גR�%�Z�4��l�c`�ov�z��$� �6���x#��RAmmiU�!%
X�y�滠�fT`
</code>```

How to make it right? I searching from google,no one encount the problem.

答:
The problem is that Fiddler (in my case v4.6.20171.7553) is not uncompressing the websocket traffic.  As a workaround, disable websocket compression on the server side.  In my case, I was using tomcat and added this jvm option:

```<code>-Dorg.apache.tomcat.websocket.DISABLE_BUILTIN_EXTENSIONS=true
</code>```

Note that disabling http compression in server.xml did not work for me.

See this link for additional information.

Title: fiddler websocket unreadable code

Body:
I am using fiddler(version v4.6.3.44034) to capture network traffic of websocket,but the content is unreadable code.Like this:

PayloadString:  �Vr���su��KLNN-(�-K-*��ϳ2�3�1�3���HM,*�MJM,�2413:20:24:4763 WSSession87.WebSocket'WebSocket #87'
MessageID:  Server.3
MessageType:    Text
PayloadString:  J�Vr���suqu��+K-*��ϳ2�3���HM,*�MJM,�2�1��+-N-��K�M�JL��̋�R P�13:20:28:5903 WSSession87.WebSocket'WebSocket #87'
MessageID:  Client.4
MessageType:    Text
PayloadString:  �V
u
v�tr���L�*.M�*HI-.��K,��_�_�������M,)-F613:20:28:5953 WSSession87.WebSocket'WebSocket #87'
MessageID:  Client.5
MessageType:    Text
PayloadString:  t�?o�1ƿ��X��q��ЁnL�c�m+�G՞XP�;>�"e���?���p{����W�����*_��a���t���tw�?/�ߏ�Ա��}�>���x^�L�w�ç�x�է�����p:�2�z֌}N�WΛ�o�2y�   ��m0�TXM��u�E�����з2��u��
H�V�С��tp_�eR��z�*�\�*Ў]��z��Z��a�b�J,�
�����w��}�m��
W�fPԦb!-Ev��גR�%�Z�4��l�c`�ov�z��$� �6���x#��RAmmiU�!%
X�y�滠�fT`

How to make it right? I searching from google,no one encount the problem.

Body:
The problem is that Fiddler (in my case v4.6.20171.7553) is not uncompressing the websocket traffic.  As a workaround, disable websocket compression on the server side.  In my case, I was using tomcat and added this jvm option:

-Dorg.apache.tomcat.websocket.DISABLE_BUILTIN_EXTENSIONS=true

Note that disabling http compression in server.xml did not work for me.

See this link for additional information.


问:
How to connect to a SAP System using sapjco3 and Eclipse?
I need to connect to SAP Systems via standard BAPI calls. I already installed JCo (sapjco3) and added the .jar to my build path in Eclipse.

But due to the fact that I am rather a beginner regarding network/server programming, I have no idea how to setup a connection between Eclipse and the SAP Systems...can anyone provide a basic solution or some ideas for that?

Thank you and greetings!

答:
Setting Up Of SAP Connection using SAP JCO3 in Eclipse IDE One Can Setup SAP Application connection with Java Application using below steps:

Steps to Produce:

Download SAP Java connectors SAPJCO3 (32bit or 64bit based on your System architecture) from SAP Marketplace.

Create a separate folder and keep the downloaded sapjco3 zip file and unzip it.

Copy the location of sapjco3.jar file in the newly created folder.

Now go to Environment Variables and create system variables CLASSPATH if not  exist and add location of sapjco3.jar followed by ; ex: D:\sapjco3-NTAMD64-3.0.16\sapjco3.jar;

Edit System Variable PATH and add newly created folder location followed by ; ex: D:\sapjco3-NTAMD64-3.0.16;

Now Go to Eclipse and Create a new project.

Create a new Class with any name for connecting to SAP application.

Right Click on Newly created project and go to build path and click Configure Build Path.

Click on Libraries and Add External Jars.

Now select sapjco3.jar file just downloaded.

Make your class name as same as you created in step 7.

Write the Java code

ContentLicense: CC BY-SA 4.0


问:
An example of a javascript function passing JSON data to a Java applet
I have just started developing applets. I want to be able to pass (JSON) data from a javascript function, to a method in my applet.

Although I have searched, I cannot find a suitable example that shows how to do this. Can someone please either show a link to a resource that shows how to do that, or paste a few lines in here to show how to do that.

Also, I have the ff questions:

is there a limit to the size of JSON string that can be passed from JSON to the applet? (if yes - what is it?)

Is it possible to compress (zip) a long string before passing it from JSON to the applet?

答:
On the JavaScript side, you should use JSON2 to convert your data to JSON text, using the code

```<code>var jsn = JSON.stringify({"x": "y"});
</code>```

Then you pass it to the applet:

```<code>var applet = document.getElementById("myApplet");
applet.setJSONData(jsn);
</code>```

You need, of course, to have a public method on your applet that you can call.  On the Java side, you can use Jackson to parse the JSON to Java hashmaps or to beans:

```<code>public class MyApplet extends JApplet {
    public void setJSONData(String data) {
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(data, Map.class);
        // TODO sth with map
    };
}
</code>```

Be careful with encodings of non-ASCII characters, it seems that the JSON produced in the browser is not always UTF-8, it may depend on browser vendor or HTML page encoding.

If you are really adventurous you could experiment with JSObject in Java Plugin 2, instead of using JSON.

ContentLicense: CC BY-SA 2.5

Body:
On the JavaScript side, you should use JSON2 to convert your data to JSON text, using the code

var jsn = JSON.stringify({"x": "y"});

Then you pass it to the applet:

var applet = document.getElementById("myApplet");
applet.setJSONData(jsn);

You need, of course, to have a public method on your applet that you can call.  On the Java side, you can use Jackson to parse the JSON to Java hashmaps or to beans:

public class MyApplet extends JApplet {
    public void setJSONData(String data) {
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(data, Map.class);
        // TODO sth with map
    };
}

Be careful with encodings of non-ASCII characters, it seems that the JSON produced in the browser is not always UTF-8, it may depend on browser vendor or HTML page encoding.

If you are really adventurous you could experiment with JSObject in Java Plugin 2, instead of using JSON.


问:
HighCharts: display the y-axis labels in percentage instead of the absolute count for basic column charts
I just started using highcharts and I am  trying to figure out a way to display the y-axis label in % instead of the actual values/counts for a Basic Column chart. Is there a way I can do that?Can someone please suggest me something.

Thanks

答:
You can change the count to a distribution percentage by taking the sum of each step division and dividing by count.

Here is the Highcharts example histogram() function modified to show percentage, make sure to set yAxis to max 1. If you do not want decimal percentage multiply by 100.

```<code>function histogram(data, step) {
    var histo = {},
        x,
        i,
        sum = 0,
        arr = [];

    // Group down
    for (i = 0; i < data.length; i++) {
        x = Math.floor(data[i][0] / step) * step;
        if (!histo[x]) {
        histo[x] = 0;
       }
        histo[x]++;
    }

    // Make the histo group into an array
    for (x in histo) {
        if (histo.hasOwnProperty((x))) {
            arr.push([parseFloat(x), histo[x]]);
        }
    }

    // find sum
    for (i = 0; i < arr.length; i++) {
            sum += arr[i][1];
       }

    // calculate percent
    for (i = 0; i < arr.length; i++) {
            arr[i][1] = arr[i][1]/sum ;
        }

    // sort the array
    arr.sort(function (a, b) {
        return a[0] - b[0];
    });

    return arr;
}
</code>```

fiddle: http://jsfiddle.net/jamie_farrell/xy7uogz4/2/

Body:
You can change the count to a distribution percentage by taking the sum of each step division and dividing by count.

Here is the Highcharts example histogram() function modified to show percentage, make sure to set yAxis to max 1. If you do not want decimal percentage multiply by 100.

function histogram(data, step) {
    var histo = {},
        x,
        i,
        sum = 0,
        arr = [];

    // Group down
    for (i = 0; i < data.length; i++) {
        x = Math.floor(data[i][0] / step) * step;
        if (!histo[x]) {
        histo[x] = 0;
       }
        histo[x]++;
    }

    // Make the histo group into an array
    for (x in histo) {
        if (histo.hasOwnProperty((x))) {
            arr.push([parseFloat(x), histo[x]]);
        }
    }

    // find sum
    for (i = 0; i < arr.length; i++) {
            sum += arr[i][1];
       }

    // calculate percent
    for (i = 0; i < arr.length; i++) {
            arr[i][1] = arr[i][1]/sum ;
        }

    // sort the array
    arr.sort(function (a, b) {
        return a[0] - b[0];
    });

    return arr;
}

fiddle: http://jsfiddle.net/jamie_farrell/xy7uogz4/2/


问:
Left excluding join in sequelize
I have two tables, where one table has the ID of the other. 1:1 relation.
So something like

```<code>EventFeedback
    somePrimaryKey
    userEventID
UserEvent
    userEventID
</code>```

Sequalize has the relation defined with

```<code>models.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });
</code>```

I need all entries in UserEvent that do not have an entry in EventFeedback, which is an exclusionary join.
Stealing images from this article because they have nice individual images:

They even give example code!

```<code>SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
</code>```

How do I do this in sequelize?
Do I just need to do a left join and process it manually?

答:
You need to eager load EventFeedback when querying UserEvent and add proper where clause. You also need to define that EventFeedback is not required in the result so the query will generate LEFT JOIN instead INNER JOIN

UserEvent.all({
    include: [
        model: EventFeedback,
        required: false, // do not generate INNER JOIN
        attributes: [] // do not return any columns of the EventFeedback table
    ],
    where: sequelize.where(
        sequelize.col('EventFeedback.userEventID'),
        'IS',
        null
    )
}).then(userEvents => {
    // user events...
});
```

In the code above the sequelize is an instance of Sequelize with model defined in it. You can also refer to the documentation of sequelize.where() and sequelize.col() methods.

Title: Left excluding join in sequelize

Body:
I have two tables, where one table has the ID of the other. 1:1 relation.
So something like

EventFeedback
    somePrimaryKey
    userEventID
UserEvent
    userEventID

Sequalize has the relation defined with

models.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });

I need all entries in UserEvent that do not have an entry in EventFeedback, which is an exclusionary join.
Stealing images from this article because they have nice individual images:

They even give example code!

SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL

How do I do this in sequelize?
Do I just need to do a left join and process it manually?

Body:
You need to eager load EventFeedback when querying UserEvent and add proper where clause. You also need to define that EventFeedback is not required in the result so the query will generate LEFT JOIN instead INNER JOIN

UserEvent.all({
    include: [
        model: EventFeedback,
        required: false, // do not generate INNER JOIN
        attributes: [] // do not return any columns of the EventFeedback table
    ],
    where: sequelize.where(
        sequelize.col('EventFeedback.userEventID'),
        'IS',
        null
    )
}).then(userEvents => {
    // user events...
});

In the code above the sequelize is an instance of Sequelize with model defined in it. You can also refer to the documentation of sequelize.where() and sequelize.col() methods.


问:
How can I update NodeJS and NPM to their latest versions?

I just installed Node.js & NPM (Node Package Manager)

I installed NPM for access to additional Node.js Modules.

After I installed Node.js & NPM I noticed that neither were the latest versions available.

I would like to know: How do I upgrade Node.js, NPM, and my Node.js Modules to their latest versions?

Do I need to uninstall Node.js & NPM and reinstall the latest versions?

Here is the link to what I have tried so far. This link is a section from npm.

答: I have developed a very simple and fast package to do this kind of update, atualiza can deal with global and project packages. In the later you can choose between the newest version or the bigger version that matches your current package.json's rule. For global packages you don't have a rule so atualiza will upgrade to newest always.


问:
Is It Possible to Make Every Instance of a Word on a Website Non-Breaking?
We have a hyphenated word that we use frequently on our website and we never want it to wrap or break - we always want the two parts of the word on the same line.

Is there a way to make every instance of this word on the site non-breaking or do I have to do it with something like "white-space: nowrap" in a span around every instance of the word?

Ideally, would love to be able to do an update where every instance of the word that exists on the site becomes non-breaking, without having to manually go and update each word.

Thanks!

答:
Similar to the non-breaking space  , look into the non-breaking hyphen ‑:

```<code>Hello‑World
</code>```

This will render as Hello‑World, however it won't be broken up in two lines.

Body:
Similar to the non-breaking space &nbsp;, look into the non-breaking hyphen &#8209;:

Hello&#8209;World

This will render as Hello‑World, however it won't be broken up in two lines.


问:
HTML / CSS - Custom made image border
First of all, I would like to point out that I'm somewhat new to CSS :)

I'm trying to make a custom image border around an image, but I just can't figure out where did it all went wrong.

Basically, I need to make this happen:

Pic of the final result

, and this is the code that I came up with:

```<code><div class="AboutMeImage">
<a href="https://s22.postimg.org/ma6wrg5r5/girl-in-winter.jpg">
<img class="test-img img-responsive" src="https://s22.postimg.org/ma6wrg5r5/girl-in-winter.jpg" alt="test photo" />
 </a>
</div>

.AboutMeImage {
clear: both;
margin-left:auto;
margin-right: auto;
height: auto;
width: 40%;
}

.test_img {
border: 10px solid transparent;
border-image: url(https://s24.postimg.org/tpxcnhk51/image_holder1.png) 602 774 0 0 stretch;
</code>```

}

```<code>.img-responsive {
display: block;
height: auto;
max-width: 100%;
}
</code>```

https://jsfiddle.net/KC87/956purro/6/

Please help!

答:
First of all your class name is wrong in css, in html you have test-img and in css you are writing it as test_img

Please apply this style.

```<code>.test-img {
  border: 10px solid #3778ff;
  height: 40vh;
  border-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/652/pink-doily-bdr.png") 30;
  }
</code>```

working Example

https://jsfiddle.net/bilawalkhan/956purro/9/

Title: HTML / CSS - Custom made image border

Body:
First of all, I would like to point out that I'm somewhat new to CSS :)

I'm trying to make a custom image border around an image, but I just can't figure out where did it all went wrong.

Basically, I need to make this happen:

Pic of the final result

, and this is the code that I came up with:

.AboutMeImage {
clear: both;
margin-left:auto;
margin-right: auto;
height: auto;
width: 40%;
}

.test_img {
border: 10px solid transparent;
border-image: url(https://s24.postimg.org/tpxcnhk51/image_holder1.png) 602 774 0 0 stretch;

}

.img-responsive {
display: block;
height: auto;
max-width: 100%;
}

https://jsfiddle.net/KC87/956purro/6/

Please help!

Body:
First of all your class name is wrong in css, in html you have test-img and in css you are writing it as test_img

Please apply this style.

.test-img {
  border: 10px solid #3778ff;
  height: 40vh;
  border-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/652/pink-doily-bdr.png") 30;
  }

working Example

https://jsfiddle.net/bilawalkhan/956purro/9/


问:
How to enable automatic code reloading in Rails
Is there a way to do 'hot code reloading' with a Rails application in the development environment?

For example: I'm working on a Rails application, I add a few lines of css in a stylesheet, I look at the browser to see the modified styling. As of right now I have to refresh the page with cmd-r or by clicking the refresh button.

Is there a way to get the page to reload automatically when changes are made?

This works nicely in the Phoenix web framework (and I'm sure Phoenix isn't the only framework in this feature). How could a feature like this be enabled in Ruby on Rails?

答:
I am using this setup reloads all assets, js, css, ruby files

in Gemfile

```<code>group :development, :test do
  gem 'guard-livereload', '~> 2.5', require: false
end

group :development do
 gem 'listen'
 gem 'guard'
 gem 'guard-zeus'
 gem 'rack-livereload'
end
</code>```

insert this in your development.rb

```<code>config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload
</code>```

i have this in my guard file

```<code># A sample Guardfile
# More info at https://github.com/guard/guard#readme

## Uncomment and set this to only include directories you want to watch
# directories %w(app lib config test spec features) \
#  .select{|d| Dir.exists?(d) ? d : UI.warning("Directory #{d} does not exist")}

## Note: if you are using the `directories` clause above and you are not
## watching the project directory ('.'), then you will want to move
## the Guardfile to a watched dir and symlink it back, e.g.
#
#  $ mkdir config
#  $ mv Guardfile config/
#  $ ln -s config/Guardfile .
#
# and, you'll have to watch "config/Guardfile" instead of "Guardfile"

guard 'livereload' do
  extensions = {
    css: :css,
    scss: :css,
    sass: :css,
    js: :js,
    coffee: :js,
    html: :html,
    png: :png,
    gif: :gif,
    jpg: :jpg,
    jpeg: :jpeg,
    # less: :less, # uncomment if you want LESS stylesheets done in browser
  }

  rails_view_exts = %w(erb haml slim)

  # file types LiveReload may optimize refresh for
  compiled_exts = extensions.values.uniq
  watch(%r{public/.+\.(#{compiled_exts * '|'})})

  extensions.each do |ext, type|
    watch(%r{
          (?:app|vendor)
          (?:/assets/\w+/(?<path>[^.]+) # path+base without extension
           (?<ext>\.#{ext})) # matching extension (must be first encountered)
          (?:\.\w+|$) # other extensions
          }x) do |m|
      path = m[1]
      "/assets/#{path}.#{type}"
    end
  end

  # file needing a full reload of the page anyway
  watch(%r{app/views/.+\.(#{rails_view_exts * '|'})$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{config/locales/.+\.yml})
end

guard 'zeus' do
  require 'ostruct'

  rspec = OpenStruct.new
  # rspec.spec_dir = 'spec'
  # rspec.spec = ->(m) { "#{rspec.spec_dir}/#{m}_spec.rb" }
  # rspec.spec_helper = "#{rspec.spec_dir}/spec_helper.rb"

  # matchers
  # rspec.spec_files = /^#{rspec.spec_dir}\/.+_spec\.rb$/

  # Ruby apps
  ruby = OpenStruct.new
  ruby.lib_files = /^(lib\/.+)\.rb$/

  # watch(rspec.spec_files)
  # watch(rspec.spec_helper) { rspec.spec_dir }
  # watch(ruby.lib_files) { |m| rspec.spec.call(m[1]) }

  # Rails example
  rails = OpenStruct.new
  rails.app_files = /^app\/(.+)\.rb$/
  rails.views_n_layouts = /^app\/(.+(?:\.erb|\.haml|\.slim))$/
  rails.controllers = %r{^app/controllers/(.+)_controller\.rb$}

  # watch(rails.app_files) { |m| rspec.spec.call(m[1]) }
  # watch(rails.views_n_layouts) { |m| rspec.spec.call(m[1]) }
  # watch(rails.controllers) do |m|
  #   [
  #     rspec.spec.call("routing/#{m[1]}_routing"),
  #     rspec.spec.call("controllers/#{m[1]}_controller"),
  #     rspec.spec.call("acceptance/#{m[1]}")
  #   ]
  # end
end
</code>```

I am using zeus instead of spring on this setup.

Run guard

Open localhost:3000 and you are good to go.

This should resolve your question, and have blazing reload times better than browserify.

I commented out guard looking at test directories if you want you can uncomment those lines if your are doing TDD.

Body:
I am using this setup reloads all assets, js, css, ruby files

in Gemfile

group :development, :test do
  gem 'guard-livereload', '~> 2.5', require: false
end

group :development do
 gem 'listen'
 gem 'guard'
 gem 'guard-zeus'
 gem 'rack-livereload'
end

insert this in your development.rb

config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload

i have this in my guard file

# A sample Guardfile
# More info at https://github.com/guard/guard#readme

## Uncomment and set this to only include directories you want to watch
# directories %w(app lib config test spec features) \
#  .select{|d| Dir.exists?(d) ? d : UI.warning("Directory #{d} does not exist")}

## Note: if you are using the `directories` clause above and you are not
## watching the project directory ('.'), then you will want to move
## the Guardfile to a watched dir and symlink it back, e.g.
#
#  $ mkdir config
#  $ mv Guardfile config/
#  $ ln -s config/Guardfile .
#
# and, you'll have to watch "config/Guardfile" instead of "Guardfile"

guard 'livereload' do
  extensions = {
    css: :css,
    scss: :css,
    sass: :css,
    js: :js,
    coffee: :js,
    html: :html,
    png: :png,
    gif: :gif,
    jpg: :jpg,
    jpeg: :jpeg,
    # less: :less, # uncomment if you want LESS stylesheets done in browser
  }

  rails_view_exts = %w(erb haml slim)

  # file types LiveReload may optimize refresh for
  compiled_exts = extensions.values.uniq
  watch(%r{public/.+\.(#{compiled_exts * '|'})})

  extensions.each do |ext, type|
    watch(%r{
          (?:app|vendor)
          (?:/assets/\w+/(?<path>[^.]+) # path+base without extension
           (?<ext>\.#{ext})) # matching extension (must be first encountered)
          (?:\.\w+|$) # other extensions
          }x) do |m|
      path = m[1]
      "/assets/#{path}.#{type}"
    end
  end

  # file needing a full reload of the page anyway
  watch(%r{app/views/.+\.(#{rails_view_exts * '|'})$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{config/locales/.+\.yml})
end

guard 'zeus' do
  require 'ostruct'

  rspec = OpenStruct.new
  # rspec.spec_dir = 'spec'
  # rspec.spec = ->(m) { "#{rspec.spec_dir}/#{m}_spec.rb" }
  # rspec.spec_helper = "#{rspec.spec_dir}/spec_helper.rb"

  # matchers
  # rspec.spec_files = /^#{rspec.spec_dir}\/.+_spec\.rb$/

  # Ruby apps
  ruby = OpenStruct.new
  ruby.lib_files = /^(lib\/.+)\.rb$/

  # watch(rspec.spec_files)
  # watch(rspec.spec_helper) { rspec.spec_dir }
  # watch(ruby.lib_files) { |m| rspec.spec.call(m[1]) }

  # Rails example
  rails = OpenStruct.new
  rails.app_files = /^app\/(.+)\.rb$/
  rails.views_n_layouts = /^app\/(.+(?:\.erb|\.haml|\.slim))$/
  rails.controllers = %r{^app/controllers/(.+)_controller\.rb$}

  # watch(rails.app_files) { |m| rspec.spec.call(m[1]) }
  # watch(rails.views_n_layouts) { |m| rspec.spec.call(m[1]) }
  # watch(rails.controllers) do |m|
  #   [
  #     rspec.spec.call("routing/#{m[1]}_routing"),
  #     rspec.spec.call("controllers/#{m[1]}_controller"),
  #     rspec.spec.call("acceptance/#{m[1]}")
  #   ]
  # end
end

I am using zeus instead of spring on this setup.

Run guard

Open localhost:3000 and you are good to go.

This should resolve your question, and have blazing reload times better than browserify.

I commented out guard looking at test directories if you want you can uncomment those lines if your are doing TDD.


问:
Implementing global ranking system based on each user's personal ranking. (Rails project)
Ok, so I have around 20 teams and every person ranks Up and Down each Team in his personal ranking list. Like the following format

```<code>    -Barcelona "Move up on the list" "Move Down on the list"
    -Arsenal "Move up" "Move Down"
    -Liverpool "Move up" "Move Down"
</code>```

So in this example, for this particular user, Barcelona has the rank 1, Arsenal rank 2 etc.

Now I want to create a global ranking system, after taking into consideration each individual ranking list.

How do I, logically, go about that?
Smaller rank means higher position, so I can't just take the sum and see which is bigger. Or can I take a sum and see which is smaller?

I thought I could add a "global ranking" integer in each team and see which is smaller, but is this approach right?

答:
You can use averages to represent the global_rankings which would also make it relatively simple to keep the global_rankings up to date.

If your global_ranking is the average rank of that team (sum of rank indexes from each list for given team/number of lists) then the value of each list change on the global_ranking is 1/number of lists.

This means that moving a team up on a list would need to reduce their global_ranking by 1/number of lists while the team that moved down on the list would need to have its global_ranking increased by 1/number of lists (Assuming rank index grows bigger as move down the list).

As long as each new list is initialized to have the same order as the current global_ranking this should keep accurate.

Even so, you may still want to periodically (maybe nightly) recalculate the averages/global_rankings just in case.

This approach should be relatively quick as getting the total number of lists should be relatively trivial on your database and only needs to be done once per request.

Alternatively,

you can recalculate the averages for each team periodically (think minutes or even every few seconds).  You'll probably have an easier time with this approach as it does mean that you don't have to worry about making changes to lists outside of the normal button presses.  Performance wise it is probably a little heavier on your server/database but doesn't necessarily need to be seen by your end users.  There are several different ways you could go about doing this.

The ways I can think of off the top of my head:

DelayedJob(this is a gem for running tasks at a given time) and/or Clockwork(gem which lets you schedule rb tasks) (I find these are both useful gems though you probably don't need both, these gems do require their own process in addition to the rails server so keep that in mind if you're going to use them).

Schedule a procedure on your database(this largely depends on your database and is purely sql).

Keep track on the application of when the last time these values were calculated and update them using the first request after x amount of time (this affects 1 in n requests potentially slowing it down dramatically).

Body:
Ok, so I have around 20 teams and every person ranks Up and Down each Team in his personal ranking list. Like the following format

    -Barcelona "Move up on the list" "Move Down on the list"
    -Arsenal "Move up" "Move Down"
    -Liverpool "Move up" "Move Down"

So in this example, for this particular user, Barcelona has the rank 1, Arsenal rank 2 etc.

Now I want to create a global ranking system, after taking into consideration each individual ranking list.

How do I, logically, go about that?
Smaller rank means higher position, so I can't just take the sum and see which is bigger. Or can I take a sum and see which is smaller?

I thought I could add a "global ranking" integer in each team and see which is smaller, but is this approach right?


问:
Homework: Java BST without nodes (BST of BSTs)
Note: BST - Binary Search Tree (initialism)

As the title says,
this is a homework assignment so I'm not looking for the answer.
Instead, I just need a point in the right direction.

For the assignment,
I am supposed to create a BST class that is directly defined as some data that holds at most 2 BST children
(i.e. does not use a helper node class).

I am given a class that is annotated with JavaDocs and am supposed to fill in the TODOS.

What is tripping me up at least getting started is implementing the insert method about halfway through the class.

```<code>import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;

/**
 * A class to implement the Binary Search Tree data structure.
 * The structure is generic in the type of Objects it contains.
 * @param <T> the type of the contained elements this structure is to hold
 */
public class BinarySearchTree<T> {
private Comparator<T> comparator;
private T data;
private BinarySearchTree<T> left;
private BinarySearchTree<T> right;

/**
 * Constructs an empty BST with a Comparator
 * @param comp the Comparator to use to impose an ordering on instances of T
 */
public BinarySearchTree(Comparator<T> comp) {
    this.comparator = comp;
}

/**
 * Constructs a BST with data and a Comparator
 * @param data the data this BST should hold
 * @param comp the Comparator to use to impose an ordering on instances of T
 */
public BinarySearchTree(T data, Comparator<T> comp) {
    this.data = data;
    this.comparator = comp;
}

/**
 * Inserts an element into this BST
 * @param element the element to insert into this BST
 */
public void insert(T element) {
    //TODO
    if(left == null && right == null){
        left = new BinarySearchTree(element, comparator);
    }else{
        /**
         *Do something with the comparator to figure out if the element goes
         *to left or right?
         */
    }
}

/**
 * Searchs for a given element in this BST
 * @param element the element to search this BST for
 * @return the element in this BST matching the given element, if found,
 *         otherwise null if the given element is not in this BST
 */
public T find(T element) {
    // TODO
}

/**
 * Gathers all the elements of this BST in order
 * @return a List holding the elements in this BST in order
 */
public List<T> getElements() {
    List<T> list = new ArrayList<>();
    // TODO
    return list;
}

/**
 * Pretty prints the contents of this BST in a horizontal tree-like fashion
 */
public void prettyPrint() {
    prettyPrint(0);
}

private void prettyPrint(int indentLevel) {
    // TODO
    // similar to printInOrder from assignment09,
    // but print `indentLevel` amount of spaces before printing data on its own line
    // you may use a for loop to print `indentLevel` amount of spaces
    // each time you recurse, you add to indentLevel
}

/**
 * A main method supplied for any debugging needs
 */
public static void main(String[] args) {
    // Up to you how you use this main method, feel free to change it
    Comparator<Integer> intComp = (i, j) -> i - j; // lambda expression
    BinarySearchTree<Integer> tree = new BinarySearchTree<>(intComp);
    tree.insert(3);
    tree.insert(8);
    tree.insert(1);
    tree.insert(0);
    tree.insert(3);
    tree.insert(9);
    tree.insert(4);
    tree.prettyPrint();
}
</code>```

}

I feel like I understand the concept of how it works, but I have no idea how to implement the code.

I apologize for the formatting if it is unreadable or if this is way too much information to share for the a little assistance.

答:
The BST class is the node.
First, decide if a null element is less than or greater than a non-null element.
To implement the insert you need to do the following:

1) Verify that the element parameter is not null.  If it is null, do nothing.

2) The uncompleted code must decide where to insert the element.

a) If one of the children is null you will end up with neither children being null after the insert.  Compare the new element to the non-null element; the greater of the two is the right child.

b) if neither child is null, determine where to put the new element (less than left, use left.  greater than left, use right) and call the insert for that element.

Note: in case you have not already noticed, this assignment is about recursion.

Body:
Note: BST - Binary Search Tree (initialism)

As the title says,
this is a homework assignment so I'm not looking for the answer.
Instead, I just need a point in the right direction.

For the assignment,
I am supposed to create a BST class that is directly defined as some data that holds at most 2 BST children
(i.e. does not use a helper node class).

I am given a class that is annotated with JavaDocs and am supposed to fill in the TODOS.

What is tripping me up at least getting started is implementing the insert method about halfway through the class.

import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;

/**
 * A class to implement the Binary Search Tree data structure.
 * The structure is generic in the type of Objects it contains.
 * @param <T> the type of the contained elements this structure is to hold
 */
public class BinarySearchTree<T> {
private Comparator<T> comparator;
private T data;
private BinarySearchTree<T> left;
private BinarySearchTree<T> right;

/**
 * Constructs an empty BST with a Comparator
 * @param comp the Comparator to use to impose an ordering on instances of T
 */
public BinarySearchTree(Comparator<T> comp) {
    this.comparator = comp;
}

/**
 * Constructs a BST with data and a Comparator
 * @param data the data this BST should hold
 * @param comp the Comparator to use to impose an ordering on instances of T
 */
public BinarySearchTree(T data, Comparator<T> comp) {
    this.data = data;
    this.comparator = comp;
}

/**
 * Inserts an element into this BST
 * @param element the element to insert into this BST
 */
public void insert(T element) {
    //TODO
    if(left == null && right == null){
        left = new BinarySearchTree(element, comparator);
    }else{
        /**
         *Do something with the comparator to figure out if the element goes
         *to left or right?
         */
    }
}

/**
 * Searchs for a given element in this BST
 * @param element the element to search this BST for
 * @return the element in this BST matching the given element, if found,
 *         otherwise null if the given element is not in this BST
 */
public T find(T element) {
    // TODO
}

/**
 * Gathers all the elements of this BST in order
 * @return a List holding the elements in this BST in order
 */
public List<T> getElements() {
    List<T> list = new ArrayList<>();
    // TODO
    return list;
}

/**
 * Pretty prints the contents of this BST in a horizontal tree-like fashion
 */
public void prettyPrint() {
    prettyPrint(0);
}

private void prettyPrint(int indentLevel) {
    // TODO
    // similar to printInOrder from assignment09,
    // but print `indentLevel` amount of spaces before printing data on its own line
    // you may use a for loop to print `indentLevel` amount of spaces
    // each time you recurse, you add to indentLevel
}

/**
 * A main method supplied for any debugging needs
 */
public static void main(String[] args) {
    // Up to you how you use this main method, feel free to change it
    Comparator<Integer> intComp = (i, j) -> i - j; // lambda expression
    BinarySearchTree<Integer> tree = new BinarySearchTree<>(intComp);
    tree.insert(3);
    tree.insert(8);
    tree.insert(1);
    tree.insert(0);
    tree.insert(3);
    tree.insert(9);
    tree.insert(4);
    tree.prettyPrint();
}

}

I feel like I understand the concept of how it works, but I have no idea how to implement the code.

I apologize for the formatting if it is unreadable or if this is way too much information to share for the a little assistance.


问:
systematic sampling of a raster
I would like to take a systematic sample of cells from a raster layer. The raster that I am using to select the sample has been divided into 15 sections. I would like to sample 2 cells from each section, but I would like the relative position of the sampled cells to be the same in each section.

eg. If the cell at the upper right of the first section is selected, I would like to sample the upper right cell of the other 14 sections. But I would like the 'starting place' to be random.

This is what my raster looks like, where the cell value represents what section it belongs to

```<code>r<-raster(ncol=36, nrow=35)
r[1:7,1:12]<-1
r[1:7,13:24]<-2
r[1:7,25:36]<-3
r[8:14,1:12]<-4
r[8:14,13:24]<-5
r[8:14,25:36]<-6
r[15:21,1:12]<-7
r[15:21,13:24]<-8
r[15:21,25:36]<-9
r[22:28,1:12]<-10
r[22:28,13:24]<-11
r[22:28,25:36]<-12
r[29:35,1:12]<-13
r[29:35,13:24]<-14
r[29:35,25:36]<-15
plot(r)
</code>```

How might I do this?

答:
This is from another very similar question I answered, but there the user wanted a randomly placed sample from a 3x3 grid within the larger raster.

```<code>library(raster)
ras <- raster(nrows = 3, ncols = 3)
v <- c(1,2,NA,4,NA,NA,7,8,9)

ras[] <- v
plot(ras)
res(ras)

ras_fine <- raster(nrows = 9, ncols = 9) #finer resolution raster
ras<-resample(ras,ras_fine,method='ngb')
plot(ras)

samp_strat.rand<- sampleStratified(ras, 1, xy = TRUE, sp=TRUE, na.rm = TRUE)

plot(ras)
points(samp_strat.rand)
</code>```

With a little tweaking:

```<code>library(raster)
r<-raster(ncol=36, nrow=35)
r[1:7,1:12]<-1
r[1:7,13:24]<-2
r[1:7,25:36]<-3
r[8:14,1:12]<-4
r[8:14,13:24]<-5
r[8:14,25:36]<-6
r[15:21,1:12]<-7
r[15:21,13:24]<-8
r[15:21,25:36]<-9
r[22:28,1:12]<-10
r[22:28,13:24]<-11
r[22:28,25:36]<-12
r[29:35,1:12]<-13
r[29:35,13:24]<-14
r[29:35,25:36]<-15
r
plot(r)
res(r)

#ras_fine <- raster(nrows = 9, ncols = 9) #finer resolution raster
#ras<-resample(ras,ras_fine,method='ngb')
#plot(ras)

samp_strat.rand<- sampleStratified(r, 2, xy = TRUE, sp=TRUE, na.rm = TRUE)

plot(r)
points(samp_strat.rand)
</code>```

So we get two random sample points per cell..
and with some minor adjustment...

```<code>samp_strat.reg<- sampleRegular(r, 36, xy = TRUE, sp=TRUE, na.rm = TRUE)

samp_strat.reg.off<-data.frame(samp_strat.reg)

coordinates(samp_strat.reg.off) <- cbind(samp_strat.reg$x+runif(1,min=0,max=res(r)[1]),samp_strat.reg$y+runif(1,min=0,max=res(r)[2]))
samp_strat.off<-samp_strat.reg.data
plot(r)
points(samp_strat.off,col="red")
points(samp_strat.reg,col="blue")
</code>```

Now we have a randomly located point within the confines of a single cell, the same random point each time. I think this was what you were looking for.

Title: systematic sampling of a raster

Body:
I would like to take a systematic sample of cells from a raster layer. The raster that I am using to select the sample has been divided into 15 sections. I would like to sample 2 cells from each section, but I would like the relative position of the sampled cells to be the same in each section.

eg. If the cell at the upper right of the first section is selected, I would like to sample the upper right cell of the other 14 sections. But I would like the 'starting place' to be random.

This is what my raster looks like, where the cell value represents what section it belongs to

r<-raster(ncol=36, nrow=35)
r[1:7,1:12]<-1
r[1:7,13:24]<-2
r[1:7,25:36]<-3
r[8:14,1:12]<-4
r[8:14,13:24]<-5
r[8:14,25:36]<-6
r[15:21,1:12]<-7
r[15:21,13:24]<-8
r[15:21,25:36]<-9
r[22:28,1:12]<-10
r[22:28,13:24]<-11
r[22:28,25:36]<-12
r[29:35,1:12]<-13
r[29:35,13:24]<-14
r[29:35,25:36]<-15
plot(r)

How might I do this?

Body:
This is from another very similar question I answered, but there the user wanted a randomly placed sample from a 3x3 grid within the larger raster.

library(raster)
ras <- raster(nrows = 3, ncols = 3)
v <- c(1,2,NA,4,NA,NA,7,8,9)

ras[] <- v
plot(ras)
res(ras)

ras_fine <- raster(nrows = 9, ncols = 9) #finer resolution raster
ras<-resample(ras,ras_fine,method='ngb')
plot(ras)

samp_strat.rand<- sampleStratified(ras, 1, xy = TRUE, sp=TRUE, na.rm = TRUE)

plot(ras)
points(samp_strat.rand)

With a little tweaking:

library(raster)
r<-raster(ncol=36, nrow=35)
r[1:7,1:12]<-1
r[1:7,13:24]<-2
r[1:7,25:36]<-3
r[8:14,1:12]<-4
r[8:14,13:24]<-5
r[8:14,25:36]<-6
r[15:21,1:12]<-7
r[15:21,13:24]<-8
r[15:21,25:36]<-9
r[22:28,1:12]<-10
r[22:28,13:24]<-11
r[22:28,25:36]<-12
r[29:35,1:12]<-13
r[29:35,13:24]<-14
r[29:35,25:36]<-15
r
plot(r)
res(r)

#ras_fine <- raster(nrows = 9, ncols = 9) #finer resolution raster
#ras<-resample(ras,ras_fine,method='ngb')
#plot(ras)

samp_strat.rand<- sampleStratified(r, 2, xy = TRUE, sp=TRUE, na.rm = TRUE)

plot(r)
points(samp_strat.rand)

So we get two random sample points per cell..
and with some minor adjustment...

samp_strat.reg<- sampleRegular(r, 36, xy = TRUE, sp=TRUE, na.rm = TRUE)

samp_strat.reg.off<-data.frame(samp_strat.reg)

coordinates(samp_strat.reg.off) <- cbind(samp_strat.reg$x+runif(1,min=0,max=res(r)[1]),samp_strat.reg$y+runif(1,min=0,max=res(r)[2]))
samp_strat.off<-samp_strat.reg.data
plot(r)
points(samp_strat.off,col="red")
points(samp_strat.reg,col="blue")

Now we have a randomly located point within the confines of a single cell, the same random point each time. I think this was what you were looking for.


问:
Applying JsonDictionary attribute to dictionary
If I try to add the JsonDictionary attribute to a .net Dictionary(Of Integer, MyClass), the compiler tells me, that the attribute could not be applied. Why is this?

```<code><JsonDictionary()>
Public ReadOnly Property monatswerte As Dictionary(Of Integer, MyClass)
</code>```

I basically couldn't find any examples of how to use the JsonDictionary online.

答:
<JsonDictionary()> can be applied to a type (a class or interface) to force Json.NET's default contract resolver (and its subclasses) to generate a dictionary contract for the type.  It is part of a family of three similar attributes:

<JsonObject()>.  Force a type to be serialized as a JSON object.  Useful to force serialization of collection properties instead of items as shown here.

<JsonArray()>.  Force a type to serialized as a JSON array.  Possibly useful to, e.g., force a dictionary to be serialized as a key/value pair array.

<JsonDictionary()>.  Force a type to be interpreted as a dictionary and serialized as a JSON object.  (It must still implement IDictionary or IDictionary<TKey, TValue> for this to work, of course.)

On the face of it <JsonDictionary()> does not seem that useful because DefaultContractResolver.CreateContract(Type objectType) checks that the incoming type implements IDictionary before checking for any other interface implementations.  However, the attribute has several properties that could be useful in customizing how a dictionary is serialized, including:

NamingStrategyType and NamingStrategyParameters allow control of casing and name-mapping of dictionary keys.

For instance, the following dictionary will always serialize its keys literally, without renaming, even if CamelCasePropertyNamesContractResolver is in use:

```<code><JsonDictionary(NamingStrategyType := GetType(LiteralKeyDictionaryNamingStrategy))> _
Public Class LiteralKeyDictionary(Of TValue)
    Inherits Dictionary(Of String, TValue)
End Class

Public Class LiteralKeyDictionaryNamingStrategy
    Inherits DefaultNamingStrategy

    Public Sub New()
        ProcessDictionaryKeys = False
    End Sub
End Class
</code>```

ItemConverterType, ItemConverterParameters, ItemIsReference, ItemReferenceLoopHandlingand ItemTypeNameHandling allow customization of how dictionary values are serialized.

For instance, in the following dictionary type, the values are always stored with reference preservation enabled:

```<code><JsonDictionary(ItemIsReference := true)> _
Public Class ReferenceObjectDictionary(of TKey, TValue As {Class, New})
    Inherits Dictionary(Of TKey, TValue)
End Class
</code>```

Or, for a dictionary type containing enum values, you might apply StringEnumConverter as an ItemConverterType to force the values to be serialized as strings.

Body:
If I try to add the JsonDictionary attribute to a .net Dictionary(Of Integer, MyClass), the compiler tells me, that the attribute could not be applied. Why is this?

<JsonDictionary()>
Public ReadOnly Property monatswerte As Dictionary(Of Integer, MyClass)

I basically couldn't find any examples of how to use the JsonDictionary online.

Body:
<JsonDictionary()> can be applied to a type (a class or interface) to force Json.NET's default contract resolver (and its subclasses) to generate a dictionary contract for the type.  It is part of a family of three similar attributes:

<JsonObject()>.  Force a type to be serialized as a JSON object.  Useful to force serialization of collection properties instead of items as shown here.

<JsonArray()>.  Force a type to serialized as a JSON array.  Possibly useful to, e.g., force a dictionary to be serialized as a key/value pair array.

<JsonDictionary()>.  Force a type to be interpreted as a dictionary and serialized as a JSON object.  (It must still implement IDictionary or IDictionary<TKey, TValue> for this to work, of course.)

On the face of it <JsonDictionary()> does not seem that useful because DefaultContractResolver.CreateContract(Type objectType) checks that the incoming type implements IDictionary before checking for any other interface implementations.  However, the attribute has several properties that could be useful in customizing how a dictionary is serialized, including:

NamingStrategyType and NamingStrategyParameters allow control of casing and name-mapping of dictionary keys.

For instance, the following dictionary will always serialize its keys literally, without renaming, even if CamelCasePropertyNamesContractResolver is in use:

<JsonDictionary(NamingStrategyType := GetType(LiteralKeyDictionaryNamingStrategy))> _
Public Class LiteralKeyDictionary(Of TValue)
    Inherits Dictionary(Of String, TValue)
End Class

Public Class LiteralKeyDictionaryNamingStrategy
    Inherits DefaultNamingStrategy

    Public Sub New()
        ProcessDictionaryKeys = False
    End Sub
End Class

ItemConverterType, ItemConverterParameters, ItemIsReference, ItemReferenceLoopHandlingand ItemTypeNameHandling allow customization of how dictionary values are serialized.

For instance, in the following dictionary type, the values are always stored with reference preservation enabled:

<JsonDictionary(ItemIsReference := true)> _
Public Class ReferenceObjectDictionary(of TKey, TValue As {Class, New})
    Inherits Dictionary(Of TKey, TValue)
End Class

Or, for a dictionary type containing enum values, you might apply StringEnumConverter as an ItemConverterType to force the values to be serialized as strings.


问:
Accessing Property Bag for List Item using SharePoint Client Object Model or Web Services
Just to ask if it is possible to access and update properties in the list item's property bag via the SharePoint 2010 client object model?  I can see that it possible to get the web's property bag (but not to set), but can't see any support for the property bag on either the list or list item.

Alternatively, if it is possible to access the propertioes via the SharePoint web services, that would also be useful.

Thanks, MagicAndi.

答: I don't think the thing which you are looking for would be possible Property Bag</p>


问:
Self sign certificate with different server
I have generated a self sign ssl certificate for my server, can I use the same certificate with different server?</p>

答:
You can use the same certificate for as many servers as your want, until your domain name matches the common name in the certificate.
Note that it will still be untrusted for every client as it is not signed by a CA.</p>


问:
Minizinc modelling: Vars as coordinate sets
I am modelling a constraint satisfaction program in minizinc where the solution is an assignment of points on a 3D grid. One of the constraints is that only one point can occupy any given position, so the points must be pairwise different in at least one of their coordinates.

My point variables are modelled as an N X 3 array of coordinates:

```<code>array[1..N,1..3] of var -N..N: X;
</code>```

And the difference constraint is

```<code>constraint forall(i in 1..N-1)(forall(j in i+1..N)(not X_eq(i,j))); %extremely slow
predicate X_eq(int: a, int: b)=
 (X[a,1]=X[b,1]/\X[a,2]=X[b,2]/\X[a,3]=X[b,3]);
</code>```

But the solution time for the problem skyrockets when I formulate the constraint like this. I have many other constraints to be added and its already way to slow to just find points that are different.

I tried to instead model the points as

```<code>array[1..N] var set of -N..N
</code>```

So that I could use the built-in function

all_different

But then I see how to enforce sets to have cardinality 3, and also it seems less natural to use the generic sized sets to model a triplet of ints.

My question is: What is a tractable and 'correct' way to model a coordinate set and the all-different constraint?

I am using the gecode solver that comes in the minizinc IDE bundle. The model is shown below. Solution time is 24 minutes.

```<code>array[1..N] of 0..1:  seq=[1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0];
int: N=18;
int: H=6;

array[1..N,1..3] of var -N..N: X;

array [1..H,1..3] of 0..N:c;

%H are in core
constraint forall(i in 1..N)(  if (seq[i]=1) then exists(j in 1..H)([i,1]=c[j,1] /\ X[i,2]=c[j,2] /\ X[i,3]=c[j,3]   ) else true endif);
%All points different
constraint forall(i in 1..N-1)(forall(j in i+1..N)(not X_eq(i,j))); %extremely slow
predicate X_eq(int: a, int: b)=
 (X[a,1]=X[b,1]/\X[a,2]=X[b,2]/\X[a,3]=X[b,3]);

solve satisfy;
output[show(X[i,j]) ++ " "|i in 1..N,j in 1..3]++["\n"];

c=[|0,0,0|
0,0,1|
0,0,2|
0,1,0|
0,1,1|
0,1,2|];
</code>```

答:
Note: I ran your model as got the first solution in 60ms (not 24 minutes), using Gecode and the latest MiniZinc version from Git. So the stuff below might not help you...

Also, I answer your original problem, i.e. how to use all_different with the 3D array X (array[1..N, 1..3]). I might have missed something in your model, but here is a model that solves the satisfiability problem in 9ms.

The idea to create an array that converts a point to an integer: (X[I,1]-1)*N*N + (X[I,2]-1)*N + X[I,3] (cf the decimal number 523 is 5*10*10 + 2*10 + 3). Perhaps this must be adjusted, but you get the general idea. Also, I added - in a comment - another approach that compares each pairs of points that should be faster than your X_eq predicate.

Note that this all_different approach might be bad if the generated integers  will be very large (e.g. for large N).

```<code>include "globals.mzn";

array[1..N] of 0..1:  seq=[1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0];
int: N=18;
int: H=6;
array [1..H,1..3] of 0..N:c;
array[1..N,1..3] of var -N..N: X;

solve satisfy;

% hakank: here's my approach of all_different
constraint
   all_different([(X[i,1]-1)*N*N + (X[i,2]-1)*N + X[i,3] | i in 1..N])

   %% another approach (slower than all_different)
   %% for each pair: ensure that there is at least one coordinate differ
   % forall(I in 1..N, J in 1..N where I < J) (
   %   sum([X[I,K] != X[J,K] | K in 1..3]) > 0
   % )

  ;

  % from original model
  constraint
     %H are in core
     forall(i in 1..N)(
        if (seq[i]=1) then exists(j in 1..H) (
              X[i,1]=c[j,1] /\ X[i,2]=c[j,2] /\ X[i,3]=c[j,3]
        )
        else true endif
    )
  ;

  output
  [
     show([X[I,J]  | J in 1..3]) ++ "\n"
     | I in 1..N
  ]
  ;

  c=[|0,0,0|
      0,0,1|
      0,0,2|
      0,1,0|
      0,1,1|
      0,1,2|];
</code>```

Body:
I am modelling a constraint satisfaction program in minizinc where the solution is an assignment of points on a 3D grid. One of the constraints is that only one point can occupy any given position, so the points must be pairwise different in at least one of their coordinates.

My point variables are modelled as an N X 3 array of coordinates:

array[1..N,1..3] of var -N..N: X;

And the difference constraint is

constraint forall(i in 1..N-1)(forall(j in i+1..N)(not X_eq(i,j))); %extremely slow
predicate X_eq(int: a, int: b)=
 (X[a,1]=X[b,1]/\X[a,2]=X[b,2]/\X[a,3]=X[b,3]);

But the solution time for the problem skyrockets when I formulate the constraint like this. I have many other constraints to be added and its already way to slow to just find points that are different.

I tried to instead model the points as

array[1..N] var set of -N..N

So that I could use the built-in function

all_different

But then I see how to enforce sets to have cardinality 3, and also it seems less natural to use the generic sized sets to model a triplet of ints.

My question is: What is a tractable and 'correct' way to model a coordinate set and the all-different constraint?

I am using the gecode solver that comes in the minizinc IDE bundle. The model is shown below. Solution time is 24 minutes.

array[1..N] of 0..1:  seq=[1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0];
int: N=18;
int: H=6;

array[1..N,1..3] of var -N..N: X;

array [1..H,1..3] of 0..N:c;

%H are in core
constraint forall(i in 1..N)(  if (seq[i]=1) then exists(j in 1..H)([i,1]=c[j,1] /\ X[i,2]=c[j,2] /\ X[i,3]=c[j,3]   ) else true endif);
%All points different
constraint forall(i in 1..N-1)(forall(j in i+1..N)(not X_eq(i,j))); %extremely slow
predicate X_eq(int: a, int: b)=
 (X[a,1]=X[b,1]/\X[a,2]=X[b,2]/\X[a,3]=X[b,3]);

solve satisfy;
output[show(X[i,j]) ++ " "|i in 1..N,j in 1..3]++["\n"];

c=[|0,0,0|
0,0,1|
0,0,2|
0,1,0|
0,1,1|
0,1,2|];

Body:
Note: I ran your model as got the first solution in 60ms (not 24 minutes), using Gecode and the latest MiniZinc version from Git. So the stuff below might not help you...

Also, I answer your original problem, i.e. how to use all_different with the 3D array X (array[1..N, 1..3]). I might have missed something in your model, but here is a model that solves the satisfiability problem in 9ms.

The idea to create an array that converts a point to an integer: (X[I,1]-1)*N*N + (X[I,2]-1)*N + X[I,3] (cf the decimal number 523 is 5*10*10 + 2*10 + 3). Perhaps this must be adjusted, but you get the general idea. Also, I added - in a comment - another approach that compares each pairs of points that should be faster than your X_eq predicate.

Note that this all_different approach might be bad if the generated integers  will be very large (e.g. for large N).

include "globals.mzn";

array[1..N] of 0..1:  seq=[1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0];
int: N=18;
int: H=6;
array [1..H,1..3] of 0..N:c;
array[1..N,1..3] of var -N..N: X;

solve satisfy;

% hakank: here's my approach of all_different
constraint
   all_different([(X[i,1]-1)*N*N + (X[i,2]-1)*N + X[i,3] | i in 1..N])

   %% another approach (slower than all_different)
   %% for each pair: ensure that there is at least one coordinate differ
   % forall(I in 1..N, J in 1..N where I < J) (
   %   sum([X[I,K] != X[J,K] | K in 1..3]) > 0
   % )

  ;

  % from original model
  constraint
     %H are in core
     forall(i in 1..N)(
        if (seq[i]=1) then exists(j in 1..H) (
              X[i,1]=c[j,1] /\ X[i,2]=c[j,2] /\ X[i,3]=c[j,3]
        )
        else true endif
    )
  ;

  output
  [
     show([X[I,J]  | J in 1..3]) ++ "\n"
     | I in 1..N
  ]
  ;

  c=[|0,0,0|
      0,0,1|
      0,0,2|
      0,1,0|
      0,1,1|
      0,1,2|];