问:
JS code guessing game color NOT WORKING
I am a neophyte JS, I'm making a game where the user has to guess a randomly generated color.

I noticed that the code I tried to write results in errors, that is, when I go to enter a color in the prompt, even if it is wrong always says the right thing. I have something wrong in check_guess function where I wrote the conditions.

Another mistake I detected when the game ends, should be out in the background the color that guessed it, nor should you.

Can you help me figure out where I'm wrong?

while (!finished) {
            guess_input_text = prompt("I am thinking of one of these colors:\n\n" +
              colors_message + "\n\n What is the color am I thinking of?");
            guess_input = guess_input_text.toLowerCase();
            guesses += 1;
            finished = check_guess();
          }
        }

        function check_guess() {
          if (guess_input == -1) {
            alert("Sorry, I don't recognize your color. \n\n Please try again.");
            return false;
          } else if (guess_input > target) {
            alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
            return false;
          } else if (guess_input < target) {
            alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
            return false;
          } else {
            alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
            var myBody = document.getElementsByTagName("body")[0];
            myBody.style.background = target;

            return true;
          }
        }
      </script>```

答:
Referring to your code revisions I got the required data. There were few glitches that were found like:

You were checking guess_input with target, where guess_input holds a string value of the user input and target holds an integer value of the correct answer. None of the conditions will ever be satisfied in this case, and thus the last else part will be executed always. That is, alert("Congratulations! You ha..);

myBody.style.background = target; will set the background
property to an integer (index of answer in colors array). You need
to set it like myBody.style.background = colors[target];

Below is the working code:

var colors = ["antiquewhite", "blueviolet", "crimson", "deepskyblue", "forestgreen", "gold", "lawngreen", "magenta", "palegreen", "skyblue"];
var colors_message = colors.join(", ");
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var ask_again = false;

function do_game() {
 var target_index = Math.random() * colors.length;
 var target_index_integer = Math.floor(target_index);
 target = target_index_integer;

 var answer = String(colors[target]).toLowerCase();
 //Alert correct answer for testing purposes
 alert("The correct answer is: " + answer);

    guess_input_text = prompt("I am thinking of one of these colors:\n\n" + colors_message + "\n\n What is the color am I thinking of?");
    while (!finished) {
        if(ask_again){
           guess_input_text = prompt("What is the color I was thinking of?");
           }
            guess_input = guess_input_text.toLowerCase();
            guesses += 1;
            finished = check_guess(colors.indexOf(guess_input));
        }
    }

    function check_guess(guess_index) {
        ask_again = true;
        if (guess_index == -1) {
            alert("Sorry, I don't recognize your color. \n\n Please try again.");
            return false;
        } else if (guess_index > target) {
            alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
            return false;
        } else if (guess_index < target) {
            alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
            return false;
        } else {
           ask_again = true;
            alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
            var myBody = document.getElementsByTagName("body")[0];
            myBody.style.background = colors[target];
            return true;
        }
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="do_game()"></body></code>```

Title: JS code guessing game color NOT WORKING

Body:
Referring to your code revisions I got the required data. There were few glitches that were found like:

You were checking guess_input with target, where guess_input holds a string value of the user input and target holds an integer value of the correct answer. None of the conditions will ever be satisfied in this case, and thus the last else part will be executed always. That is, alert("Congratulations! You ha..);

myBody.style.background = target; will set the background
property to an integer (index of answer in colors array). You need
to set it like myBody.style.background = colors[target];

Below is the working code:

var colors = ["antiquewhite", "blueviolet", "crimson", "deepskyblue", "forestgreen", "gold", "lawngreen", "magenta", "palegreen", "skyblue"];
var colors_message = colors.join(", ");
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var ask_again = false;

function do_game() {
 var target_index = Math.random() * colors.length;
 var target_index_integer = Math.floor(target_index);
 target = target_index_integer;

 var answer = String(colors[target]).toLowerCase();
 //Alert correct answer for testing purposes
 alert("The correct answer is: " + answer);

    guess_input_text = prompt("I am thinking of one of these colors:\n\n" + colors_message + "\n\n What is the color am I thinking of?");
    while (!finished) {
        if(ask_again){
           guess_input_text = prompt("What is the color I was thinking of?");
           }
            guess_input = guess_input_text.toLowerCase();
            guesses += 1;
            finished = check_guess(colors.indexOf(guess_input));
        }
    }

    function check_guess(guess_index) {
        ask_again = true;
        if (guess_index == -1) {
            alert("Sorry, I don't recognize your color. \n\n Please try again.");
            return false;
        } else if (guess_index > target) {
            alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
            return false;
        } else if (guess_index < target) {
            alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
            return false;
        } else {
           ask_again = true;
            alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
            var myBody = document.getElementsByTagName("body")[0];
            myBody.style.background = colors[target];
            return true;
        }
     }

<body onload="do_game()"></body>


来源: stackexchange

问:
Virtualbox OSX Host access to Ubuntu Samba share
I am attempting setup of a dev environment using Virtualbox on OSX host running Ubuntu Server 16.10 on guest.
I am stuck on getting Samba to share the dev directory on the guest so that ultimately Netbeans can be used to edit the server files on OSX via the share directory.
This works fine on OSX to seperate physical Ubuntu machine.
From standard Samba config, at the end is

```<code>[testsharename]
path=/home/myusername/shared#note trailing slash required
#hosts deny=*
#hosts allow=192.168.0.210#ip of an allowed lan address
guest ok=yes
writeable=yes
</code>```

The actual share is identified using Finder on OSX however on clicking on it there is an error that it cannot be found. Changing the share name reflects on Finder. The commented out lines are because I only really want a single Lan IP to access.

Finder error is that the operation can't be completed because the original item for "testshare" can't be found

答:
Logs showed Can't mount Samba share (canonicalize_connect_path failed) therefore some research narrowed this down to a permissions issue hinted at by https://ubuntuforums.org/showthread.php?t=1439582

Moving the share out of the home directory into /var/www/ as I originally required (the home directory part was simply testing things) this, with 777 permissions on the share dir only showed it to work perfectly.
I certainly don't agree from the forum post that all path nodes leading to the share require permission changes however.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting setup of a dev environment using Virtualbox on OSX host running Ubuntu Server 16.10 on guest.
I am stuck on getting Samba to share the dev directory on the guest so that ultimately Netbeans can be used to edit the server files on OSX via the share directory.
This works fine on OSX to seperate physical Ubuntu machine.
From standard Samba config, at the end is

[testsharename]
path=/home/myusername/shared#note trailing slash required
#hosts deny=*
#hosts allow=192.168.0.210#ip of an allowed lan address
guest ok=yes
writeable=yes

The actual share is identified using Finder on OSX however on clicking on it there is an error that it cannot be found. Changing the share name reflects on Finder. The commented out lines are because I only really want a single Lan IP to access.

Finder error is that the operation can't be completed because the original item for "testshare" can't be found


问:
change value of dynamically created buttons
i want to assign value to 0 if its 1 and vice versa on clicking the button then save it to an array there may be 20-25 buttons based on the query</p>

```<code><?php while($row = mysqli_fetch_array($result)) { ?>

    <button  class="btn-success btn-sq btn-lg " value="0" id="<?php echo $row[0]; ?>" onclick="toggle(this) ">
        <?php echo $row[0]; ?> <br>
    </button>

<?php } ?>
</code>```

答:
If you're simply looking to toggle the value, here's a simple jsfiddle which can do just that: https://jsfiddle.net/fz1o0dsr/</p>

```<code>$(document).ready(function(){
    $("button").click(function(){
    var $this = $(this);
    $this.attr('value', $this.attr('value') === "0" ? "1" : "0");
    alert("The button val is now " + $this.attr('value'));
  });
});
</code>```

Body:
i want to assign value to 0 if its 1 and vice versa on clicking the button then save it to an array there may be 20-25 buttons based on the query

<?php while($row = mysqli_fetch_array($result)) { ?>

    <button  class="btn-success btn-sq btn-lg " value="0" id="<?php echo $row[0]; ?>" onclick="toggle(this) ">
        <?php echo $row[0]; ?>

    </button>

<?php } ?>

Body:
If you're simply looking to toggle the value, here's a simple jsfiddle which can do just that: https://jsfiddle.net/fz1o0dsr/

$(document).ready(function(){
    $("button").click(function(){
    var $this = $(this);
    $this.attr('value', $this.attr('value') === "0" ? "1" : "0");
    alert("The button val is now " + $this.attr('value'));
  });
});


问:
JavaScript loop through to check duplicate value
I am having troubles trying to check if the date exists in the array.

```<code> for(var i = 0; i< crisislist.length; i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }
</code>```

The sample data for the date is:

```<code>["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]
</code>```

And the expected output for hazelabel, hazedata should be:

hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
   hazedata: [1,2,1]

With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:

```<code>Uncaught TypeError: Cannot read property 'date' of undefined
</code>```

I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.

Any idea how to fix this? Thanks in advance!

答:
Check that code. If you have any questions, add a comment :)  In my solution dates dont have to be sorted.

```<code>  </head>

<BODY>
<script>

function Something(date)
{
    this.date = date;
    this.category = 1;
}

var crisislist = [];
var hazelabel = [];
var hazedata = [];
crisislist[0] = new Something("01-02-2017");
crisislist[1] = new Something("22-03-2017");
crisislist[2] = new Something("22-03-2017");
crisislist[3] = new Something("07-08-2017");

 for(var i = 0; i< crisislist.length; i++){
    if(crisislist[i].category == 1)
    {
     if(!hazelabel[crisislist[i].date])
     {
         hazelabel[crisislist[i].date] = crisislist[i].date;
         hazedata[crisislist[i].date] = 1;
     }
     else
     {
         hazedata[crisislist[i].date]++;
     }
    }
 }

for(var key  in hazelabel)
{
console.log(hazelabel[key]);
console.log(hazedata[key]);
}

</script>
</BODY>
</HTML>
</code>```

Body:
I am having troubles trying to check if the date exists in the array.

 for(var i = 0; i< crisislist.length; i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }

The sample data for the date is:

["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]

And the expected output for hazelabel, hazedata should be:

hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
   hazedata: [1,2,1]

With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:

Uncaught TypeError: Cannot read property 'date' of undefined

I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.

Any idea how to fix this? Thanks in advance!

Body:
Check that code. If you have any questions, add a comment :)  In my solution dates dont have to be sorted.

  </head>

<BODY>
<script>

function Something(date)
{
    this.date = date;
    this.category = 1;
}

var crisislist = [];
var hazelabel = [];
var hazedata = [];
crisislist[0] = new Something("01-02-2017");
crisislist[1] = new Something("22-03-2017");
crisislist[2] = new Something("22-03-2017");
crisislist[3] = new Something("07-08-2017");

 for(var i = 0; i< crisislist.length; i++){
    if(crisislist[i].category == 1)
    {
     if(!hazelabel[crisislist[i].date])
     {
         hazelabel[crisislist[i].date] = crisislist[i].date;
         hazedata[crisislist[i].date] = 1;
     }
     else
     {
         hazedata[crisislist[i].date]++;
     }
    }
 }

for(var key  in hazelabel)
{
console.log(hazelabel[key]);
console.log(hazedata[key]);
}

</script>
</BODY>
</HTML>


问:
UIButton inside a UIView not responding to gesture
I have a UIView with a UIButton inside it but the button does not recognise gestures

Any ideas why? I have tried using the solutions in the questions related to this but have not succeeded.

The whole class code:

```<code>import UIKit
import Foundation

public class HUDView: UIView , UIGestureRecognizerDelegate {
    var stopwatch: StopwatchView
    var gamePoints: CounterLabelView

     var hintButton: UIButton!

    required public init(coder aDecoder: NSCoder) {
        fatalError("Never call this... Use init(frame:)")
    }

    override init(frame: CGRect) {
        self.stopwatch = StopwatchView(frame: CGRect(x: ScreenWidth/2 - 150, y: 0, width: 300, height: 100))
        self.stopwatch.setSecondsRemaining(0)

        self.gamePoints = CounterLabelView(font: FontHUD!, frame: CGRect(x: ScreenWidth - 200, y: 30, width: 320, height: 70))
        gamePoints.textColor = UIColor.black
        gamePoints.value = 0

        super.init(frame: frame)

        self.addSubview(gamePoints)
        let pointsLabel = UILabel(frame: CGRect(x: ScreenWidth - 340, y: 30, width: 140, height: 70))
        pointsLabel.backgroundColor = UIColor.clear
        pointsLabel.font = FontHUD
        pointsLabel.text = " Points:"
        self.addSubview(pointsLabel)

        self.isUserInteractionEnabled = false
        self.addSubview(self.stopwatch)

        //load the button image
        let hintButtonImage = UIImage(named: "btn")!

        //the help button
        self.hintButton = UIButton()
      //  hintButton.perform(#selector(HUDView.s))
        hintButton.setTitle("Hint!", for:.normal)
        hintButton.titleLabel?.font = lHud
        hintButton.setBackgroundImage(hintButtonImage, for: .normal)
        hintButton.frame = CGRect(x: 50, y: 30, width: hintButtonImage.size.width, height: hintButtonImage.size.height)

       // hintButton.center = self.center
        //50, 30, hintButtonImage.size.width, hintButtonImage.size.height
        hintButton.alpha = 1.0
        hintButton.isUserInteractionEnabled = true
        self.addSubview(hintButton)

    //    hintButton.addTarget(self, action: #selector(self.tapButton(_:)), for: .touchUpInside)

        let g = UITapGestureRecognizer(target: self, action: #selector(self.h(_:)))
        g.delegate = self
        hintButton.addGestureRecognizer(g)
    }

    func h(_ sender: UITapGestureRecognizer) {
        print("hey!")
        fatalError()
    }

}
</code>```

答:
The problem is in line self.isUserInteractionEnabled = false

You are adding button as a subview to HUDView. The button tap will not work because the parent view ie:HUDView has user interaction disabled and so the user interaction of all the subViews will be disabled.
Make  the changes as self.isUserInteractionEnabled = true it will work.

Body:
I have a UIView with a UIButton inside it but the button does not recognise gestures

Any ideas why? I have tried using the solutions in the questions related to this but have not succeeded.

The whole class code:

import UIKit
import Foundation

public class HUDView: UIView , UIGestureRecognizerDelegate {
    var stopwatch: StopwatchView
    var gamePoints: CounterLabelView

     var hintButton: UIButton!

    required public init(coder aDecoder: NSCoder) {
        fatalError("Never call this... Use init(frame:)")
    }

    override init(frame: CGRect) {
        self.stopwatch = StopwatchView(frame: CGRect(x: ScreenWidth/2 - 150, y: 0, width: 300, height: 100))
        self.stopwatch.setSecondsRemaining(0)

        self.gamePoints = CounterLabelView(font: FontHUD!, frame: CGRect(x: ScreenWidth - 200, y: 30, width: 320, height: 70))
        gamePoints.textColor = UIColor.black
        gamePoints.value = 0

        super.init(frame: frame)

        self.addSubview(gamePoints)
        let pointsLabel = UILabel(frame: CGRect(x: ScreenWidth - 340, y: 30, width: 140, height: 70))
        pointsLabel.backgroundColor = UIColor.clear
        pointsLabel.font = FontHUD
        pointsLabel.text = " Points:"
        self.addSubview(pointsLabel)

        self.isUserInteractionEnabled = false
        self.addSubview(self.stopwatch)

        //load the button image
        let hintButtonImage = UIImage(named: "btn")!

        //the help button
        self.hintButton = UIButton()
      //  hintButton.perform(#selector(HUDView.s))
        hintButton.setTitle("Hint!", for:.normal)
        hintButton.titleLabel?.font = lHud
        hintButton.setBackgroundImage(hintButtonImage, for: .normal)
        hintButton.frame = CGRect(x: 50, y: 30, width: hintButtonImage.size.width, height: hintButtonImage.size.height)

       // hintButton.center = self.center
        //50, 30, hintButtonImage.size.width, hintButtonImage.size.height
        hintButton.alpha = 1.0
        hintButton.isUserInteractionEnabled = true
        self.addSubview(hintButton)

    //    hintButton.addTarget(self, action: #selector(self.tapButton(_:)), for: .touchUpInside)

        let g = UITapGestureRecognizer(target: self, action: #selector(self.h(_:)))
        g.delegate = self
        hintButton.addGestureRecognizer(g)
    }

    func h(_ sender: UITapGestureRecognizer) {
        print("hey!")
        fatalError()
    }

}


问:
Segmentation Fault with string array
I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:

```<code>int main (  ){

 int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
 char string[100][100];
 char line [17];
 char str[4];
 char str1[5];
 char str2[4];
 char str3[4];

 FILE *p;
 p = fopen("text.txt", "r");
 while(fgets(line, sizeof line, p)!=NULL){
  printf("%s", line);
  strncpy(string[i], line, 17);
  i++;
  numLinhas++;
  }
  fclose(p);
  char *temp[numLinhas];
</code>```

After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:

```<code>    for (i = 0; i<numLinhas; i++){
    sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
    if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
    temp[i] = "NOP";
    count++;
    }
    if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

    if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
    temp[i] = "RLC";
    count++;
    }
</code>```

The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf.
Ah yes! And below is the txt file I'm loading as an example:

```<code>0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d
</code>```

Just saw something new. here's the compile window i'm getting:

```<code>marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16

Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16

Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16

Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:

string:0003 7Ea

string:0004 21a 12r 00r
string:

string:0007 46a

string:0008 80a

string:0009 21a 13r 00r
string:

string:000C 77a

string:000D 3Ea 01a

string:000F 3Da

string:0010 76a

string:0011 0Ad

string:0012 03d

string:0013 01d

Segmentation fault
</code>```

The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?

答:
Are you allocating memory for each temp[i] before calling sprintf?  If not, there's your problem.

```<code>if (!strncmp(str, "06", 2) && str[2] != 'd')
{
  temp[i] = malloc(5 + strlen(str2) + 2);  // Thanks, philippe
  if (temp[i])
    sprintf(temp[i], "%s,%s", "MVI B", str2);
}
</code>```

Although now you'll have to keep track of which elements of temp were allocated with malloc so you can free them later.

Edit

At the end of your program, you can loop through the temp array and check the contents of each element against the leading part of your string above, and if they match, deallocate that element using free:

```<code>for (i = 0; i < numLinhas; i++)
{
  if (strcnmp(temp[i], "MVI B", strlen("MVI B")) == 0)
    free(temp[i]);
}
</code>```

You do not need to do this for the array elements that were assigned "NOP" or "RLC"; in those cases, you simply copied the address of the string literal to the array element.  No new memory was allocated for those elements, so you don't have to worry about deallocating them.

Title: Segmentation Fault with string array

Body:
I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:

int main (  ){

 int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
 char string[100][100];
 char line [17];
 char str[4];
 char str1[5];
 char str2[4];
 char str3[4];

 FILE *p;
 p = fopen("text.txt", "r");
 while(fgets(line, sizeof line, p)!=NULL){
  printf("%s", line);
  strncpy(string[i], line, 17);
  i++;
  numLinhas++;
  }
  fclose(p);
  char *temp[numLinhas];

After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:

    for (i = 0; i<numLinhas; i++){
    sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
    if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
    temp[i] = "NOP";
    count++;
    }
    if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

    if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
    temp[i] = "RLC";
    count++;
    }

The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf.
Ah yes! And below is the txt file I'm loading as an example:

0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d

Just saw something new. here's the compile window i'm getting:

marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16

Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16

Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16

Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:

string:0003 7Ea

string:0004 21a 12r 00r
string:

string:0007 46a

string:0008 80a

string:0009 21a 13r 00r
string:

string:000C 77a

string:000D 3Ea 01a

string:000F 3Da

string:0010 76a

string:0011 0Ad

string:0012 03d

string:0013 01d

Segmentation fault

The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?

Body:
Are you allocating memory for each temp[i] before calling sprintf?  If not, there's your problem.

if (!strncmp(str, "06", 2) && str[2] != 'd')
{
  temp[i] = malloc(5 + strlen(str2) + 2);  // Thanks, philippe
  if (temp[i])
    sprintf(temp[i], "%s,%s", "MVI B", str2);
}

Although now you'll have to keep track of which elements of temp were allocated with malloc so you can free them later.

Edit

At the end of your program, you can loop through the temp array and check the contents of each element against the leading part of your string above, and if they match, deallocate that element using free:

for (i = 0; i < numLinhas; i++)
{
  if (strcnmp(temp[i], "MVI B", strlen("MVI B")) == 0)
    free(temp[i]);
}

You do not need to do this for the array elements that were assigned "NOP" or "RLC"; in those cases, you simply copied the address of the string literal to the array element.  No new memory was allocated for those elements, so you don't have to worry about deallocating them.

ContentLicense: CC BY-SA 2.5


问:
Upload image to GraphQL server
I'm using react-dropzone and graphql-server-express-upload to upload an image all in GraphQL Apollo. In my client the file looks like this:

But in the server, when I log it, it looks like this:

```<code>{ preview: 'blob:http://localhost:3000/c622b0bd-3f0d-4f52-91f4-7676c8534c59' }
</code>```

I'm following the instructions in the readme in graphql-server-express-upload, but no luck so far. How do I get the full image?

答: I ended up using apollo-upload-client, works great!</p>

Title: Upload image to GraphQL server

Body:
I'm using react-dropzone and graphql-server-express-upload to upload an image all in GraphQL Apollo. In my client the file looks like this:

But in the server, when I log it, it looks like this:

{ preview: 'blob:http://localhost:3000/c622b0bd-3f0d-4f52-91f4-7676c8534c59' }

I'm following the instructions in the readme in graphql-server-express-upload, but no luck so far. How do I get the full image?


问:
Creating self-executable node.js server
I would like to create an executable bash file that will execute the command
node app.js - the goal is to have an executable file that can be opened on a local machine on which node is already installed and the executable is inside the project directory (It's an express.js app).

I'm trying to do it on a mac, I've written a .command file, made it executable and added the command.
Problem is, the process immediately closes, as the terminal seems to automatically add exit; after the last command.
I would like to do it on Windows machines also.

I don't need the entire app in an executable file, only the option to double click a file instead of opening the terminal and manually writing that simple command.

Any idea how to achieve this?

答:
hotel might be a good general solution for your use case.

Once registered with the command hotel add, you can start and stop your server from a simple web interface.

Its a better cross-platform solution too, since otherwise using executables means you'd need:

.bat for Windows

.sh for Linux

.command for Mac

My favorite feature though is the proxy support.  For example, once I registered my node project my-express-app as such:

```<code>$ cd my-express-app
$ hotel add "node app.js"
</code>```

I can simply open up my browser and nagivate to http://my-express-app.dev to start the server.

Title: Creating self-executable node.js server

Body:
hotel might be a good general solution for your use case.

Once registered with the command hotel add, you can start and stop your server from a simple web interface.

Its a better cross-platform solution too, since otherwise using executables means you'd need:

.bat for Windows

.sh for Linux

.command for Mac

My favorite feature though is the proxy support.  For example, once I registered my node project my-express-app as such:

$ cd my-express-app
$ hotel add "node app.js"

I can simply open up my browser and nagivate to http://my-express-app.dev to start the server.


问:
Is there a maximum size to char[]?
IN JAVA

Is there a maximum size of char[]? Can I have a char[5,000,000]?

Is array in java composed of contiguous memory blocks?

答:
Since the index is int based the maximum size of an array should be Integer.MAX_VALUE

Obviously the other limit is the amount of memory available to your application :)

Title: Is there a maximum size to char[]?


问:
How to setup IMAP in CodeIgniter
How can I setup IMAP in CodeIgniter. For now, I'm using just pure php. But I need to change as CodeIgniter Standard. Please help me. Here is my IMAP Setup with Pure php</p>

```<code>// Connect to gmail
                    $hostname = '{imap.gmail.com:993/ssl/novalidate-cert}[Gmail]/All Mail';
                    $username = 'my email';
                    $password = 'my password';
</code>```

答:
You can use something like this, make some changles as per your needs and add this as a function in your controller.
If you need more help give us a sample od your code from controller and view.</p>

```<code><?php
    $mbox = imap_open("{imap.gmail.com:993/imap/ssl}", "me mail", "my password");

    echo "<h1>Mailboxes</h1>\n";
    $folders = imap_listmailbox($mbox, "{imap.gmail.com:993/imap/ssl}", "*");

    if ($folders == false) {
        echo "Call failed<br />\n";
    } else {
        foreach ($folders as $val) {
            echo $val . "<br />\n";
        }
    }

    echo "<h1>Headers in INBOX</h1>\n";
    $headers = imap_headers($mbox);
    arsort($headers);

    if ($headers == false) {
        echo "Call failed<br />\n";
    } else {
        foreach ($headers as $val) {
            echo $val . "<br />\n";
        }
    }

    imap_close($mbox);
    ?>
</code>```

Title: How to setup IMAP in CodeIgniter

Body:
How can I setup IMAP in CodeIgniter. For now, I'm using just pure php. But I need to change as CodeIgniter Standard. Please help me. Here is my IMAP Setup with Pure php

// Connect to gmail
                    $hostname = '{imap.gmail.com:993/ssl/novalidate-cert}[Gmail]/All Mail';
                    $username = 'my email';
                    $password = 'my password';

Body:
You can use something like this, make some changles as per your needs and add this as a function in your controller.
If you need more help give us a sample od your code from controller and view.

<?php
    $mbox = imap_open("{imap.gmail.com:993/imap/ssl}", "me mail", "my password");

    echo "<h1>Mailboxes</h1>\n";
    $folders = imap_listmailbox($mbox, "{imap.gmail.com:993/imap/ssl}", "*");

    if ($folders == false) {
        echo "Call failed<br />\n";
    } else {
        foreach ($folders as $val) {
            echo $val . "<br />\n";
        }
    }

    echo "<h1>Headers in INBOX</h1>\n";
    $headers = imap_headers($mbox);
    arsort($headers);

    if ($headers == false) {
        echo "Call failed<br />\n";
    } else {
        foreach ($headers as $val) {
            echo $val . "<br />\n";
        }
    }

    imap_close($mbox);
    ?>


问:
Foreach ADO Enumerator doesn't show ADO object source variable
I have like 1 hour of SSIS experience so I do not know why this is failing.

I am following this guide.

However when I get to the Foreach loop editor screen section and pick "Foreach ADO enumerator" I cannot see the ADO Object source variable section.

The screen should look like this

Any ideas?

I am using Visual Studio 2015 and a release candidate of SSDT so this may be an issue.

I have followed all steps correctly and have seen no errors in previous steps

答:
I searched for this issue and i found two simple suggestions:

Try running visual studio in Safe mode using this command (this issue can be caused by a third-party add-on)

```<code>devenv.exe /safemode
</code>```

Try repairing your SQL Server Data Tools installation or Download the Latest release

Body:
I searched for this issue and i found two simple suggestions:

Try running visual studio in Safe mode using this command (this issue can be caused by a third-party add-on)

devenv.exe /safemode

Try repairing your SQL Server Data Tools installation or Download the Latest release


问:
Python: How to call a method from another module?
I have 2 files written in python. main.py looks like this:

```<code>import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cats.cat.talk()
</code>```

and cats.py that looks like this:

```<code>class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        dog.talk()
cat = Cat("pus")
cat.MakeDogTalk()
</code>```

as you can see, i am trying to make the dog talk from the cats module, is there some way to make this work? My real world app looks nothing like this btw...
of course,now i get this error:

```<code>line 9, in MakeDogTalk
dog.talk()
NameError: name 'dog' is not defined
</code>```

答:
You are referencing dog in MakeDogTalk, but it doesnt know what it is. Add this to your MakeDogTalk:</p>

```<code>    def MakeDogTalk(self):
        from main import dog
        dog.talk()
</code>```

Body:
I have 2 files written in python. main.py looks like this:

import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cats.cat.talk()

and cats.py that looks like this:

class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        dog.talk()
cat = Cat("pus")
cat.MakeDogTalk()

as you can see, i am trying to make the dog talk from the cats module, is there some way to make this work? My real world app looks nothing like this btw...
of course,now i get this error:

line 9, in MakeDogTalk
dog.talk()
NameError: name 'dog' is not defined

Body:
You are referencing dog in MakeDogTalk, but it doesnt know what it is. Add this to your MakeDogTalk:

    def MakeDogTalk(self):
        from main import dog
        dog.talk()


问:
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver
I'm running an AWS EC2 g2.2xlarge instance with Ubuntu 14.04 LTS.
I'd like to observe the GPU utilization while training my TensorFlow models.
I get an error trying to run 'nvidia-smi'.

```<code>ubuntu@ip-10-0-1-213:/etc/alternatives$ cd /usr/lib/nvidia-375/bin
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ ls
nvidia-bug-report.sh     nvidia-debugdump     nvidia-xconfig
nvidia-cuda-mps-control  nvidia-persistenced
nvidia-cuda-mps-server   nvidia-smi
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ ./nvidia-smi
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ dpkg -l | grep nvidia
ii  nvidia-346                                            352.63-0ubuntu0.14.04.1                             amd64        Transitional package for nvidia-346
ii  nvidia-346-dev                                        346.46-0ubuntu1                                     amd64        NVIDIA binary Xorg driver development files
ii  nvidia-346-uvm                                        346.96-0ubuntu0.0.1                                 amd64        Transitional package for nvidia-346
ii  nvidia-352                                            375.26-0ubuntu1                                     amd64        Transitional package for nvidia-375
ii  nvidia-375                                            375.39-0ubuntu0.14.04.1                             amd64        NVIDIA binary driver - version 375.39
ii  nvidia-375-dev                                        375.39-0ubuntu0.14.04.1                             amd64        NVIDIA binary Xorg driver development files
ii  nvidia-modprobe                                       375.26-0ubuntu1                                     amd64        Load the NVIDIA kernel driver and create device files
ii  nvidia-opencl-icd-346                                 352.63-0ubuntu0.14.04.1                             amd64        Transitional package for nvidia-opencl-icd-352
ii  nvidia-opencl-icd-352                                 375.26-0ubuntu1                                     amd64        Transitional package for nvidia-opencl-icd-375
ii  nvidia-opencl-icd-375                                 375.39-0ubuntu0.14.04.1                             amd64        NVIDIA OpenCL ICD
ii  nvidia-prime                                          0.6.2.1                                             amd64        Tools to enable NVIDIA's Prime
ii  nvidia-settings                                       375.26-0ubuntu1                                     amd64        Tool for configuring the NVIDIA graphics driver
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ lspci | grep -i nvidia
00:03.0 VGA compatible controller: NVIDIA Corporation GK104GL [GRID K520] (rev a1)
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$

$ inxi -G
Graphics:  Card-1: Cirrus Logic GD 5446
           Card-2: NVIDIA GK104GL [GRID K520]
           X.org: 1.15.1 driver: N/A tty size: 80x24 Advanced Data: N/A out of X

$  lspci -k | grep -A 2 -E "(VGA|3D)"
00:02.0 VGA compatible controller: Cirrus Logic GD 5446
    Subsystem: XenSource, Inc. Device 0001
    Kernel driver in use: cirrus
00:03.0 VGA compatible controller: NVIDIA Corporation GK104GL [GRID K520] (rev a1)
    Subsystem: NVIDIA Corporation Device 1014
00:1f.0 Unassigned class [ff80]: XenSource, Inc. Xen Platform Device (rev 01)
</code>```

I followed these instructions to install CUDA 7 and cuDNN:

```<code>$sudo apt-get -q2 update
$sudo apt-get upgrade
$sudo reboot
</code>```

=======================================================================

Post reboot, update the initramfs by running '$sudo update-initramfs -u'

Now, please edit the /etc/modprobe.d/blacklist.conf file to blacklist nouveau. Open the file in an editor and insert the following lines at the end of the file.

blacklist nouveau
blacklist lbm-nouveau
options nouveau modeset=0
alias nouveau off
alias lbm-nouveau off

Save and exit from the file.

Now install the build essential tools and update the initramfs and reboot again as below:

```<code>$sudo apt-get install linux-{headers,image,image-extra}-$(uname -r) build-essential
$sudo update-initramfs -u
$sudo reboot
</code>```

========================================================================

Post reboot, run the following commands to install Nvidia.

```<code>$sudo wget http://developer.download.nvidia.com/compute/cuda/7_0/Prod/local_installers/cuda_7.0.28_linux.run
$sudo chmod 700 ./cuda_7.0.28_linux.run
$sudo ./cuda_7.0.28_linux.run
$sudo update-initramfs -u
$sudo reboot
</code>```

========================================================================

Now that the system has come up, verify the installation by running the following.

```<code>$sudo modprobe nvidia
$sudo nvidia-smi -q | head`enter code here`
</code>```

You should see the output like 'nvidia.png'.

Now run the following commands.
$

```<code>cd ~/NVIDIA_CUDA-7.0_Samples/1_Utilities/deviceQuery
$make
$./deviceQuery
</code>```

However, 'nvidia-smi' still doesn't show GPU activity while Tensorflow is training models:

```<code>ubuntu@ip-10-0-1-48:~$ ipython
Python 2.7.11 |Anaconda custom (64-bit)| (default, Dec  6 2015, 18:08:32)
Type "copyright", "credits" or "license" for more information.

IPython 4.1.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import tensorflow as tf
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcublas.so.7.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcudnn.so.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcufft.so.7.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcurand.so.7.5 locally

ubuntu@ip-10-0-1-48:~$ nvidia-smi
Thu Mar 30 05:45:26 2017
+------------------------------------------------------+
| NVIDIA-SMI 346.46     Driver Version: 346.46         |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GRID K520           Off  | 0000:00:03.0     Off |                  N/A |
| N/A   35C    P0    38W / 125W |     10MiB /  4095MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+
</code>```

Body:
I'm running an AWS EC2 g2.2xlarge instance with Ubuntu 14.04 LTS.
I'd like to observe the GPU utilization while training my TensorFlow models.
I get an error trying to run 'nvidia-smi'.

ubuntu@ip-10-0-1-213:/etc/alternatives$ cd /usr/lib/nvidia-375/bin
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ ls
nvidia-bug-report.sh     nvidia-debugdump     nvidia-xconfig
nvidia-cuda-mps-control  nvidia-persistenced
nvidia-cuda-mps-server   nvidia-smi
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ ./nvidia-smi
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ dpkg -l | grep nvidia
ii  nvidia-346                                            352.63-0ubuntu0.14.04.1                             amd64        Transitional package for nvidia-346
ii  nvidia-346-dev                                        346.46-0ubuntu1                                     amd64        NVIDIA binary Xorg driver development files
ii  nvidia-346-uvm                                        346.96-0ubuntu0.0.1                                 amd64        Transitional package for nvidia-346
ii  nvidia-352                                            375.26-0ubuntu1                                     amd64        Transitional package for nvidia-375
ii  nvidia-375                                            375.39-0ubuntu0.14.04.1                             amd64        NVIDIA binary driver - version 375.39
ii  nvidia-375-dev                                        375.39-0ubuntu0.14.04.1                             amd64        NVIDIA binary Xorg driver development files
ii  nvidia-modprobe                                       375.26-0ubuntu1                                     amd64        Load the NVIDIA kernel driver and create device files
ii  nvidia-opencl-icd-346                                 352.63-0ubuntu0.14.04.1                             amd64        Transitional package for nvidia-opencl-icd-352
ii  nvidia-opencl-icd-352                                 375.26-0ubuntu1                                     amd64        Transitional package for nvidia-opencl-icd-375
ii  nvidia-opencl-icd-375                                 375.39-0ubuntu0.14.04.1                             amd64        NVIDIA OpenCL ICD
ii  nvidia-prime                                          0.6.2.1                                             amd64        Tools to enable NVIDIA's Prime
ii  nvidia-settings                                       375.26-0ubuntu1                                     amd64        Tool for configuring the NVIDIA graphics driver
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$ lspci | grep -i nvidia
00:03.0 VGA compatible controller: NVIDIA Corporation GK104GL [GRID K520] (rev a1)
ubuntu@ip-10-0-1-213:/usr/lib/nvidia-375/bin$

$ inxi -G
Graphics:  Card-1: Cirrus Logic GD 5446
           Card-2: NVIDIA GK104GL [GRID K520]
           X.org: 1.15.1 driver: N/A tty size: 80x24 Advanced Data: N/A out of X

$  lspci -k | grep -A 2 -E "(VGA|3D)"
00:02.0 VGA compatible controller: Cirrus Logic GD 5446
    Subsystem: XenSource, Inc. Device 0001
    Kernel driver in use: cirrus
00:03.0 VGA compatible controller: NVIDIA Corporation GK104GL [GRID K520] (rev a1)
    Subsystem: NVIDIA Corporation Device 1014
00:1f.0 Unassigned class [ff80]: XenSource, Inc. Xen Platform Device (rev 01)

I followed these instructions to install CUDA 7 and cuDNN:

$sudo apt-get -q2 update
$sudo apt-get upgrade
$sudo reboot

=======================================================================

Post reboot, update the initramfs by running '$sudo update-initramfs -u'

Now, please edit the /etc/modprobe.d/blacklist.conf file to blacklist nouveau. Open the file in an editor and insert the following lines at the end of the file.

blacklist nouveau
blacklist lbm-nouveau
options nouveau modeset=0
alias nouveau off
alias lbm-nouveau off

Save and exit from the file.

Now install the build essential tools and update the initramfs and reboot again as below:

$sudo apt-get install linux-{headers,image,image-extra}-$(uname -r) build-essential
$sudo update-initramfs -u
$sudo reboot

========================================================================

Post reboot, run the following commands to install Nvidia.

$sudo wget http://developer.download.nvidia.com/compute/cuda/7_0/Prod/local_installers/cuda_7.0.28_linux.run
$sudo chmod 700 ./cuda_7.0.28_linux.run
$sudo ./cuda_7.0.28_linux.run
$sudo update-initramfs -u
$sudo reboot

========================================================================

Now that the system has come up, verify the installation by running the following.

$sudo modprobe nvidia
$sudo nvidia-smi -q | head`enter code here`

You should see the output like 'nvidia.png'.

Now run the following commands.
$

cd ~/NVIDIA_CUDA-7.0_Samples/1_Utilities/deviceQuery
$make
$./deviceQuery

However, 'nvidia-smi' still doesn't show GPU activity while Tensorflow is training models:

ubuntu@ip-10-0-1-48:~$ ipython
Python 2.7.11 |Anaconda custom (64-bit)| (default, Dec  6 2015, 18:08:32)
Type "copyright", "credits" or "license" for more information.

IPython 4.1.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import tensorflow as tf
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcublas.so.7.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcudnn.so.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcufft.so.7.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcurand.so.7.5 locally

ubuntu@ip-10-0-1-48:~$ nvidia-smi
Thu Mar 30 05:45:26 2017
+------------------------------------------------------+
| NVIDIA-SMI 346.46     Driver Version: 346.46         |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GRID K520           Off  | 0000:00:03.0     Off |                  N/A |
| N/A   35C    P0    38W / 125W |     10MiB /  4095MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

Body:
I had to install the NVIDIA 367.57 driver and CUDA 7.5 with Tensorflow on the g2.2xlarge Ubuntu 14.04LTS instance.
e.g.
nvidia-graphics-drivers-367_367.57.orig.tar

Now the GRID K520 GPU is working while I train tensorflow models:

ubuntu@ip-10-0-1-70:~$ nvidia-smi
Sat Apr  1 18:03:32 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 367.57                 Driver Version: 367.57                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GRID K520           Off  | 0000:00:03.0     Off |                  N/A |
| N/A   39C    P8    43W / 125W |   3800MiB /  4036MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      2254    C   python                                        3798MiB |
+-----------------------------------------------------------------------------+

ubuntu@ip-10-0-1-70:~/NVIDIA_CUDA-7.0_Samples/1_Utilities/deviceQuery$ ./deviceQuery
./deviceQuery Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "GRID K520"
  CUDA Driver Version / Runtime Version          8.0 / 7.0
  CUDA Capability Major/Minor version number:    3.0
  Total amount of global memory:                 4036 MBytes (4232052736 bytes)
  ( 8) Multiprocessors, (192) CUDA Cores/MP:     1536 CUDA Cores
  GPU Max Clock rate:                            797 MHz (0.80 GHz)
  Memory Clock rate:                             2500 Mhz
  Memory Bus Width:                              256-bit
  L2 Cache Size:                                 524288 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65536), 3D=(4096, 4096, 4096)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 65536
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  2048
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (2147483647, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 2 copy engine(s)
  Run time limit on kernels:                     No
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 0 / 3
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 7.0, NumDevs = 1, Device0 = GRID K520
Result = PASS


问:
How to independently use single Zend Framework component like XML-RPC or REST?
Zend framework is well known for loosely coupled components.

I would like to use XML-RPC from zend framework, is there any dependency for XML-RPC? Like if I had taken out XML-RPC folder off Zend Framework Library and try to instantiate RPC object, would it throw error?

Where can I find the proper way of separating component from the framework?

Thanks

答: My first question is why you would want to do that in the first place.  It means that every time you upgrade Zend Framework you now need add a bunch of tooling to manage the removal of some components.  One of the purposes of using a framework is so you don't have to manage a bunch of code.  Removing parts of a framework is a step backwards IMHO.  Disk space is cheap.  Network transfer is cheap.  If you are going to remove parts of a framework you should have a REALLY, REALLY good reason to do it.</p>


问:
Writing loop or function for various t-tests
all.

I am very new to writing loops or functions in R, and I still haven't really understood how to do that. Currently, I need to write a loop/function (not sure which one would be better) to perform several t-tests with different data frames.

I have data that is similar to this:

```<code>set.seed(694)
df_1_08 <- data.frame(
  year = 2008,
  a = runif(100, 0, 100),
  b = runif(100, 0, 100),
  c = runif(100, 0, 100),
  d = runif(100, 0, 100)
)

df_1_09 <- data.frame(
  year = 2009,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_1_10 <- data.frame(
  year = 2010,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_2_08 <- data.frame(
  year = 2008,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_2_09 <- data.frame(
  year = 2009,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_2_10 <- data.frame(
  year = 2010,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

# Write Loop to do t-test between dfs 08, 09, 10 comparing columns a, b, c, d and storing the full results in a df
</code>```

Essentially, what I need to do with this data is to run t-tests for specific columns each year (2008, 2009, 2010) so that df_1_08 runs a t-test with df_2_08 in all columns (a, b, c, d) and then store these in a data frame (with the t-statistic, p-value, etc stored in it). This sounds like a job perfect for a loop. But I also need to do this for each of the years (2008, 2009, and 2010) and store the results in separate data frames, so this sounds like a job perfect for a function.

I'm unsure about how to write either, so I figured I'd ask for some help in writing these loops/functions. Thanks in advance for any help you might provide.

I could also have the dataframes combined into one large df with a column identifying the original data frame number (i.e. df1 or df2) and one column identifying the data frame year (i.e. 2008, 2009, 2010). It would look like this:

```<code>df1 <- rbind(df_1_08, df_1_09, df_1_10)
df1$ID <-1
df2 <- rbind(df_1_08, df_1_09, df_1_10)
df2$ID <- 2

master.df <- rbind(df1, df2)
</code>```

I'm not sure if it would be easier to write a loop/function to run the t.tests with the master.df. In that df, I would essentially need to do the following within a loop or function:

Subset master.df into df1 and df2

Subset df1 and df2 in years

Run t.test for columns a, b, c, and d for each year

Store all relevant t.test outputs (i.e. t-statistic, p-value, etc) in a data.frame that I can then print.

答:
How about:

```<code>df_1_08 <- data.frame(year = 2008, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_1_09 <- data.frame(year = 2009, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_1_10 <- data.frame(year = 2010, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_2_08 <- data.frame(year = 2008, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_2_09 <- data.frame(year = 2009, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_2_10 <- data.frame(year = 2010, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))

dfs_1.names <- ls()[grep("df_1", ls())]
dfs_2.names <- ls()[grep("df_2", ls())]
dfs_1.list <-lapply(dfs_1.names, get)
dfs_2.list <- lapply(dfs_2.names, get)

#in case you want to try the matrix
dfs_1.mtrx <- do.call("rbind",dfs_1.list)
dfs_2.mtrx <- do.call("rbind",dfs_2.list)

years <- intersect(unique(dfs_1.mtrx[,"year"]),unique(dfs_2.mtrx[,"year"]))
# [1] 2008 2009 2010
columns <- intersect(colnames(dfs_1.mtrx[,-1]),colnames(dfs_2.mtrx[,-1]))
# [1] "a" "b" "c" "d"

df.ttest <- as.data.frame(matrix(NA, ncol = 8, nrow = length(years)*length(columns)))
colnames(df.ttest) <- c("year","column","tstat","p.value","degreesf","low.conf","up.conf","data.name")
count = 0
for(i in 1:length(years)){
  for(j in columns){
    ttest <- t.test(dfs_1.list[[i]][j], dfs_2.list[[i]][j])
    ttest$data.name <- paste(paste0("df_1_",years[i]-2000,"$",j),"and",
                             paste0("df_2_",years[i]-2000,"$",j))
    count <- count + 1
    df.ttest[count, "year"]     <- years[i]
    df.ttest[count, "column"]   <- j
    df.ttest[count, "tstat"]    <- ttest$statistic
    df.ttest[count, "p.value"]  <- ttest$p.value
    df.ttest[count, "degreesf"] <- ttest$parameter
    df.ttest[count, "low.conf"] <- ttest$conf.int[1]
    df.ttest[count, "up.conf"]  <- ttest$conf.int[2]
    df.ttest[count, "data.name"] <- ttest$data.name
  }
}
df.ttest
</code>```

Which looks like:

```<code>   year column      tstat    p.value degreesf    low.conf   up.conf               data.name
1  2008      a  1.0607688 0.29008725 197.9914  -3.7038792 12.327117   df_1_8$a and df_2_8$a
2  2008      b  0.3311722 0.74086573 197.3689  -6.6956039  9.398291   df_1_8$b and df_2_8$b
3  2008      c  1.0410813 0.29910773 197.9405  -3.7582835 12.164152   df_1_8$c and df_2_8$c
4  2008      d  1.2623350 0.20834791 193.4532  -2.9384999 13.387911   df_1_8$d and df_2_8$d
5  2009      a -0.5764091 0.56500626 194.1686 -10.1442158  5.555762   df_1_9$a and df_2_9$a
6  2009      b -1.5222524 0.12954190 197.9248 -14.4317793  1.857603   df_1_9$b and df_2_9$b
7  2009      c -0.1744245 0.86171283 195.0217  -8.6590932  7.251902   df_1_9$c and df_2_9$c
8  2009      d  0.0839337 0.93319409 197.6654  -7.5768817  8.250526   df_1_9$d and df_2_9$d
9  2010      a  1.9125742 0.05724768 197.7406  -0.2353887 15.378495 df_1_10$a and df_2_10$a
10 2010      b  0.9024489 0.36792603 196.0224  -4.0977460 11.011904 df_1_10$b and df_2_10$b
11 2010      c -0.9735756 0.33145768 197.5899 -12.2641333  4.157135 df_1_10$c and df_2_10$c
12 2010      d  0.8721498 0.38418378 197.8601  -4.5311820 11.717207 df_1_10$d and df_2_10$d
</code>```

Body:
all.

I am very new to writing loops or functions in R, and I still haven't really understood how to do that. Currently, I need to write a loop/function (not sure which one would be better) to perform several t-tests with different data frames.

I have data that is similar to this:

set.seed(694)
df_1_08 <- data.frame(
  year = 2008,
  a = runif(100, 0, 100),
  b = runif(100, 0, 100),
  c = runif(100, 0, 100),
  d = runif(100, 0, 100)
)

df_1_09 <- data.frame(
  year = 2009,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_1_10 <- data.frame(
  year = 2010,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_2_08 <- data.frame(
  year = 2008,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_2_09 <- data.frame(
  year = 2009,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

df_2_10 <- data.frame(
  year = 2010,
  a = rnorm(100, 0, 1),
  b = rnorm(100, 0, 1),
  c = rnorm(100, 0, 1),
  d = rnorm(100, 0, 1)
)

# Write Loop to do t-test between dfs 08, 09, 10 comparing columns a, b, c, d and storing the full results in a df

Essentially, what I need to do with this data is to run t-tests for specific columns each year (2008, 2009, 2010) so that df_1_08 runs a t-test with df_2_08 in all columns (a, b, c, d) and then store these in a data frame (with the t-statistic, p-value, etc stored in it). This sounds like a job perfect for a loop. But I also need to do this for each of the years (2008, 2009, and 2010) and store the results in separate data frames, so this sounds like a job perfect for a function.

I'm unsure about how to write either, so I figured I'd ask for some help in writing these loops/functions. Thanks in advance for any help you might provide.

I could also have the dataframes combined into one large df with a column identifying the original data frame number (i.e. df1 or df2) and one column identifying the data frame year (i.e. 2008, 2009, 2010). It would look like this:

df1 <- rbind(df_1_08, df_1_09, df_1_10)
df1$ID <-1
df2 <- rbind(df_1_08, df_1_09, df_1_10)
df2$ID <- 2

master.df <- rbind(df1, df2)

I'm not sure if it would be easier to write a loop/function to run the t.tests with the master.df. In that df, I would essentially need to do the following within a loop or function:

Subset master.df into df1 and df2

Subset df1 and df2 in years

Run t.test for columns a, b, c, and d for each year

Store all relevant t.test outputs (i.e. t-statistic, p-value, etc) in a data.frame that I can then print.

Body:
How about:

df_1_08 <- data.frame(year = 2008, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_1_09 <- data.frame(year = 2009, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_1_10 <- data.frame(year = 2010, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_2_08 <- data.frame(year = 2008, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_2_09 <- data.frame(year = 2009, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))
df_2_10 <- data.frame(year = 2010, a = runif(100, 0, 100), b = runif(100, 0, 100), c = runif(100, 0, 100), d = runif(100, 0, 100))

dfs_1.names <- ls()[grep("df_1", ls())]
dfs_2.names <- ls()[grep("df_2", ls())]
dfs_1.list <-lapply(dfs_1.names, get)
dfs_2.list <- lapply(dfs_2.names, get)

#in case you want to try the matrix
dfs_1.mtrx <- do.call("rbind",dfs_1.list)
dfs_2.mtrx <- do.call("rbind",dfs_2.list)

years <- intersect(unique(dfs_1.mtrx[,"year"]),unique(dfs_2.mtrx[,"year"]))
# [1] 2008 2009 2010
columns <- intersect(colnames(dfs_1.mtrx[,-1]),colnames(dfs_2.mtrx[,-1]))
# [1] "a" "b" "c" "d"

df.ttest <- as.data.frame(matrix(NA, ncol = 8, nrow = length(years)*length(columns)))
colnames(df.ttest) <- c("year","column","tstat","p.value","degreesf","low.conf","up.conf","data.name")
count = 0
for(i in 1:length(years)){
  for(j in columns){
    ttest <- t.test(dfs_1.list[[i]][j], dfs_2.list[[i]][j])
    ttest$data.name <- paste(paste0("df_1_",years[i]-2000,"$",j),"and",
                             paste0("df_2_",years[i]-2000,"$",j))
    count <- count + 1
    df.ttest[count, "year"]     <- years[i]
    df.ttest[count, "column"]   <- j
    df.ttest[count, "tstat"]    <- ttest$statistic
    df.ttest[count, "p.value"]  <- ttest$p.value
    df.ttest[count, "degreesf"] <- ttest$parameter
    df.ttest[count, "low.conf"] <- ttest$conf.int[1]
    df.ttest[count, "up.conf"]  <- ttest$conf.int[2]
    df.ttest[count, "data.name"] <- ttest$data.name
  }
}
df.ttest

Which looks like:

   year column      tstat    p.value degreesf    low.conf   up.conf               data.name
1  2008      a  1.0607688 0.29008725 197.9914  -3.7038792 12.327117   df_1_8$a and df_2_8$a
2  2008      b  0.3311722 0.74086573 197.3689  -6.6956039  9.398291   df_1_8$b and df_2_8$b
3  2008      c  1.0410813 0.29910773 197.9405  -3.7582835 12.164152   df_1_8$c and df_2_8$c
4  2008      d  1.2623350 0.20834791 193.4532  -2.9384999 13.387911   df_1_8$d and df_2_8$d
5  2009      a -0.5764091 0.56500626 194.1686 -10.1442158  5.555762   df_1_9$a and df_2_9$a
6  2009      b -1.5222524 0.12954190 197.9248 -14.4317793  1.857603   df_1_9$b and df_2_9$b
7  2009      c -0.1744245 0.86171283 195.0217  -8.6590932  7.251902   df_1_9$c and df_2_9$c
8  2009      d  0.0839337 0.93319409 197.6654  -7.5768817  8.250526   df_1_9$d and df_2_9$d
9  2010      a  1.9125742 0.05724768 197.7406  -0.2353887 15.378495 df_1_10$a and df_2_10$a
10 2010      b  0.9024489 0.36792603 196.0224  -4.0977460 11.011904 df_1_10$b and df_2_10$b
11 2010      c -0.9735756 0.33145768 197.5899 -12.2641333  4.157135 df_1_10$c and df_2_10$c
12 2010      d  0.8721498 0.38418378 197.8601  -4.5311820 11.717207 df_1_10$d and df_2_10$d


答:
I did the following and it gave me the expected result: </p>

```<code>val custUserModifyTime = df
      .groupBy($"cust", $"user_id").agg(max($"modify_time")).collect()

 val mostRecent: Seq[DataFrame] = custUserModifyTime.map(x => df.select("*")
      .where("cust = '" + x.getAs[String]("cust") + "'" +
        " AND user_id = '" + x.getAs[String]("user_id") + "'" +
        " AND modify_time = '" + x.getAs[Timestamp]("max(modify_time)") + "'"))

val unifiedMostUpdatedData = mostRecent.reduce((a, b) => a.union(b))
</code>```

Title: How to select the most recent data from dataframe for a pair of keys?

Body:
I am new in Spark/Scala world, and I have a question regarding data selection from dataframes.
I have a table with the following data, and I need to choose for each cust and user_id pair, all the last modified records, with max modify_time:

Original data frame:

+--------+----------+------------+--------------------+
|  cust  | user_id  | another_id |     modify_time    |
+--------+----------+------------+--------------------+
|   cust1|   1      |         222|2017-03-22 07:29    |
|   cust1|   1      |         111|2017-03-22 07:29    |
|   cust2|   2      |         111|2017-03-21 07:29    |
|   cust1|   1      |         333|2017-03-21 07:29    |
|   cust2|   2      |         444|2017-03-22 07:29    |
|   cust2|   2      |         333|2017-03-22 07:29    |
+--------+----------+------------+--------------------+

The required result:

+--------+----------+------------+--------------------+
|  cust  | user_id  | another_id |     modify_time    |
+--------+----------+------------+--------------------+
|   cust1|   1      |         222|2017-03-22 07:29    |
|   cust1|   1      |         111|2017-03-22 07:29    |
|   cust2|   2      |         444|2017-03-22 07:29    |
|   cust2|   2      |         333|2017-03-22 07:29    |
+--------+----------+------------+--------------------+

What is the most efficient way to do so?

Body:
I did the following and it gave me the expected result:

val custUserModifyTime = df
      .groupBy($"cust", $"user_id").agg(max($"modify_time")).collect()

 val mostRecent: Seq[DataFrame] = custUserModifyTime.map(x => df.select("*")
      .where("cust = '" + x.getAs[String]("cust") + "'" +
        " AND user_id = '" + x.getAs[String]("user_id") + "'" +
        " AND modify_time = '" + x.getAs[Timestamp]("max(modify_time)") + "'"))

val unifiedMostUpdatedData = mostRecent.reduce((a, b) => a.union(b))


问:
What happens to variable x in this for loop in C?
In this code below

```<code>int main(){
int i;
for(i = 0;i<4;i++){
int x = 1;
x++;
} // for close
}// main close
</code>```

Here the variable x is `auto  storage class, right?

So, will the variable x get created, I mean memory allocation happens when the statement is encountered and gets destroyed when it reaches the end of the loop and gets created/memory is allocated again for x?

I tried to print the address of x in the loop and it prints the same address for x every time.So,does it mean every time x is created and destroyed and it is using the same room/memory block for it ?

If it is creating and destroying like that, doesn't it effect CPU usage?
If so, is there any way to prevent it and maintain good memory health?

答:
Short answer is "nothing". Any optimizing compiler will optimize this variable out, because it is never read.

Even when you turn off the optimizer, the variable would be allocated once upon entering the function, and then set to 1 in each iteration, followed by an increment.

The allocation is very cheap, because it is in the automatic storage. The space is decided at compile time, so at run-time it costs you nothing. All iterations reuse the same location, so there will be no additional costs due to iterating.

Body:
In this code below

int main(){
int i;
for(i = 0;i<4;i++){
int x = 1;
x++;
} // for close
}// main close

Here the variable x is `auto  storage class, right?

So, will the variable x get created, I mean memory allocation happens when the statement is encountered and gets destroyed when it reaches the end of the loop and gets created/memory is allocated again for x?

I tried to print the address of x in the loop and it prints the same address for x every time.So,does it mean every time x is created and destroyed and it is using the same room/memory block for it ?

If it is creating and destroying like that, doesn't it effect CPU usage?
If so, is there any way to prevent it and maintain good memory health?


问:
Why do these two images not wanna go on top of each other?
http://lucasdebelder.be/googledoodle/

I want to have the planet (bottom image) on top of the top image (the blue background/space). I have a main div class:"center" set on 'position: absolute' and around both of those images is separately a div wrapped with position: relative; but somehow they don't want to go and sit on top of each other, I've also tried it with z-index but that doesn't work either.

Thanks in advance.

答:
I would recommend nesting the two images in a div then adding a class to each image. Then use margin: 0 auto to center the div to the page. This is my solution:

#googledoodle {
  position: relative;
  top: 0;
  left: 0;
  height:512px;
  width:900px;
  margin: 0 auto;
  overflow: hidden;
}
.galaxy {
  position: relative;
  top: 0;
  left: 0;
}
.planet {
  position: absolute;
  top: 380px;
  left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="googledoodle">
 <img src="http://lucasdebelder.be/googledoodle/images/galaxy.png" width="900" class="galaxy">
 <img src="http://lucasdebelder.be/googledoodle/images/planeet.png" width="950" class="planet">
</div></code>```

Body:
I would recommend nesting the two images in a div then adding a class to each image. Then use margin: 0 auto to center the div to the page. This is my solution:

#googledoodle {
  position: relative;
  top: 0;
  left: 0;
  height:512px;
  width:900px;
  margin: 0 auto;
  overflow: hidden;
}
.galaxy {
  position: relative;
  top: 0;
  left: 0;
}
.planet {
  position: absolute;
  top: 380px;
  left: 0px;
}

<div id="googledoodle">
 <img src="http://lucasdebelder.be/googledoodle/images/galaxy.png" width="900" class="galaxy">
 <img src="http://lucasdebelder.be/googledoodle/images/planeet.png" width="950" class="planet">
</div>


问:
404 error after hosting website developed using codeigniter
I am trying to develop an web application that takes google address and stores for future use..

I am a little new to codeIgniter and a little help would be appreciable...
I have developed the application in WAMP 2.0..

It works fine there..But when I upload it to a production server, it displays the index page..but as soon as I try to navigate to other pages from the home page it gives a
404 Page Not Found..

You can always check the site  here..

The entire application is working fine in my localhost that is in WAMP..

Thanks in advance

答:
it may be to do with case sensitivity in *nix and windows environments.

this link works:

http://www.poimart.com/index.php/poi/create_user

but this doesn't (404s) (no capital P)

http://www.poimart.com/index.php/Poi/create_user

so any references to your pages within your app should have lower case.


问:
pbsnodes and bash string matching
I have a string of the form: "8, 14-24, 30-45, 9", which is a substring of the output of pbsnodes.  This shows the cores in use on a given node, where 14-24 is a range of cores in use.

I'd like to know the total number of cores in use from this string, i.e.
1 + (24 - 14 + 1) + (45 - 30 + 1 )+ 1 in this example, using a bash script.

Any suggestions or help is much appreciated.

Michael

答:
You could use pure bash techniques to achieve this. By reading the string to array and doing the arithmetic operator using the $((..)) operator. You can run these commands directly on the command-line,

```<code>IFS=", " read -ra numArray <<<"8, 14-24, 30-45, 9"

unset count
for word in "${numArray[@]}"; do
   (( ${#word} == 1 )) && ((++count)) || count=$(( count +  ${word#*-} - ${word%-*} + 1  ))
done

printf "%s\n" "$count"
</code>```

The idea is

The read with -a splits the string on the de-limiter set by IFS and reads it into the array numArray

A loop on each of the elements, for each element, if the element is just single character, just increment total count by 1

For numeric ranges, do manipulation as e.g. for number a-b use parameter expansion syntax ${word#*-} and ${word%-*} to extract b and a respectively and do b-a+1 and add it with count calculated already and print the element after the loop

You can put this in a bash script with she-bang set to #!/bin/bash and run the script or run it directly from the command-line

Title: pbsnodes and bash string matching

Body:
You could use pure bash techniques to achieve this. By reading the string to array and doing the arithmetic operator using the $((..)) operator. You can run these commands directly on the command-line,

IFS=", " read -ra numArray <<<"8, 14-24, 30-45, 9"

unset count
for word in "${numArray[@]}"; do
   (( ${#word} == 1 )) && ((++count)) || count=$(( count +  ${word#*-} - ${word%-*} + 1  ))
done

printf "%s\n" "$count"

The idea is

The read with -a splits the string on the de-limiter set by IFS and reads it into the array numArray

A loop on each of the elements, for each element, if the element is just single character, just increment total count by 1

For numeric ranges, do manipulation as e.g. for number a-b use parameter expansion syntax ${word#*-} and ${word%-*} to extract b and a respectively and do b-a+1 and add it with count calculated already and print the element after the loop

You can put this in a bash script with she-bang set to #!/bin/bash and run the script or run it directly from the command-line


问:
how to count no of records in and display in view

This error will show when i want to display no. of records in a table.
  A PHP Error was encountered

Severity: Notice

Message: Undefined variable: h

Filename: views/index.php

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/index.php

Controller

```<code>public function index() {
    if ($this->session->userdata('admin_logged_in')) {
        $data['h']= $this->admin_model->visitor_count();

        $this->load->view('header');
        $this->load->view('sidebar');
        $this->load->view('index',$data);
        $this->load->view('footer');
    } else {
        $this->load->view('login');
    }
}
</code>```

model

```<code>function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) FROM create_new_pass");
    return $query->num_rows();
}
</code>```

view

```<code><div class="inner">
<?php foreach ($h as $counts){?>
            <h3><?php echo $counts; ?></h3>
<?php } ?>
          <p>Total No. of Visitors till yet</p>
        </div>
</code>```

答:
There is problem in your model. You are COUNTing rows and then using num_rows which will allways return 1 (because count will be only one row).
Update your model:

```<code>function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) as count_rows FROM create_new_pass");
    return $query->row_array();
}
</code>```

and your view:

```<code><div class="inner">
    <h3><?php echo $h['count_rows']; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>
</code>```

Or you can use Query helper methods in your model:

```<code>function visitor_count() {
    return $this->db->count_all('create_new_pass');
}
</code>```

and your view:

```<code><div class="inner">
    <h3><?php echo $h; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>
</code>```

Body:
This error will show when i want to display no. of records in a table.
  A PHP Error was encountered

Severity: Notice

Message: Undefined variable: h

Filename: views/index.php

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/index.php

Controller

public function index() {
    if ($this->session->userdata('admin_logged_in')) {
        $data['h']= $this->admin_model->visitor_count();

        $this->load->view('header');
        $this->load->view('sidebar');
        $this->load->view('index',$data);
        $this->load->view('footer');
    } else {
        $this->load->view('login');
    }
}

model

function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) FROM create_new_pass");
    return $query->num_rows();
}

view

<?php foreach ($h as $counts){?>

<?php echo $counts; ?>

<?php } ?>

Total No. of Visitors till yet

Body:
There is problem in your model. You are COUNTing rows and then using num_rows which will allways return 1 (because count will be only one row).
Update your model:

function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) as count_rows FROM create_new_pass");
    return $query->row_array();
}

and your view:

<div class="inner">
    <h3><?php echo $h['count_rows']; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>

Or you can use Query helper methods in your model:

function visitor_count() {
    return $this->db->count_all('create_new_pass');
}

and your view:

<div class="inner">
    <h3><?php echo $h; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>


答:
Yes, the variable is constructed and destroyed for each turn in the loop.

However, as you have noticed, the compiler is smart enough to reuse the same storage for the variable each time. Likely on the stack, where the space could be allocated already when the function is entered. So there is no need to worry about the "memory management".

And if you turn on some optimizations, the compiler will also probably notice that none of the variables are really used for anything, and remove all of the code.

Title: What happens to variable x in this for loop in C?


答:
In each iteration of the for loop, you are creating the variable 'x,' setting it to 1, and incrementing it to 2.  'x' is being destroyed because it only exists within the for loop.  If you don't want it to be created and destroyed each iteration, you could simply declare it above the for loop.

What exactly are you trying to accomplish with this code, though?  It doesn't seem to be doing much.  Also, since you're worried about memory allocation, the variable 'i' could just be declared in the for loop so that you don't have it hanging around after you're done with the for loop.


问:
Time delay Tkinter
I'd like to make a graphic window in PyDev (Eclipse) python 2.75.

I've done few things but I'd like to make an "entrance" "blink". It's Tests the user input.
If it's an integer it should blink green for a second, and then turn into white. But if it's a string of something else it should blink red, and then turn into white. I've used a time.sleep() but it doesn't work as I'd like to.

Here is my code for this action:

```<code>def sprawdzam():

    z = e.get()
    try:
        z = int(z)
        e.config(bg = 'green')
        time.sleep(2)
        e.config(bg = 'white')

    except:
        l.config(bg = 'red')
        time.sleep(2)
        e.config(bg = 'white')
</code>```

答:
```<code>       for P in range(len(MaxTrace)):
           T = P + 1
           if T < len(MaxTrace):
               PrevPlate  , PrevDot   = MaxTrace[P][0], MaxTrace[P][1]
               TargetPlate, TargetDot = MaxTrace[T][0], MaxTrace[T][1]
               self.__window.update()
               sleep(0.3)
               #replace REGULAR token img to ACTIVE token img
               GameCanvas.itemconfig(self.tokens[PrevPlate,PrevDot],image=self.DotImgActv[RivalColor])
               self.__window.update()
               sleep(0.2)
               # mark Target vacation for move to by Yellow-RING img
               self.tokens[TargetPlate, TargetDot]=GameCanvas.create_image(DotXY[TargetPlate,TargetDot],
                                                                           image=self.DotVacantImg  )
               self.__window.update()
               sleep(0.4)
               GameCanvas.delete(self.tokens[PrevPlate,PrevDot])
               self.__window.update()
               sleep(0.3)
               GameCanvas.itemconfig(self.tokens[TargetPlate, TargetDot],image=self.DotImg[RivalColor])
</code>```

Title: Time delay Tkinter

Body:
I'd like to make a graphic window in PyDev (Eclipse) python 2.75.

I've done few things but I'd like to make an "entrance" "blink". It's Tests the user input.
If it's an integer it should blink green for a second, and then turn into white. But if it's a string of something else it should blink red, and then turn into white. I've used a time.sleep() but it doesn't work as I'd like to.

Here is my code for this action:

def sprawdzam():

    z = e.get()
    try:
        z = int(z)
        e.config(bg = 'green')
        time.sleep(2)
        e.config(bg = 'white')

    except:
        l.config(bg = 'red')
        time.sleep(2)
        e.config(bg = 'white')


问:
Can I convert my app for 64-bit with XCode 7.2.1?
I want to update/convert my iOS App for 64-bit so it will still run on iOS 11. I am still on Yosemite and don't currently have the time to upgrade to El Capitan so I'm stuck with XCode 7.2.1. Is it even possible to convert my App to a 64-bit binary with that version of XCode?

If yes, does anyone know a good description of how to do this? I haven't coded in XCode for a while and don't know where to begin with this task.

答:
From here:

In Xcode, set the following values:

Build settings > Architectures

Set to arm64 only. (click Other -> + and than enter arm64)

Build settings > Valid architectures

Set to arm64 only.

Really though I'd recommend you just update because you are missing out on a ton of features.


问:
Build an instance of Gson that can inflate subclasses
I have a list of objects that I need to deserialize into their proper subclasses. I have been able to get this working by building a gson object like below

```<code>    JsonDeserializer<Shape> jdTypes = (json, typeOfT, jsonContext) -> {
        JsonObject jsonObject = json.getAsJsonObject();
        int type = jsonObject.get("type").getAsInt();

        Gson gson = new Gson();

        switch (type){
            case Types.TYPE_CARD:
                return gson.fromJson(json, Card.class);

            case Types.TYPE_BLOCK:
                return gson.fromJson(json, Block.class);

            case Types.TYPE_STRIPE:
                return gson.fromJson(json, Stripe.class);

            //...

        }
    };

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Shape.class, jdTypes);
    builder.create();
</code>```

Although it is working, there has to be a better way of doing it. Currently I am creating an instance of Gson within my GsonBuilder. Yikes.  Is there a way I can use the Gson object I am about to build to deserialize the different sub-types?

答:
If I understand this issue correctly, you could just use the JsonDeserializationContext directly.

```<code>return jsonContext.deserialize(json, classOfType(type));
</code>```

Where classOfType() should just return the the class corresponding to the type of your shape.

Body:
I have a list of objects that I need to deserialize into their proper subclasses. I have been able to get this working by building a gson object like below

    JsonDeserializer<Shape> jdTypes = (json, typeOfT, jsonContext) -> {
        JsonObject jsonObject = json.getAsJsonObject();
        int type = jsonObject.get("type").getAsInt();

        Gson gson = new Gson();

        switch (type){
            case Types.TYPE_CARD:
                return gson.fromJson(json, Card.class);

            case Types.TYPE_BLOCK:
                return gson.fromJson(json, Block.class);

            case Types.TYPE_STRIPE:
                return gson.fromJson(json, Stripe.class);

            //...

        }
    };

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Shape.class, jdTypes);
    builder.create();

Although it is working, there has to be a better way of doing it. Currently I am creating an instance of Gson within my GsonBuilder. Yikes.  Is there a way I can use the Gson object I am about to build to deserialize the different sub-types?

Body:
If I understand this issue correctly, you could just use the JsonDeserializationContext directly.

return jsonContext.deserialize(json, classOfType(type));

Where classOfType() should just return the the class corresponding to the type of your shape.


问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
[regex]::Matches('RAM Statistics: 5954 / 8174 743=InUse 746=Peak','\D+(\d+)')|%{$_.groups[1].value}

It gives the next result::

5954
8174
743
746


问:
How can I color a graph (vertices and edges) with excel data?
I'm have an excel file with mostly 0's and 1's and I want to use this information to color the vertices and edges of a graph. So like if a cell is 0, color the edge gray, but if the cell is 1, color it blue. And similarly for vertices.

Can anyone give me a suggestion for how to go about this? What should I use to make the graph? And how do I tell it how to color it?

THANKS!

答:
Try using D3 graph. Visit https://d3js.org/

D3 uses javascript language. You can refer to multiple graphs.

Even you can take input data from excel file to create dynamic graphs.

You can refer to D3 network graph to understand how to change colour of vertex and edges of graph from given data http://christophergandrud.github.io/d3Network/


问:
git partial merge, not whole branch
I've read about some tricks with merge in Git: merging public and private branches while while keeping certain files intact in both branches and others and not found a solution.

In my case I'm feeling need to do opposite merge strategy. In parallel development I have to keep some files same across the arbitrary branches. From other side I do not want to do squash or no-commit merge, while difference are significant and could break current state of testing branch.

What I want something like

git checkout testing

git merge config.xml -b development or git merge config\*.xml -b development

I guess this is like git merge-files ... command, but second file delivered from the branch, not from the filesystem.
Is it possible? or may be there is a kind of workaround? submodules? attributes?

Thanks

答:
There are a couple things you can do.

One, you can cherry-pick the changes you want, which applies only a single commit. For example, if there's a change that only touches config.xml, you can cherry-pick it with

```<code>$ git cherry-pick $COMMIT_ID_YOU_WANT
</code>```

You could also just grab config.xml from the development branch:

```<code>$ git checkout testing
$ git checkout development -- config.xml
</code>```

That'll get you the same version of config.xml that exists in the development branch, but note that it won't pull in the history of changes to the file.

Title: git partial merge, not whole branch

Body:
There are a couple things you can do.

One, you can cherry-pick the changes you want, which applies only a single commit. For example, if there's a change that only touches config.xml, you can cherry-pick it with

$ git cherry-pick $COMMIT_ID_YOU_WANT

You could also just grab config.xml from the development branch:

$ git checkout testing
$ git checkout development -- config.xml

That'll get you the same version of config.xml that exists in the development branch, but note that it won't pull in the history of changes to the file.


问:
How to check two instances are having same values in android?
How can I check 2 instances of same class are equal or not in android?

code is as below

```<code>class Address{
    int id;
    String name;
    String street;
    City city;
    State state;
    List<Language> languages;
}
class City{
    int cityId;
    String cityName;
}
class State{
    int stateId;
    String stateName;
}
class Language{
    int langId,
    String langName;
}

class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    .
    Address address1=new Address();
    .
    .
    Address address2=new Address();
    .
    .
    .

    **check address1 and address2 are having same values**
    .
    .
    .

    }

}
</code>```

Kindly let me know the best way to check address1 and address2 instances are having same values or not.

Thanks.

答:
You can override the equals() method of the Address class and then in that method return true if the values are same else false.
For more details:
http://www.leepoint.net/data/expressions/22compareobjects.html

Body:
How can I check 2 instances of same class are equal or not in android?

code is as below

class Address{
    int id;
    String name;
    String street;
    City city;
    State state;
    List<Language> languages;
}
class City{
    int cityId;
    String cityName;
}
class State{
    int stateId;
    String stateName;
}
class Language{
    int langId,
    String langName;
}

class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    .
    Address address1=new Address();
    .
    .
    Address address2=new Address();
    .
    .
    .

    **check address1 and address2 are having same values**
    .
    .
    .

    }

}

Kindly let me know the best way to check address1 and address2 instances are having same values or not.

Thanks.


问:
DAX code to calculate cumulative count of events
I have a simple powerpivot model with a datetable and a milestone table.

 shown in the figure.  The milestone table has columns of milestone forecast and actual dates, eventually for six major milestones but two are shown.  I am able to summarize (calculated field) the COUNT of forecasted or actual milestone events by week and year.  But I cannot see how to also generate a cumulative total (YTD) of these counts - probably missing something that should be obvious.

The two calculated fields that work are:

```<code>MS1 YTD Forecast:=CALCULATE(COUNT([Forecast MS1 Date]))

MS1 YTD Actual:=CALCULATE(COUNT([Actual MS1 Date]), USERELATIONSHIP(milestones[Actual MS1 Date],datetbl[Date]))
</code>```

The pivotchart of this shows

Eventually I would like to create a report showing the progress for each milestone (actual vs forecast) for this project.

答:
I have a partial answer.  Added 'helper columns' with a 1 or 0 based on existence of a date.  THEN used Javier Guillen's "Running Totals" post (https://javierguillen.wordpress.com/2012/11/28/running-total-techniques-in-dax/) to create the lines.

But I get a syntax error when I attempt to apply the DAX Cumulative pattern to FILTER for valid dates.  My measure is:
Cumulative MS1 Actual :=
IF (
    MIN ( 'datetbl'[Date] )
        <= CALCULATE ( MAX (milestones[Actual MS1 Date] ), ALL (milestones) ),
    CALCULATE (
        SUM (milestones[MS1 Actual exists] ),
        USERELATIONSHIP(milestones[Actual MS1 Date],datetbl[Date]),
        FILTER (
            ALL ( 'datetbl'[Date] ),
            'milestones'[MS1 Actual Date] <= MAX ( 'milestones'[MS1 Actual Date] )
        )
    )
)

I am getting a semantic error 'column 'MS1 Actual Date' in table milestones cannot be found or may not be used in this expression.

unfortunately I cannot seem to post the updated chart or datamodel

Body:
I have a simple powerpivot model with a datetable and a milestone table.

 shown in the figure.  The milestone table has columns of milestone forecast and actual dates, eventually for six major milestones but two are shown.  I am able to summarize (calculated field) the COUNT of forecasted or actual milestone events by week and year.  But I cannot see how to also generate a cumulative total (YTD) of these counts - probably missing something that should be obvious.

The two calculated fields that work are:

MS1 YTD Forecast:=CALCULATE(COUNT([Forecast MS1 Date]))

MS1 YTD Actual:=CALCULATE(COUNT([Actual MS1 Date]), USERELATIONSHIP(milestones[Actual MS1 Date],datetbl[Date]))

The pivotchart of this shows

Eventually I would like to create a report showing the progress for each milestone (actual vs forecast) for this project.


问:
How do I make a color legend in gnuplot?
I have a plot which looks like this:

I would like to add a color legend, preferably outside the graph itself.  So, for example, a legend with a red dot and, after it, a description of what each red point in the plot means.  Similarly for blue.

i.e.

(red dot) 'description'

(blue dot) 'description'

Is there a way to do this in gnuplot?

答:
first, set the key properly:

```<code>set key top right outside
</code>```

Then add  title of to the plot command like this:

```<code>plot 'data1.txt' title 'description 1', 'data2.txt' title 'description 2'
</code>```

Body:
first, set the key properly:

set key top right outside

Then add  title of to the plot command like this:

plot 'data1.txt' title 'description 1', 'data2.txt' title 'description 2'