问:
Getting DDMathParser tokens and group tokens
I already found a solution to my problem on stackoverflow but it is in Objective-C. See this link
DDMathParser - Getting tokens

I translated this into Swift as shown below. So what is the latest way to get tokens from a string and to get grouped tokens?

For example: 1 + ($a - (3 / 4))

Here is my try:

```<code>do{
    let token = try Tokenizer(string: "1 + ($a - (3 /4))").tokenize()
    for element in token {
        print(element)
    }
} catch {
    print(error)
}
</code>```

But I get the following messages:

```<code>MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.OperatorToken
MathParser.VariableToken
MathParser.OperatorToken
MathParser.OperatorToken
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.OperatorToken
</code>```

How do I get the specific tokens from my string?

答:
You're getting all of the tokens.

OperatorToken, DecimalNumberToken, etc all inherit from a RawToken superclass. RawToken defines a .string and a .range property.

The .string is the actual String, as extracted or inferred from the source. The .range is where in the original string the token is located.

It's important to note, however, that there may be tokens produced by the tokenizer that are not present in the original string. For example, tokens get injected by the Tokenizer when resolving implicit multiplication (3x turns in to 3 * x).

Added later:

If you want the final tree of how it all gets parsed, then you want the Expression:

```<code>let expression = try Expression(string: "1 + ($a - (3 / 4))")
</code>```

At this point, you switch on expression.kind. It'll either be a number, a variable, or a function. function expressions have child expressions, representing the arguments to the function.

Body:
I already found a solution to my problem on stackoverflow but it is in Objective-C. See this link
DDMathParser - Getting tokens

I translated this into Swift as shown below. So what is the latest way to get tokens from a string and to get grouped tokens?

For example: 1 + ($a - (3 / 4))

Here is my try:

do{
    let token = try Tokenizer(string: "1 + ($a - (3 /4))").tokenize()
    for element in token {
        print(element)
    }
} catch {
    print(error)
}

But I get the following messages:

MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.OperatorToken
MathParser.VariableToken
MathParser.OperatorToken
MathParser.OperatorToken
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.OperatorToken

How do I get the specific tokens from my string?

Body:
You're getting all of the tokens.

OperatorToken, DecimalNumberToken, etc all inherit from a RawToken superclass. RawToken defines a .string and a .range property.

The .string is the actual String, as extracted or inferred from the source. The .range is where in the original string the token is located.

It's important to note, however, that there may be tokens produced by the tokenizer that are not present in the original string. For example, tokens get injected by the Tokenizer when resolving implicit multiplication (3x turns in to 3 * x).

Added later:

If you want the final tree of how it all gets parsed, then you want the Expression:

let expression = try Expression(string: "1 + ($a - (3 / 4))")

At this point, you switch on expression.kind. It'll either be a number, a variable, or a function. function expressions have child expressions, representing the arguments to the function.


来源: stackexchange

问:
How to write Xpath for webelement which are on iframe using firebug/Firepath?

I can write Xpath with or without Firebug/ Firepath but it would be great if there is work around to write Xpath with iframe using these third party tool.

First I need to move to iframe then write regular Xpath for webElements

答:
use xpath to find the iframe. then use getattribute() to get the src. then navigate to the src.

for example:

```<code>var myFrame = driver.FindElement("descendant::iframe[@name='TheIFrame']");
string frameSrc = myFrame.GetAttribute("src");
driver.Navigate().GoToUrl(frameSrc);
//now you're on the frame and interact with its DOM
</code>```

If you don't want to navigate away from the page you're on, you have a few otions:

1) Create a new driver and navigate there

2) use httpclient (less overhead than the driver) to get the content by sending a get to the src url, then use HTMLAgilityPack to load it into an HTMLDoc you can navigate with XPath - of course this will let you scrape data but you won't be able to click buttons or interact with javascript.

ContentLicense: CC BY-SA 3.0

Body:
use xpath to find the iframe. then use getattribute() to get the src. then navigate to the src.

for example:

var myFrame = driver.FindElement("descendant::iframe[@name='TheIFrame']");
string frameSrc = myFrame.GetAttribute("src");
driver.Navigate().GoToUrl(frameSrc);
//now you're on the frame and interact with its DOM

If you don't want to navigate away from the page you're on, you have a few otions:

1) Create a new driver and navigate there

2) use httpclient (less overhead than the driver) to get the content by sending a get to the src url, then use HTMLAgilityPack to load it into an HTMLDoc you can navigate with XPath - of course this will let you scrape data but you won't be able to click buttons or interact with javascript.


问:
Improperly creating timestamped filenames
I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module.

The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long?

I've tried numerous variations of the code below:

```<code>import os

import time
import datetime

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S")

sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st

os.system(sys_call)
</code>```

I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.

答:
Assuming...

```<code>st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S') <--- close with " instead of '
</code>```

isn't your problem... I've used the following code and it works for me.

```<code>ti = datetime.datetime.utcfromtimestamp(time.time()).strftime("%y-%m-%d_%H:%M:%S")
</code>```

outputs...

'17-11-18_01:47:48'

Note:  This outputs in UTC +0:00 so you'd need to apply another operation on it to get it to your timezone.  Since time.time() returns a UNIX epoch time in seconds, you'd need to offset the time by however much faster/slower your timezone is, in relation to UTC +0:00, in seconds.

I.e. if you're in EST time, then you'd apply utcfromtimestamp() on time.time() - 18000 to get the time for your timezone.

```<code>ti = datetime.datetime.utcfromtimestamp(time.time() - 18000).strftime("%y-%m-%d_%H:%M:%S")
</code>```

Body:
I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module.

The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long?

I've tried numerous variations of the code below:

import os

import time
import datetime

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S")

sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st

os.system(sys_call)

I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.

Body:
Assuming...

st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S') <--- close with " instead of '

isn't your problem... I've used the following code and it works for me.

ti = datetime.datetime.utcfromtimestamp(time.time()).strftime("%y-%m-%d_%H:%M:%S")

outputs...

'17-11-18_01:47:48'

Note:  This outputs in UTC +0:00 so you'd need to apply another operation on it to get it to your timezone.  Since time.time() returns a UNIX epoch time in seconds, you'd need to offset the time by however much faster/slower your timezone is, in relation to UTC +0:00, in seconds.

I.e. if you're in EST time, then you'd apply utcfromtimestamp() on time.time() - 18000 to get the time for your timezone.

ti = datetime.datetime.utcfromtimestamp(time.time() - 18000).strftime("%y-%m-%d_%H:%M:%S")


问:
how to place a gridview inside the html table
i am doing something like </p>

```<code><table>
<tr>
   <td width="15%" height="50"> Some content </td>
   <td width="25%" height="50"> My dropdown 1 </td>
   <td colspan="2" rowspan="3">
       <asp:gridview id="mygrid-1" runat="server">....<asp:gridview>
       <br>
     <asp:gridview id="mygrid-2" runat="server">....<asp:gridview>
   </td>
<tr>
<tr>
    <td width="15%" height="50"> Some content </td>
     <td width="25%" height="50"> My dropdown 2 </td>
</tr>
<tr>
    <td colspan="2" height="*">  </td>
</table>
</code>```

<p>On My dropdowns Selexted index change, both grids are populated , but this thing totally ignoring the height i have assigned to my 1st two tables rows , i want 1st two row height to be same as 50 , and on grid data population , i want 3rd row of table to grow in height </p>

答:
There are a few ways to maintain your row height here, but without seeing more I can't tell what the problem truly is. The first thing coming to mind when looking at your code here is that the width/height properties should really be done in CSS rather than in the html. Then, using CSS for those rows you could further maintain height using white-space:nowrap;depending on what that content is.

I'm not positive from looking here, but it seems you may be using your table for layout. Switch to using CSS for layout and turn those rows into
s and you can work with your gridview in a much more elegant and semantic way.

Body:
i am doing something like

    Some content
    My dropdown 1

       <asp:gridview id="mygrid-1" runat="server">....<asp:gridview>

     <asp:gridview id="mygrid-2" runat="server">....<asp:gridview>

     Some content
      My dropdown 2

On My dropdowns Selexted index change, both grids are populated , but this thing totally ignoring the height i have assigned to my 1st two tables rows , i want 1st two row height to be same as 50 , and on grid data population , i want 3rd row of table to grow in height

Body:
There are a few ways to maintain your row height here, but without seeing more I can't tell what the problem truly is. The first thing coming to mind when looking at your code here is that the width/height properties should really be done in CSS rather than in the html. Then, using CSS for those rows you could further maintain height using white-space:nowrap;depending on what that content is.

I'm not positive from looking here, but it seems you may be using your table for layout. Switch to using CSS for layout and turn those rows into <div>s and you can work with your gridview in a much more elegant and semantic way.

ContentLicense: CC BY-SA 2.5


问:
ajax fail to POST on API
i tried everything, and i still cant figure out whats the problem, i'm trying to 'POST' something on teachers server that we had for homework, and i have no idea what i'm doing wrong ,i'm stuck for like 2 hours already.

here is my code.

```<code>const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
  if(xhr.readyState === XMLHttpRequest.DONE){
    console.log(xhr.response);
  }
}
xhr.open('POST',url);
xhr.send(attendee);
</code>```

答:
Please see this snippet, you are getting The 401 Unauthorized error, you have to attach authorization token variable to the request.

xhr.setRequestHeader('Authorization', '~Token~');

There will be an other api that will get authorization token.

const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
  if(xhr.readyState === XMLHttpRequest.DONE){
    console.log(xhr.response);
  }
  else{
    console.log(xhr.status);
  }
}
xhr.open('POST',url);
xhr.send(attendee);```

Title: ajax fail to POST on API

Body:
i tried everything, and i still cant figure out whats the problem, i'm trying to 'POST' something on teachers server that we had for homework, and i have no idea what i'm doing wrong ,i'm stuck for like 2 hours already.

here is my code.

const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
  if(xhr.readyState === XMLHttpRequest.DONE){
    console.log(xhr.response);
  }
}
xhr.open('POST',url);
xhr.send(attendee);


问:
What will happen if variable is not declared in Javascript?
For example, I have code like this:

```<code>var Player = function(param){
    var self = {
    x:0,
    y:0,
    spdX:0,
    spdY:0,
    id:"",
    }
    self.hp = 24;
}
</code>```

Do I need to add hp inside var self = {}?

答:
I believe others have misunderstood the question. If I understand correctly, you are asking about any potential issues with dynamically adding properties to an existing object (vs. when first declaring the object). The answer is that it is fine to do, is common JS practice and should have no negative performance impact.

This is a perfectly reasonable question if you are coming from a statically typed language background. For example, in TypeScript, you cannot add properties to an object after it has been defined (see this question). This is done for:

Type safety (far and away the main reason)

Performance (possibly).

Body:
For example, I have code like this:

var Player = function(param){
    var self = {
    x:0,
    y:0,
    spdX:0,
    spdY:0,
    id:"",
    }
    self.hp = 24;
}

Do I need to add hp inside var self = {}?


问:
Get int variables within a String method Java
This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do

```<code>import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
    int length, odd, even, largest;
    int n = getNumber();
    length=odd=even=largest=initialize();
    String sequence=createSequence(n, largest, odd, even, length);
    displaySequence(sequence);
    displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
   Scanner kb = new Scanner(System.in);
   System.out.println("Enter the value of the number: ");
   int number = kb.nextInt();
   return number;
}
private static int initialize(){
    return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
    String sequence="";
    sequence+=n+" ";
    while (n!=1){
        n = (n%2==0) ? n/2 : 3*n+1;
        System.out.print(", "+n);
        sequence+=n+" ";
        if(n%2==0){ even++;
        }else{ odd++;}
        if(n>=largest){ largest = n;
        }
        length++;
    }
    return sequence;
}
private static void displaySequence(String sequence){
    System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
    String nil = "";
    System.out.println("The largest number in the sequence was "+largest);
    System.out.println("The length of the sequence was "+length);
    System.out.println("There were "+odd+" odd numbers");
    System.out.println("There were "+even+" even numbers");
    return nil;
}

}
</code>```

I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?

Note:

Requirements:

Declare variables in main

Initialize variables in Initialize()

createSequence (Create the sequence)

displaySequence (Then display the sequence in a separate method)

finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me

答:
Try reimplementing your code off of my basecode</p>

```<code>public class Question{

    public class NumberStats {
        int len;
        boolean isOdd;
    }

    private ArrayList<NumberStats> stats = new ArrayList<>();
    public static void main(String[] args){
        Question q = new Question();
        Scanner kb = new Scanner(System.in);
        String number = "";
        do {
            System.out.println("Enter a series of numbers or q to quit: ");
            number = kb.next();
            q.stats.add(q.parseNumber(number));
        } while (number.equals("q")==false);

        q.printSummary();

    }

    private void printSummary(){
        int oddCount = 0;
        int evenCount = 0;
        int longestNumber = 0;

        for (NumberStats s : stats){
            if (longestNumber<s.len){
                longestNumber = s.len;
            }
            if (s.isOdd){
                oddCount+=1;
            } else {
                evenCount+=1;
            }
        }
        System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
    }
    private NumberStats parseNumber(String number){
        NumberStats stats = new NumberStats();
        Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
        stats.isOdd = true;
        if (lastNumber%2==0){
            stats.isOdd = false;
        }
        stats.len = number.length();
        return stats;

    }
}
</code>```

Body:
This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do

import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
    int length, odd, even, largest;
    int n = getNumber();
    length=odd=even=largest=initialize();
    String sequence=createSequence(n, largest, odd, even, length);
    displaySequence(sequence);
    displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
   Scanner kb = new Scanner(System.in);
   System.out.println("Enter the value of the number: ");
   int number = kb.nextInt();
   return number;
}
private static int initialize(){
    return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
    String sequence="";
    sequence+=n+" ";
    while (n!=1){
        n = (n%2==0) ? n/2 : 3*n+1;
        System.out.print(", "+n);
        sequence+=n+" ";
        if(n%2==0){ even++;
        }else{ odd++;}
        if(n>=largest){ largest = n;
        }
        length++;
    }
    return sequence;
}
private static void displaySequence(String sequence){
    System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
    String nil = "";
    System.out.println("The largest number in the sequence was "+largest);
    System.out.println("The length of the sequence was "+length);
    System.out.println("There were "+odd+" odd numbers");
    System.out.println("There were "+even+" even numbers");
    return nil;
}

}

I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?

Note:

Requirements:

Declare variables in main

Initialize variables in Initialize()

createSequence (Create the sequence)

displaySequence (Then display the sequence in a separate method)

finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me

Body:
Try reimplementing your code off of my basecode

public class Question{

    public class NumberStats {
        int len;
        boolean isOdd;
    }

    private ArrayList<NumberStats> stats = new ArrayList<>();
    public static void main(String[] args){
        Question q = new Question();
        Scanner kb = new Scanner(System.in);
        String number = "";
        do {
            System.out.println("Enter a series of numbers or q to quit: ");
            number = kb.next();
            q.stats.add(q.parseNumber(number));
        } while (number.equals("q")==false);

        q.printSummary();

    }

    private void printSummary(){
        int oddCount = 0;
        int evenCount = 0;
        int longestNumber = 0;

        for (NumberStats s : stats){
            if (longestNumber<s.len){
                longestNumber = s.len;
            }
            if (s.isOdd){
                oddCount+=1;
            } else {
                evenCount+=1;
            }
        }
        System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
    }
    private NumberStats parseNumber(String number){
        NumberStats stats = new NumberStats();
        Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
        stats.isOdd = true;
        if (lastNumber%2==0){
            stats.isOdd = false;
        }
        stats.len = number.length();
        return stats;

    }
}


问:
Python Histogram of Oriented Gradients
I am trying to implement this version of Histogram of Oriented Gradients(HOG). My code is below. The only difference in my code is that I've used opencv to read the image and convert it to grayscale.

```<code>import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = 'match1/hockey15.jpg'
im = cv2.imread(filename)
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.show()
</code>```

A sample input and output are:

Input:

Output:

Why is the output so cluttered? I have even tried the image with the astronaut in the skimage link above. For this too, I get a lot of clutter and the output is not at all like what is shown in the link. How can I fix this?

答:
Just change the value 0.02 to something like 0.5. That will make it darker.

```<code>hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))
</code>```

Change to

```<code>hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.5))
</code>```

Title: Python Histogram of Oriented Gradients

Body:
I am trying to implement this version of Histogram of Oriented Gradients(HOG). My code is below. The only difference in my code is that I've used opencv to read the image and convert it to grayscale.

import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = 'match1/hockey15.jpg'
im = cv2.imread(filename)
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.show()

A sample input and output are:

Input:

Output:

Why is the output so cluttered? I have even tried the image with the astronaut in the skimage link above. For this too, I get a lot of clutter and the output is not at all like what is shown in the link. How can I fix this?

Body:
Just change the value 0.02 to something like 0.5. That will make it darker.

hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

Change to

hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.5))


问:
Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"
I would like install R on my laptop Mac OS X version 10.7.3

I downloaded the last version and I double click on it and it was installed, when i start up I get the following error, I searched in internet but I could not solve the problem, any help would be appreciated

the errors are

During startup - Warning messages:

  1: Setting LC_CTYPE failed, using "C"

  2: Setting LC_COLLATE failed, using "C"

  3: Setting LC_TIME failed, using "C"

  4: Setting LC_MESSAGES failed, using "C"

  5: Setting LC_PAPER failed, using "C"

  [R.app GUI 1.50 (6126) x86_64-apple-darwin9.8.0]

WARNING: You're using a non-UTF8 locale, therefore only ASCII characters will work.
  Please read R for Mac OS X FAQ (see Help) section 9 and adjust your system preferences accordingly.
  [History restored from /Users/nemo/.Rapp.history]

答:
On my Mac r is installed in /usr/local/bin/r, add line below in .bash_profile solved the same problem:

```<code>alias r="LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 r"
</code>```

Body:
On my Mac r is installed in /usr/local/bin/r, add line below in .bash_profile solved the same problem:

alias r="LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 r"


问:
How do I clone a Django model instance object and save it to the database?
```<code>Foo.objects.get(pk="foo")
<Foo: test>
</code>```

In the database, I want to add another object which is a copy of the object above.

Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that?

答:
Just change the primary key of your object and run save().

```<code>obj = Foo.objects.get(pk=<some_existing_pk>)
obj.pk = None
obj.save()
</code>```

If you want auto-generated key, set the new key to None.

More on UPDATE/INSERT here.

Official docs on copying model instances: https://docs.djangoproject.com/en/2.2/topics/db/queries/#copying-model-instances

Body:
Foo.objects.get(pk="foo")
<Foo: test>

In the database, I want to add another object which is a copy of the object above.

Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that?

Body:
Just change the primary key of your object and run save().

obj = Foo.objects.get(pk=<some_existing_pk>)
obj.pk = None
obj.save()

If you want auto-generated key, set the new key to None.

More on UPDATE/INSERT here.

Official docs on copying model instances: https://docs.djangoproject.com/en/2.2/topics/db/queries/#copying-model-instances

ContentLicense: CC BY-SA 4.0


问:
How to insert a foreign key spring mvc jdbc template
I'm doing a crud with two tables:

```<code>CREATE TABLE productos (
    id int NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) ,
    nombre varchar(40) NOT NULL,
    precio varchar(40) NOT NULL,
    fecha_vencimiento varchar(40) NOT NULL,
    FOREIGN KEY (NOMBRE) REFERENCES FABRICANTE(NOMBRE));
CREATE FABRICANTE (
    nombre varchar(40) PRIMARY KEY  NOT NULL,
    direccion varchar(40) NOT NULL,
    telefono varchar(40) NOT NULL,
    tipo varchar(40) NOT NULL);
</code>```

but I have not found how to insert the value of the foreign key in the table productos.
currently I'm only saving the data from the product table, but not the foreign key
    package Controller;

```<code>import Modelo.Conectar;
import Modelo.Productos;
import Modelo.ProductosValidar;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
* @author aula3
*/
@Controller
@RequestMapping("add.htm")
public class AddController {
ProductosValidar productosValidar;
private JdbcTemplate jdbcTemplate;

public AddController()
{
    this.productosValidar=new ProductosValidar();
    Conectar con=new Conectar();
    this.jdbcTemplate=new JdbcTemplate(con.conectar() );
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView form()
{
    ModelAndView mav=new ModelAndView();
    mav.setViewName("add");
    mav.addObject("productos",new Productos());
    return mav;
}
@RequestMapping(method=RequestMethod.POST)
public ModelAndView form
    (
            @ModelAttribute("productos") Productos p,
            BindingResult result,
            SessionStatus status
    )
{
    this.productosValidar.validate(p, result);
    if(result.hasErrors())
    {
        ModelAndView mav=new ModelAndView();
        mav.setViewName("add");
        mav.addObject("productos",new Productos());
        return mav;
    }else
    {
    this.jdbcTemplate.update
    (
    "insert into productos (nombre,precio,fecha_vencimiento ) values (?,?,?)",
     p.getNombre(),p.getPrecio(),p.getFecha_vencimiento()
    );
     return new ModelAndView("redirect:/home.htm");
    }

}
}
</code>```

In which part of the controller should I place the code of the foreign key?

答:
you have the line FOREIGN KEY (FABRICANTE_NOMBRE) REFERENCES FABRICANTE(NOMBRE));
but you don't have a column in your table called FABRICANTE_NOMBRE

Body:
I'm doing a crud with two tables:

CREATE TABLE productos (
    id int NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) ,
    nombre varchar(40) NOT NULL,
    precio varchar(40) NOT NULL,
    fecha_vencimiento varchar(40) NOT NULL,
    FOREIGN KEY (NOMBRE) REFERENCES FABRICANTE(NOMBRE));
CREATE FABRICANTE (
    nombre varchar(40) PRIMARY KEY  NOT NULL,
    direccion varchar(40) NOT NULL,
    telefono varchar(40) NOT NULL,
    tipo varchar(40) NOT NULL);

but I have not found how to insert the value of the foreign key in the table productos.
currently I'm only saving the data from the product table, but not the foreign key
    package Controller;

import Modelo.Conectar;
import Modelo.Productos;
import Modelo.ProductosValidar;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
* @author aula3
*/
@Controller
@RequestMapping("add.htm")
public class AddController {
ProductosValidar productosValidar;
private JdbcTemplate jdbcTemplate;

public AddController()
{
    this.productosValidar=new ProductosValidar();
    Conectar con=new Conectar();
    this.jdbcTemplate=new JdbcTemplate(con.conectar() );
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView form()
{
    ModelAndView mav=new ModelAndView();
    mav.setViewName("add");
    mav.addObject("productos",new Productos());
    return mav;
}
@RequestMapping(method=RequestMethod.POST)
public ModelAndView form
    (
            @ModelAttribute("productos") Productos p,
            BindingResult result,
            SessionStatus status
    )
{
    this.productosValidar.validate(p, result);
    if(result.hasErrors())
    {
        ModelAndView mav=new ModelAndView();
        mav.setViewName("add");
        mav.addObject("productos",new Productos());
        return mav;
    }else
    {
    this.jdbcTemplate.update
    (
    "insert into productos (nombre,precio,fecha_vencimiento ) values (?,?,?)",
     p.getNombre(),p.getPrecio(),p.getFecha_vencimiento()
    );
     return new ModelAndView("redirect:/home.htm");
    }

}
}

In which part of the controller should I place the code of the foreign key?


问:
How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?
How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

答: Look into the MemoryStream class.

Body: Look into the MemoryStream class.


问:
MySQL query to print data from two tables

I need help with writing a MySQL query to print the respective department names and number of Employee for all departments in the Department table.

Expected output:

```<code>Executive 2
Technical 2
Production 1
</code>```

答:
A join command would be what you are looking for.

```<code>select transaction.username, transaction.transactiondate, products.price, products.quantity, products.description
from transaction, products
where products.productid = transaction.productid
  and products.productid = IDHERE
</code>```

Body:
I need help with writing a MySQL query to print the respective department names and number of Employee for all departments in the Department table.

Expected output:

Executive 2
Technical 2
Production 1

Body:
A join command would be what you are looking for.

select transaction.username, transaction.transactiondate, products.price, products.quantity, products.description
from transaction, products
where products.productid = transaction.productid
  and products.productid = IDHERE


问:
getting exception while trying to query xdocument
I am trying to extract the data from Web response having XML format using the below code
but I am getting null reference exception here at this line  var status = html.Element("Status");

```<code>if (oHttpWebResponse.StatusCode.ToString().ToLower() == "ok")
    {
        string contentType = oHttpWebResponse.ContentType;
        Stream content = oHttpWebResponse.GetResponseStream();
        XDocument xDoc = new XDocument(XDocument.Load(content));
        var html = xDoc.Root.Element("html");
        var status = html.Element("Status"); // getting System.NullReferenceException here
       var statusValue = status.Value;
        var lice = html.Element("LicenseKey").Value;

    }
</code>```

I am not why i am getting this error and xml format looks like this ..

```<code><html>
<Status>
200
</Status>
<LicenseKey>
FXOZ-HTTEKG-3QYB-MP2NPQ-AC7I3C-76SX-DVN4BA-C55RMK-RV2P-O5NSOQ
</LicenseKey>
<CustomerId>
U2N3XCAV
</CustomerId>
</html>
</code>```

I am not sure why i am getting this error, If any one please help on this query that would be very grateful to me ..

Thanks in advance..

答:
xDoc.Root is the whole text, since the root is the html tag. It has no child elements.
In order to fetch an element based on its name, you can run the following code:

```<code>var status = xDoc.Root.Elements("Status").FirstOrDefault();
// ensure not null is assigned to "stringValue"
var statusValue = status==null? String.Empty: status.Value;
</code>```

After C# 6.0, you can use this assignment as well to ensure null is not assigned to stringValue:

```<code>statusValue = status?.Value ?? String.Empty;
</code>```

Body:
I am trying to extract the data from Web response having XML format using the below code
but I am getting null reference exception here at this line  var status = html.Element("Status");

if (oHttpWebResponse.StatusCode.ToString().ToLower() == "ok")
    {
        string contentType = oHttpWebResponse.ContentType;
        Stream content = oHttpWebResponse.GetResponseStream();
        XDocument xDoc = new XDocument(XDocument.Load(content));
        var html = xDoc.Root.Element("html");
        var status = html.Element("Status"); // getting System.NullReferenceException here
       var statusValue = status.Value;
        var lice = html.Element("LicenseKey").Value;

    }

I am not why i am getting this error and xml format looks like this ..

<Status>
200
</Status>
<LicenseKey>
FXOZ-HTTEKG-3QYB-MP2NPQ-AC7I3C-76SX-DVN4BA-C55RMK-RV2P-O5NSOQ
</LicenseKey>
<CustomerId>
U2N3XCAV
</CustomerId>

I am not sure why i am getting this error, If any one please help on this query that would be very grateful to me ..

Thanks in advance..

Body:
xDoc.Root is the whole text, since the root is the html tag. It has no child elements.
In order to fetch an element based on its name, you can run the following code:

var status = xDoc.Root.Elements("Status").FirstOrDefault();
// ensure not null is assigned to "stringValue"
var statusValue = status==null? String.Empty: status.Value;

After C# 6.0, you can use this assignment as well to ensure null is not assigned to stringValue:

statusValue = status?.Value ?? String.Empty;


问:
Can Anybody Explain Why This Script Cannot Be Uploaded as an External Resource?
I am currently working within Tumblr's theme builder framework, and have been facing some difficulties uploading certain scripts as external resources. Upon several upload attempts, I continuously received an error message implying that Tumblr does not accept .html files to be uploaded as an asset, even though the file I am attempting to upload is a .js file.

I suppose it's worth noting that my site runs via HTTPS, so why would a code, (as shown below), not be able to be loaded as an external source/asset?

UPDATE: Ok, so far the issue has something to do with this portion of HTML in the script:

```<code>if (photos[j].alt_sizes[1]) {
        imgURL = photos[j].alt_sizes[1].url;
        // console.log(imgURL, linkURL);
      } else {
        continue;
      }
      $("#tumblr-posts").append(
        "<li><a href=" +
          linkURL +
          "><img src=" +
          imgURL +
          " /></a>" +
          "</li>"
      );
    }
</code>```

The denied external JS (mycustomscript.js):

```<code>apiKey = "API-HIDDEN";
limit = 4;
$.ajax({
  url: "https://api.tumblr.com/v2/blog/MYTUMBLRID.tumblr.com/posts?limit=4",
  dataType: "jsonp",
  data: {
    api_key: apiKey,
    tag: "blog"
  },
  success: function(results) {
    var i = 0;
    while (i < results.response.posts.length) {
      var type = results.response.posts[i].type;
      if (type == "photo") {
        var photos = results.response.posts[i].photos;
        var linkURL = results.response.posts[i].post_url;
        var caption = results.response.posts[i].caption;
        for (var j = 0; j < photos.length; j++) {
          if (photos[j].alt_sizes[1]) {
            imgURL = photos[j].alt_sizes[1].url;
            // console.log(imgURL, linkURL);
          } else {
            continue;
          }
          $("#tumblr-posts").append(
            "<li><a href=" +
              linkURL +
              "><img src=" +
              imgURL +
              " /></a>" +
              "</li>"
          );
        }
      }
      i++;
    }
    console.log(results.response);
  }
});
</code>```

How I've attempted to call for the script, (x's in place to conceal hidden link portions):

```<code><script src="http://static.tumblr.com/x/x/mycustomscript.js"></script>
</code>```

答:
It’s due the HTML tags in the script. You can work around this by splitting the HTML tags so

```<code>"<li>"
</code>```

Becomes

```<code>"<"+"li>"
</code>```

And do the same with end tags too.

Body:
I am currently working within Tumblr's theme builder framework, and have been facing some difficulties uploading certain scripts as external resources. Upon several upload attempts, I continuously received an error message implying that Tumblr does not accept .html files to be uploaded as an asset, even though the file I am attempting to upload is a .js file.

I suppose it's worth noting that my site runs via HTTPS, so why would a code, (as shown below), not be able to be loaded as an external source/asset?

UPDATE: Ok, so far the issue has something to do with this portion of HTML in the script:

if (photos[j].alt_sizes[1]) {
        imgURL = photos[j].alt_sizes[1].url;
        // console.log(imgURL, linkURL);
      } else {
        continue;
      }
      $("#tumblr-posts").append(
        "
" +
          "
"
      );
    }

The denied external JS (mycustomscript.js):

apiKey = "API-HIDDEN";
limit = 4;
$.ajax({
  url: "https://api.tumblr.com/v2/blog/MYTUMBLRID.tumblr.com/posts?limit=4",
  dataType: "jsonp",
  data: {
    api_key: apiKey,
    tag: "blog"
  },
  success: function(results) {
    var i = 0;
    while (i < results.response.posts.length) {
      var type = results.response.posts[i].type;
      if (type == "photo") {
        var photos = results.response.posts[i].photos;
        var linkURL = results.response.posts[i].post_url;
        var caption = results.response.posts[i].caption;
        for (var j = 0; j < photos.length; j++) {
          if (photos[j].alt_sizes[1]) {
            imgURL = photos[j].alt_sizes[1].url;
            // console.log(imgURL, linkURL);
          } else {
            continue;
          }
          $("#tumblr-posts").append(
            "
" +
              "
"
          );
        }
      }
      i++;
    }
    console.log(results.response);
  }
});

How I've attempted to call for the script, (x's in place to conceal hidden link portions):

Body:
It’s due the HTML tags in the script. You can work around this by splitting the HTML tags so

"<li>"

Becomes

"<"+"li>"

And do the same with end tags too.


问:
Error with Varchar to Numeric
For background: this works fine without the addition of the 'E' Table in production.

I am trying to execute the below query but am getting the error:

Msg 8114, Level 16, State 5, Line 10

  Error converting data type varchar to numeric.

The odd thing is that it executes fine on our test DB - not seeing anything trying to convert to numeric so a bit baffled. Not really sure what would cause that difference as I assume data types are the same in the test DB and the production DB - any ideas?

Thanks.

```<code>/* - adding po balance qty causes duplicates
   - adding stock category causes duplicates
   - added PO comments using MAX function to return only first comment - gets rid of duplicates*/

/* Using NEW employee table as of 11/2 */
SELECT
    S.team_member_name AS [ASSIGNED EMPLOYEE],  --Using new employee table - only on bus unit as of 11/2
    H.po_type AS [ PO TYPE],
    G.order_no AS [GPS PO #],
    P.po_number AS [SAP PO NUMBER],
    M.department AS [DEPARTMENT],
    G.order_qty AS [GPS QTY],
    SUM(P.po_ordered_quantity) AS [SAP QUANTITY],
    (SUM(P.po_ordered_quantity) - G.order_qty) AS [DIFFERENCE],
    G.last_conf_date_cst AS [LAST CONFIRMED DATE],
    K.business_unit_desc AS [BU],
    M.[description] AS [DESCRIPTION],
    P.material AS [MATERIAL],
    MAX(P.comment) AS [PO COMMENT],
    MIN(E.date) AS [FIRST SHOWN ON RPT]
FROM
    (SELECT
         order_no, order_qty, order_status,
         last_conf_date_cst
     FROM
         asagdwpdx_prod.dbo.SimoxOrder1
     UNION ALL
     SELECT
         order_no, order_qty, order_status,
         last_conf_date_cst
     FROM
         asagdwpdx_prod.dbo.SimoxOrder2
     UNION ALL
     SELECT
         order_no, order_qty, order_status,
         last_conf_date_cst
     FROM
         asagdwpdx_prod.dbo.SimoxOrder3) G

JOIN
    pdx_sap_user.dbo.vw_po_header H ON G.order_no = h.ahag_number
JOIN
    pdx_sap_user.dbo.vw_po_item P ON H.po_number = P.po_number
JOIN
    pdx_sap_user.dbo.vw_mm_material M ON P.material = M.material
JOIN
    adi_user_maintained.dbo.SCM_PO_Employee_Name S ON P.po_number = S.po_number
JOIN
    pdx_sap_user.dbo.vw_kd_business_unit K ON M.business_unit_code = K.business_unit_code
JOIN
    adi_user_maintained.dbo.scm_po_error_tracking E ON E.po_number = P.po_number
WHERE
    M.business_segment_code NOT IN ('421', '420', '422', '424') --exclude adi golf
    AND E.report_source = 'gpsvssap_qty'
GROUP BY
    G.order_no, -- GROUP BY needed on aggregate function in SELECT
    G.order_qty,
    G.order_status,
    P.po_number,
    P.material,
    P.del_indicator,
    H.po_created_by,
    M.[description],
    M.department,
    S.team_member_name,
    K.business_unit_desc,
    G.last_conf_date_cst,
    H.po_type
HAVING
    G.order_qty <> SUM(P.po_ordered_quantity)
    AND G.order_status NOT IN ('60', '90') -- excluding GPS cancelled (90) & shipped (60) - do we need to exclude other status'?
    AND P.del_indicator <> 'L'
</code>```

答: You might want to look at 'MAX(P.comment)'. You cant find Max of string. Unless your comment is numeric</p>

Title: Error with Varchar to Numeric

Body:
For background: this works fine without the addition of the 'E' Table in production.

I am trying to execute the below query but am getting the error:

Msg 8114, Level 16, State 5, Line 10

  Error converting data type varchar to numeric.

The odd thing is that it executes fine on our test DB - not seeing anything trying to convert to numeric so a bit baffled. Not really sure what would cause that difference as I assume data types are the same in the test DB and the production DB - any ideas?

Thanks.

/* - adding po balance qty causes duplicates
   - adding stock category causes duplicates
   - added PO comments using MAX function to return only first comment - gets rid of duplicates*/

/* Using NEW employee table as of 11/2 */
SELECT
    S.team_member_name AS [ASSIGNED EMPLOYEE],  --Using new employee table - only on bus unit as of 11/2
    H.po_type AS [ PO TYPE],
    G.order_no AS [GPS PO #],
    P.po_number AS [SAP PO NUMBER],
    M.department AS [DEPARTMENT],
    G.order_qty AS [GPS QTY],
    SUM(P.po_ordered_quantity) AS [SAP QUANTITY],
    (SUM(P.po_ordered_quantity) - G.order_qty) AS [DIFFERENCE],
    G.last_conf_date_cst AS [LAST CONFIRMED DATE],
    K.business_unit_desc AS [BU],
    M.[description] AS [DESCRIPTION],
    P.material AS [MATERIAL],
    MAX(P.comment) AS [PO COMMENT],
    MIN(E.date) AS [FIRST SHOWN ON RPT]
FROM
    (SELECT
         order_no, order_qty, order_status,
         last_conf_date_cst
     FROM
         asagdwpdx_prod.dbo.SimoxOrder1
     UNION ALL
     SELECT
         order_no, order_qty, order_status,
         last_conf_date_cst
     FROM
         asagdwpdx_prod.dbo.SimoxOrder2
     UNION ALL
     SELECT
         order_no, order_qty, order_status,
         last_conf_date_cst
     FROM
         asagdwpdx_prod.dbo.SimoxOrder3) G

JOIN
    pdx_sap_user.dbo.vw_po_header H ON G.order_no = h.ahag_number
JOIN
    pdx_sap_user.dbo.vw_po_item P ON H.po_number = P.po_number
JOIN
    pdx_sap_user.dbo.vw_mm_material M ON P.material = M.material
JOIN
    adi_user_maintained.dbo.SCM_PO_Employee_Name S ON P.po_number = S.po_number
JOIN
    pdx_sap_user.dbo.vw_kd_business_unit K ON M.business_unit_code = K.business_unit_code
JOIN
    adi_user_maintained.dbo.scm_po_error_tracking E ON E.po_number = P.po_number
WHERE
    M.business_segment_code NOT IN ('421', '420', '422', '424') --exclude adi golf
    AND E.report_source = 'gpsvssap_qty'
GROUP BY
    G.order_no, -- GROUP BY needed on aggregate function in SELECT
    G.order_qty,
    G.order_status,
    P.po_number,
    P.material,
    P.del_indicator,
    H.po_created_by,
    M.[description],
    M.department,
    S.team_member_name,
    K.business_unit_desc,
    G.last_conf_date_cst,
    H.po_type
HAVING
    G.order_qty <> SUM(P.po_ordered_quantity)
    AND G.order_status NOT IN ('60', '90') -- excluding GPS cancelled (90) & shipped (60) - do we need to exclude other status'?
    AND P.del_indicator <> 'L'


问:
how to display parent categories depended in drop down chlid categories in php mysql
I'm trying  to display user select sub category from drop down and display his parent categories , but my code showing display till second level parent categories im new in php  help me please thank you

Display All categories

```<code>    <?php

$result = mysqli_query($mysqli, "SELECT category.*, cat.name as parentName FROM category left join category as cat on category.parentId = cat.id  ORDER BY id ASC"); // using mysqli_query instead

    while($res = mysqli_fetch_array($result)) {
        echo "<tr>";
         echo "<td>".$res['id']."</td>";
        echo "<td>".$res['name']."</td>";
        echo "<td>".$res['description']."</td>";

        echo "<td>".$res['parentId']."</td>";
        echo "<td>".$res['parentName']."</td>";

        echo "<td><a href=\"update.php?id=$res[id]&parentId=$res[parentId]\">Edit</a> | <a href=\"action/delete.php?id=$res[id]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";
    }
    ?>
</code>```

i get parentid and id and send it into update page,

Update-category.php

```<code>        <form action="action/update-category.php" method="post" class="form-horizontal">
    <fieldset>
    <?php
    include_once './action/connection.php';
    ?>
    <?php
    $id = $_GET['id']; //
    $parentId = $_GET['parentId'];
    $sql  = "SELECT * FROM category WHERE id = $id";

    $result = mysqli_query($mysqli, $sql);
    $mainCategories = array();
    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            $mainCategories[] = $row;
        }
    } else {
        echo "0 results";
    }
    // echo "<b>Thank you! Record UPDATED Successfully!";
      ?>
    <!-- Form Name -->
    <legend>Edit Product</legend>
    <div class="col-md-12">
        <div class="form-group" id="category_main">
          <label class="col-md-6 control-label" for="product_categorie">CATEGORY</label>
          <div class="col-md-6">
          <select for="category_main" onchange="loadChildCategories(this);" id="" name="mainCategory_1" class="form-control category_main">
            <option> Please select parent category</option>
            <?php
        foreach ($mainCategories AS $eachCategory) {
        echo "<option value='".$eachCategory['parentId']."'>".$eachCategory['name']."</option>";
                }

            ?>
             </select>
          </div>
        </div>
    </div>
</code>```

Updatecategoryby Id

```<code>    <?php

include_once 'connection.php';
if(!empty($_POST["parentId"])) {
$id = $_POST['parentId'];
$sql  = "SELECT * FROM category WHERE id='".$id."' Or parentId = '0'";
$result = mysqli_query($mysqli, $sql);
$childCategories = array();
$response = array();
if (mysqli_num_rows($result) > 0) {
    $response['hasChildCategories'] = true;
    $htmlChildCategories = '<div class="form-group" id="category_'.$id.'">
      <label class="col-md-6 control-label" for="product_categorie">CATEGORY</label>
      <div class="col-md-6">
      <select for="category_'.$id.'" onchange="loadChildCategories(this)" name="mainCategory_'.$id.'" class="form-control category_main">
        <option value="'.$id.'"> Select parent category</option>';

    // output data of each rowa
    while($row = mysqli_fetch_assoc($result)) {
        $childCategories[] = $row;
        $htmlChildCategories .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
    }
    $htmlChildCategories .= '</select></div></div>';
    $response['html'] = $htmlChildCategories;
}
else
{
    $response['hasChildCategories'] = false;
    $response['html'] = '';
}

echo json_encode($response);

}
?>
</code>```

fullfull code

答:
Actually problem is with your Update-category.php code where you select only parent category of selected category. You have to write recursive function to fetch all above parent categories.

if you provided definition of loadChildCategories() then its easy to answer you. but still you can check following URL, It will helpful for you.

How can I recursively get the IDs of all the parent elements in a multidimensional array?

Thanks

Body:
I'm trying  to display user select sub category from drop down and display his parent categories , but my code showing display till second level parent categories im new in php  help me please thank you

Display All categories

    <?php

$result = mysqli_query($mysqli, "SELECT category.*, cat.name as parentName FROM category left join category as cat on category.parentId = cat.id  ORDER BY id ASC"); // using mysqli_query instead

    while($res = mysqli_fetch_array($result)) {
        echo "
";
         echo "".$res['id']."	";
        echo "".$res['name']."	";
        echo "".$res['description']."	";

        echo "".$res['parentId']."	";
        echo "".$res['parentName']."	";

        echo "Edit | Delete	";
    }
    ?>

i get parentid and id and send it into update page,

Update-category.php

        <form action="action/update-category.php" method="post" class="form-horizontal">
    <fieldset>
    <?php
    include_once './action/connection.php';
    ?>
    <?php
    $id = $_GET['id']; //
    $parentId = $_GET['parentId'];
    $sql  = "SELECT * FROM category WHERE id = $id";

    $result = mysqli_query($mysqli, $sql);
    $mainCategories = array();
    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            $mainCategories[] = $row;
        }
    } else {
        echo "0 results";
    }
    // echo "Thank you! Record UPDATED Successfully!";
      ?>

    <legend>Edit Product</legend>

          CATEGORY

          <select for="category_main" onchange="loadChildCategories(this);" id="" name="mainCategory_1" class="form-control category_main">
            <option> Please select parent category</option>
            <?php
        foreach ($mainCategories AS $eachCategory) {
        echo "<option value='".$eachCategory['parentId']."'>".$eachCategory['name']."</option>";
                }

            ?>
             </select>

Updatecategoryby Id

    <?php

include_once 'connection.php';
if(!empty($_POST["parentId"])) {
$id = $_POST['parentId'];
$sql  = "SELECT * FROM category WHERE id='".$id."' Or parentId = '0'";
$result = mysqli_query($mysqli, $sql);
$childCategories = array();
$response = array();
if (mysqli_num_rows($result) > 0) {
    $response['hasChildCategories'] = true;
    $htmlChildCategories = '

      CATEGORY

      <select for="category_'.$id.'" onchange="loadChildCategories(this)" name="mainCategory_'.$id.'" class="form-control category_main">
        <option value="'.$id.'"> Select parent category</option>';

    // output data of each rowa
    while($row = mysqli_fetch_assoc($result)) {
        $childCategories[] = $row;
        $htmlChildCategories .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
    }
    $htmlChildCategories .= '</select>

';
    $response['html'] = $htmlChildCategories;
}
else
{
    $response['hasChildCategories'] = false;
    $response['html'] = '';
}

echo json_encode($response);

}
?>

fullfull code


问:
Selenium - Basic Authentication via url
In my Selenium-Test (with chromedriver-2.24) I'm trying to access my webpage via basic authentication with the following statement:

```<code>WebDriver driver  = ...;
driver.get("http://admin:admin@localhost:8080/project/");
</code>```

But Google Chrome gives me the following warning in the console:

[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass@host/) are blocked. See https://www.chromestatus.com/feature/5669008342777856 for more details.

In the tagged link is mentioned that the support was dropped:

Drop support for embedded credentials in subresource requests. (removed)

My question now is, is there an other way to basic-authenticate from Selenium?

NOTE: this has not helped: How to Handle HTTP Basic Auth headers in Selenium Webdriver using Java ?

答:
Florent B.'s approach of calling .get on the URL twice worked for me with a slight modification.  In JS:

```<code>driver
        .get('http://admin:admin@localhost:8080')
        .then( () => driver.get('http://localhost:8080') )
</code>```

working on google chrome 62.0.3202.94 with ChromeDriver 2.33.506092 and the approach seems compatible with firefox 56.0.2 with geckodriver 0.19.1, and phantomjs 2.1.1 all under Debian linux 9.

What I believe is happening is the first call sets up the Authorization header sent by the browser.  The second call removes the credentials from the URL and the credentials no longer are applied to subresources. The then synchronizes the two requests ensuring order.

Title: Selenium - Basic Authentication via url

Body:
In my Selenium-Test (with chromedriver-2.24) I'm trying to access my webpage via basic authentication with the following statement:

WebDriver driver  = ...;
driver.get("http://admin:admin@localhost:8080/project/");

But Google Chrome gives me the following warning in the console:

[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass@host/) are blocked. See https://www.chromestatus.com/feature/5669008342777856 for more details.

In the tagged link is mentioned that the support was dropped:

Drop support for embedded credentials in subresource requests. (removed)

My question now is, is there an other way to basic-authenticate from Selenium?

NOTE: this has not helped: How to Handle HTTP Basic Auth headers in Selenium Webdriver using Java ?

Body:
Florent B.'s approach of calling .get on the URL twice worked for me with a slight modification.  In JS:

driver
        .get('http://admin:admin@localhost:8080')
        .then( () => driver.get('http://localhost:8080') )

working on google chrome 62.0.3202.94 with ChromeDriver 2.33.506092 and the approach seems compatible with firefox 56.0.2 with geckodriver 0.19.1, and phantomjs 2.1.1 all under Debian linux 9.

What I believe is happening is the first call sets up the Authorization header sent by the browser.  The second call removes the credentials from the URL and the credentials no longer are applied to subresources. The then synchronizes the two requests ensuring order.


问:
Java coin flip with user entered variables
I am trying to create a java program which accepts a user entered number and then flips a coin that many times and then displays how many heads or tails have been flipped so far.
My problem comes when I can't figure out how to make the program flip the coin the number of times the user says to, any help?</p>

```<code>package E1;
import java.util.Scanner;
public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("How many coins should be tossed?");
        input.nextInt();
        if (Math.random() < 0.5) {
            System.out.println("Heads");
            hCount++;
        } else {
            System.out.println("Tails");
            tCount++;
        }
    }
}
</code>```

答:
I suggest set package name in lower case as it's a wide and good practice.

Look at this, it could be what you want:

```<code>package e1;

import java.util.Scanner;

public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.print("How many coins should be tossed? ");
        int coinsCount = input.nextInt();
        for (int i=0; i < coinsCount; i++) {
            if (Math.random() < 0.5) {
                System.out.println("Heads");
                hCount++;
            } else {
                System.out.println("Tails");
                tCount++;
            }
        }
        System.out.println("Heads: "+hCount+", Tails: "+tCount);
    }
}
</code>```

Body:
I am trying to create a java program which accepts a user entered number and then flips a coin that many times and then displays how many heads or tails have been flipped so far.
My problem comes when I can't figure out how to make the program flip the coin the number of times the user says to, any help?

package E1;
import java.util.Scanner;
public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("How many coins should be tossed?");
        input.nextInt();
        if (Math.random() < 0.5) {
            System.out.println("Heads");
            hCount++;
        } else {
            System.out.println("Tails");
            tCount++;
        }
    }
}

Body:
I suggest set package name in lower case as it's a wide and good practice.

Look at this, it could be what you want:

package e1;

import java.util.Scanner;

public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.print("How many coins should be tossed? ");
        int coinsCount = input.nextInt();
        for (int i=0; i < coinsCount; i++) {
            if (Math.random() < 0.5) {
                System.out.println("Heads");
                hCount++;
            } else {
                System.out.println("Tails");
                tCount++;
            }
        }
        System.out.println("Heads: "+hCount+", Tails: "+tCount);
    }
}


问:
Question Mark in a Box when using println
When running this in a command prompt,

```<code>System.out.println(Num + " is prime!");
System.out.println("Press N to put in another number or S to stop");
</code>```

Where Num is an int

This is what comes out:

Is there any way to counter it or should I just deal with it?

答:
```<code>System.out.println(String.valueOf(Num) + " is prime!");
</code>```

Edit: Adding more information to replete the mystery here.

java.lang.String.valueOf will correctly parse your Number where as simply adding a Number with a String will vary between compilers.

See  more here Concat an integer to a String - use String literal or primitive from performance and memory point of view?

Body:
When running this in a command prompt,

System.out.println(Num + " is prime!");
System.out.println("Press N to put in another number or S to stop");

Where Num is an int

This is what comes out:

Is there any way to counter it or should I just deal with it?

Body:
System.out.println(String.valueOf(Num) + " is prime!");

Edit: Adding more information to replete the mystery here.

java.lang.String.valueOf will correctly parse your Number where as simply adding a Number with a String will vary between compilers.

See  more here Concat an integer to a String - use String literal or primitive from performance and memory point of view?


答:
I assume you have a simple table which structure as below show:

```<code>+--------+------+
| name   | dep  |
+--------+------+
| frank  | IT   |
| jack   | IT   |
| Sissel | FA   |
| Li     | FA   |
| Mok    | PM   |
+--------+------+
</code>```

You have three department maybe more, you can simple use count to fetch number of employee for all departments. and if you use group by dep you will get each number by you expect .

```<code>SELECT dep, count(*) FROM user_table GROUP BY dep;
</code>```

And then you got:

```<code>+------+----------+
| dep  | count(*) |
+------+----------+
| FA   |        2 |
| IT   |        2 |
| PM   |        1 |
+------+----------+
</code>```

Hope, that's all your need~

Title: MySQL query to print data from two tables

Body:
I assume you have a simple table which structure as below show:

+--------+------+
| name   | dep  |
+--------+------+
| frank  | IT   |
| jack   | IT   |
| Sissel | FA   |
| Li     | FA   |
| Mok    | PM   |
+--------+------+

You have three department maybe more, you can simple use count to fetch number of employee for all departments. and if you use group by dep you will get each number by you expect .

SELECT dep, count(*) FROM user_table GROUP BY dep;

And then you got:

+------+----------+
| dep  | count(*) |
+------+----------+
| FA   |        2 |
| IT   |        2 |
| PM   |        1 |
+------+----------+

Hope, that's all your need~


问:
VirtualHost problem with passenger (mod_rails)
I'm at my wit's end here with virtual hosting. I'm trying to install redmine and it works with the webrick test server, but when I tried to use passenger (mod_rails) to host and go to the address I specified when in the virtualhost part of my apache config file nothing happens. Here is the relavent section of /etc/httpd/conf/httpd.conf where I try to set up the virtual host:

```<code><VirtualHost *:80>

SetEnv RAILS_ENV production
ServerName redmine.MYSITE.com:80
DocumentRoot /opt/redmine-1.0.5/public/
<Directory /opt/redmine-1.0.5/public/>
    Options -MultiViews
    Allow from all
    AllowOverride none
</Directory>
</code>```

However, when I got to redmine.MYSITE.com:80 nothing happens, I just get our normal home page. I have no idea what the problem is, any help our guidance would be greatly appreciated. If you need any other information, please tell me and I'll provide it.

答:
Your VirtualHost *:80 directive must be matched by a corresponding NameVirtualHost *:80 earlier in your config.

You can ask apache what it makes of your vhosts with the -S switch. Of course, the name of your server binary depends somewhat on how it was installed and on what OS/Distro.

Body:
I'm at my wit's end here with virtual hosting. I'm trying to install redmine and it works with the webrick test server, but when I tried to use passenger (mod_rails) to host and go to the address I specified when in the virtualhost part of my apache config file nothing happens. Here is the relavent section of /etc/httpd/conf/httpd.conf where I try to set up the virtual host:

<VirtualHost *:80>

SetEnv RAILS_ENV production
ServerName redmine.MYSITE.com:80
DocumentRoot /opt/redmine-1.0.5/public/
<Directory /opt/redmine-1.0.5/public/>
    Options -MultiViews
    Allow from all
    AllowOverride none
</Directory>

However, when I got to redmine.MYSITE.com:80 nothing happens, I just get our normal home page. I have no idea what the problem is, any help our guidance would be greatly appreciated. If you need any other information, please tell me and I'll provide it.


问:
Trying to temporarily convert entire string to lowercase and remove spaces
So my program is a palindrome checker function using only the string library and C++ sting objects. In order to check if the string input by the user is a palindrome, I need to convert the entire string to lowercase and remove the spaces to check if the string and its reverse are equal. I've tried looking up solutions but I've only found answers using different libraries and creating new functions. This is the code I have so far.</p>

```<code>#include <iostream>
#include <string>

using namespace std;

string checkPalin();

int main()
{
    string result = checkPalin();

    cout << "The palindromes are: " << result;
}

string checkPalin()
{
    int stringNum, time = 0;
    string list;
    string str1;
    string reverse;
    cout << "How many strings? " << endl;
    cin >> stringNum;
    cout << "Enter the strings: " << endl;

    do
    {
        getline(cin, str1);

        int size = str1.length();
        for (int i = size - 1; i >= 0; i--)
            reverse += str1[i];

        if ((str1.compare(reverse)) == 0)
        {
            list += str1;
        }

        time++;
    } while (time <= stringNum);

    return list;
}
</code>```

答:
How about something like this

```<code>std::string inputString = "WhatEver", cleanString;
for (char & c : inputString)
    if (c != ' ')
        cleanString += std::tolower(static_cast<unsigned char>(c));
</code>```

std::tolower is undefined if the char value is not representable as unsigned char, hence the cast.

Body:
So my program is a palindrome checker function using only the string library and C++ sting objects. In order to check if the string input by the user is a palindrome, I need to convert the entire string to lowercase and remove the spaces to check if the string and its reverse are equal. I've tried looking up solutions but I've only found answers using different libraries and creating new functions. This is the code I have so far.

#include <iostream>
#include <string>

using namespace std;

string checkPalin();

int main()
{
    string result = checkPalin();

    cout << "The palindromes are: " << result;
}

string checkPalin()
{
    int stringNum, time = 0;
    string list;
    string str1;
    string reverse;
    cout << "How many strings? " << endl;
    cin >> stringNum;
    cout << "Enter the strings: " << endl;

    do
    {
        getline(cin, str1);

        int size = str1.length();
        for (int i = size - 1; i >= 0; i--)
            reverse += str1[i];

        if ((str1.compare(reverse)) == 0)
        {
            list += str1;
        }

        time++;
    } while (time <= stringNum);

    return list;
}

Body:
How about something like this

std::string inputString = "WhatEver", cleanString;
for (char & c : inputString)
    if (c != ' ')
        cleanString += std::tolower(static_cast<unsigned char>(c));

std::tolower is undefined if the char value is not representable as unsigned char, hence the cast.


问:
How can I get a button in bootstrap 4 to float right without leaving the container it's in?
I am trying to create a container in bootstrap with a button on the bottom floating on the right. Unfortunately, the button is leaving the div. Why is this happening and how can I prevent this? Here is a copy of the HTML

```<code><body>
  <div class="container">
    <p>
      ...
    </p>
    <button type="button" class="btn btn-primary float-right">Primary</button>
  </div>
</body>
</code>```

CSS

```<code>.container {
  border: 1px solid black;
}
</code>```

and a plunker: https://plnkr.co/edit/9DUn1CUj0g6NPhEmqeB9?p=preview

答:
This seems to be a normal problem when trying to wrap the button tag. Using a row inside the container can solve this problem. Here you can see i am using col-md-12 which is insite the row ,but you can change it depending on your design.

// Code goes here```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Styles go here */

.container {
  border: 1px solid black;
}</code>```

<!DOCTYPE html>

    <link data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />

    <link rel="stylesheet" href="style.css" />

Measured fer yer chains piracy marooned schooner snow yo-ho-ho parley furl six pounders lanyard. Snow brig Sink me rum American Main reef sails bucko pirate crow's nest Sail ho. American Main coxswain lee heave down tender brig schooner gibbet piracy rum.

          <button type="button" class="btn btn-primary float-right">Primary</button>

```

Body:
I am trying to create a container in bootstrap with a button on the bottom floating on the right. Unfortunately, the button is leaving the div. Why is this happening and how can I prevent this? Here is a copy of the HTML

      ...

    <button type="button" class="btn btn-primary float-right">Primary</button>

CSS

.container {
  border: 1px solid black;
}

and a plunker: https://plnkr.co/edit/9DUn1CUj0g6NPhEmqeB9?p=preview

Body:
This seems to be a normal problem when trying to wrap the button tag. Using a row inside the container can solve this problem. Here you can see i am using col-md-12 which is insite the row ,but you can change it depending on your design.

// Code goes here

/* Styles go here */

.container {
  border: 1px solid black;
}

<!DOCTYPE html>
<html>

  <head>
    <link data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
    <script data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />

  </head>

  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <p>Measured fer yer chains piracy marooned schooner snow yo-ho-ho parley furl six pounders lanyard. Snow brig Sink me rum American Main reef sails bucko pirate crow's nest Sail ho. American Main coxswain lee heave down tender brig schooner gibbet piracy rum.</p>
          <button type="button" class="btn btn-primary float-right">Primary</button>
        </div>
      </div>
    </div>
  </body>

</html>


问:
Is there a tool to check database integrity in Django?
The MySQL database powering our Django site has developed some integrity problems; e.g. foreign keys that refer to nonexistent rows. I won't go into how we got into this mess, but I'm now looking at how to fix it.

Basically, I'm looking for a script that scans all models in the Django site, and checks whether all foreign keys and other constraints are correct. Hopefully, the number of problems will be small enough so they can be fixed by hand.

I could code this up myself but I'm hoping that somebody here has a better idea.

I found django-check-constraints but it doesn't quite fit the bill: right now, I don't need something to prevent these problems, but to find them so they can be fixed manually before taking other steps.

Other constraints:

Django 1.1.1 and upgrading has been determined to break things

MySQL 5.0.51 (Debian Lenny), currently with MyISAM tables

Python 2.5, might be upgradable but I'd rather not right now

(Later, we will convert to InnoDB for proper transaction support, and maybe foreign key constraints on the database level, to prevent similar problems in the future. But that's not the topic of this question.)

答:
I whipped up something myself. The management script below should be saved in myapp/management/commands/checkdb.py. Make sure that intermediate directories have an __init__.py file.

Usage: ./manage.py checkdb for a full check; use --exclude app.Model or -e app.Model to exclude the model Model in the app app.

from django.core.management.base import BaseCommand, CommandError
from django.core.management.base import NoArgsCommand
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from optparse import make_option
from lib.progress import with_progress_meter

def model_name(model):
    return '%s.%s' % (model._meta.app_label, model._meta.object_name)

class Command(BaseCommand):
    args = '[-e|--exclude app_name.ModelName]'
    help = 'Checks constraints in the database and reports violations on stdout'

    option_list = NoArgsCommand.option_list + (
        make_option('-e', '--exclude', action='append', type='string', dest='exclude'),
    )

    def handle(self, *args, **options):
        # TODO once we're on Django 1.2, write to self.stdout and self.stderr instead of plain print

        exclude = options.get('exclude', None) or []

        failed_instance_count = 0
        failed_model_count = 0
        for app in models.get_apps():
            for model in models.get_models(app):
                if model_name(model) in exclude:
                    print 'Skipping model %s' % model_name(model)
                    continue
                fail_count = self.check_model(app, model)
                if fail_count > 0:
                    failed_model_count += 1
                    failed_instance_count += fail_count
        print 'Detected %d errors in %d models' % (failed_instance_count, failed_model_count)

    def check_model(self, app, model):
        meta = model._meta
        if meta.proxy:
            print 'WARNING: proxy models not currently supported; ignored'
            return

        # Define all the checks we can do; they return True if they are ok,
        # False if not (and print a message to stdout)
        def check_foreign_key(model, field):
            foreign_model = field.related.parent_model
            def check_instance(instance):
                try:
                    # name: name of the attribute containing the model instance (e.g. 'user')
                    # attname: name of the attribute containing the id (e.g. 'user_id')
                    getattr(instance, field.name)
                    return True
                except ObjectDoesNotExist:
                    print '%s with pk %s refers via field %s to nonexistent %s with pk %s' % \
                        (model_name(model), str(instance.pk), field.name, model_name(foreign_model), getattr(instance, field.attname))
            return check_instance

        # Make a list of checks to run on each model instance
        checks = []
        for field in meta.local_fields + meta.local_many_to_many + meta.virtual_fields:
            if isinstance(field, models.ForeignKey):
                checks.append(check_foreign_key(model, field))

        # Run all checks
        fail_count = 0
        if checks:
            for instance in with_progress_meter(model.objects.all(), model.objects.count(), 'Checking model %s ...' % model_name(model)):
                for check in checks:
                    if not check(instance):
                        fail_count += 1
        return fail_count
```

I'm making this a community wiki because I welcome any and all improvements to my code!

Body:
I whipped up something myself. The management script below should be saved in myapp/management/commands/checkdb.py. Make sure that intermediate directories have an __init__.py file.

Usage: ./manage.py checkdb for a full check; use --exclude app.Model or -e app.Model to exclude the model Model in the app app.

from django.core.management.base import BaseCommand, CommandError
from django.core.management.base import NoArgsCommand
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from optparse import make_option
from lib.progress import with_progress_meter

def model_name(model):
    return '%s.%s' % (model._meta.app_label, model._meta.object_name)

class Command(BaseCommand):
    args = '[-e|--exclude app_name.ModelName]'
    help = 'Checks constraints in the database and reports violations on stdout'

    option_list = NoArgsCommand.option_list + (
        make_option('-e', '--exclude', action='append', type='string', dest='exclude'),
    )

    def handle(self, *args, **options):
        # TODO once we're on Django 1.2, write to self.stdout and self.stderr instead of plain print

        exclude = options.get('exclude', None) or []

        failed_instance_count = 0
        failed_model_count = 0
        for app in models.get_apps():
            for model in models.get_models(app):
                if model_name(model) in exclude:
                    print 'Skipping model %s' % model_name(model)
                    continue
                fail_count = self.check_model(app, model)
                if fail_count > 0:
                    failed_model_count += 1
                    failed_instance_count += fail_count
        print 'Detected %d errors in %d models' % (failed_instance_count, failed_model_count)

    def check_model(self, app, model):
        meta = model._meta
        if meta.proxy:
            print 'WARNING: proxy models not currently supported; ignored'
            return

        # Define all the checks we can do; they return True if they are ok,
        # False if not (and print a message to stdout)
        def check_foreign_key(model, field):
            foreign_model = field.related.parent_model
            def check_instance(instance):
                try:
                    # name: name of the attribute containing the model instance (e.g. 'user')
                    # attname: name of the attribute containing the id (e.g. 'user_id')
                    getattr(instance, field.name)
                    return True
                except ObjectDoesNotExist:
                    print '%s with pk %s refers via field %s to nonexistent %s with pk %s' % \
                        (model_name(model), str(instance.pk), field.name, model_name(foreign_model), getattr(instance, field.attname))
            return check_instance

        # Make a list of checks to run on each model instance
        checks = []
        for field in meta.local_fields + meta.local_many_to_many + meta.virtual_fields:
            if isinstance(field, models.ForeignKey):
                checks.append(check_foreign_key(model, field))

        # Run all checks
        fail_count = 0
        if checks:
            for instance in with_progress_meter(model.objects.all(), model.objects.count(), 'Checking model %s ...' % model_name(model)):
                for check in checks:
                    if not check(instance):
                        fail_count += 1
        return fail_count

I'm making this a community wiki because I welcome any and all improvements to my code!


问:
Typescript: Type 'Audience' is not assignable to type 'boolean'
The problem:

```<code>.filter(audience => audience)
</code>```

I'm using VSCode and I know why it's throwing this error as it's expecting a boolean and I'm returning an object, but this is valid Javascript as I'm returning a truthy value and so a reference will be coerced to true. Can I change something in the configuration to make it work? I already made it work with:

```<code>.filter(audience => Boolean(audience))
</code>```

But I'd rather avoid that.

答:
I'm surprised you are seeing this error. But if you need a boolean, truthy/falsy values are commonly converted to booleans like this: </p>

```<code>.filter(audience => !!audience)
</code>```

Body:
The problem:

.filter(audience => audience)

I'm using VSCode and I know why it's throwing this error as it's expecting a boolean and I'm returning an object, but this is valid Javascript as I'm returning a truthy value and so a reference will be coerced to true. Can I change something in the configuration to make it work? I already made it work with:

.filter(audience => Boolean(audience))

But I'd rather avoid that.

Body:
I'm surprised you are seeing this error. But if you need a boolean, truthy/falsy values are commonly converted to booleans like this:

.filter(audience => !!audience)


问:
Is there a technical reason why the implementation isn't just impl Foo<T>?
I just learned that structs using generics are declared as struct Foo<T>, and that the implementation is declared as impl<T> Foo<T>. The book explains the discrepancy in the following way:

Note that we have to declare T just after impl in order to use T in the type Point<T>. Declaring T as a generic type after the impl is how Rust knows the type in the angle brackets in Point is a generic type rather than a concrete type.

Again, I'm a newbie, but couldn't the same argument be made for having to declare struct<T> Foo<T> (and possibly even fn<T> foo<T>(bar: T))?

答:
```<code>impl Foo<T> { ... }
</code>```

Is T a type parameter, or an actual type named T?  If you answered the second, then you've thrown generics out the window entirely: it would be impossible to implement functionality for a generic set of types.  If you answered the first, then how do you propose users do this:

```<code>impl Foo<T> { /* generic stuff */ }
impl Foo<i32> { /* i32-specific stuff */ }
impl Foo<u32> { /* u32-specific stuff */ }
</code>```

That would just be three impl blocks with type parameters named T, i32, and u32 respectively.

You might say "well, just decide from context".  Now, in order to work out what's going on, a user has to check not only the rest of the module, but all imported symbols and anything in the standard library's prelude in order to decide if a type is a parameter or not.  Rust abhors this kind of ambiguity.

It is far, far simpler for the compiler and the reader to just be specific about what is and is not a parameter.

You don't have to do this with struct because the thing in the brackets cannot possibly be anything other than a type parameter declaration.

Body:
impl Foo<T> { ... }

Is T a type parameter, or an actual type named T?  If you answered the second, then you've thrown generics out the window entirely: it would be impossible to implement functionality for a generic set of types.  If you answered the first, then how do you propose users do this:

impl Foo<T> { /* generic stuff */ }
impl Foo<i32> { /* i32-specific stuff */ }
impl Foo<u32> { /* u32-specific stuff */ }

That would just be three impl blocks with type parameters named T, i32, and u32 respectively.

You might say "well, just decide from context".  Now, in order to work out what's going on, a user has to check not only the rest of the module, but all imported symbols and anything in the standard library's prelude in order to decide if a type is a parameter or not.  Rust abhors this kind of ambiguity.

It is far, far simpler for the compiler and the reader to just be specific about what is and is not a parameter.

You don't have to do this with struct because the thing in the brackets cannot possibly be anything other than a type parameter declaration.


问:
Applying transformation to every item in Single<List<T>>
I have a val singleList: Single<List<EntityItem>> = ...

I also have a custom transformer to convert ItemEntity to Item
(doing either transformer::fromEntity or transformer.fromEntity(entity))

How would I use RxJava operators to run this transformation on each EntityItem in singleList so that Single<List<EntityItem>> becomes Single<List<Item>>

答:
You can use .map { ... } on Single<T> to transform the value it holds, and inside map the items of the list:

```<code>val result = singleList.map { it.map(transformer::fromEntity) }
</code>```

Body:
You can use .map { ... } on Single<T> to transform the value it holds, and inside map the items of the list:

val result = singleList.map { it.map(transformer::fromEntity) }


问:
Formulas not working in excel when i put 58+2 instead of 60?
I want to put 58+2 instead of 60 in Microsoft Excel cells. But, when I do that the cell is not counted for summation or other functions. How do I put 58+2 in a cell and get results?
If I put =58+2 inside the cell, due to AUTOSUM it automatically turns to 60
enter image description here

答:
For any cell you want to calculate instead of hard-code, add an equals sign at the beginning

=58+2

will be evaluated by Excel to be a function rather than text and will evaluate it.


问:
How do I check whether a variable is declared in Python?
How do I check whether a variable is declared, without using the try, except statement?

答:
The dir() command gives a list of all the variables in your global namespace. If your variable is x_val, use

```<code>'x_val' in dir()
</code>```

Body:
The dir() command gives a list of all the variables in your global namespace. If your variable is x_val, use

'x_val' in dir()


问:
what is causing this AssociationTypeMismatch in my controllers?
I have two controllers - ItemsController and TradesController. I'm building a @trade inside the ItemsController #show action, which is sent to the TradesController #create action with a form.

```<code>class ItemsController < ApplicationController
 def show
  @item = Item.friendly.find(params[:id])
  @trade = current_user.requested_trades.build
  @approved_trades = @item.trades
  respond_to do |format|
   format.html
   format.json { render :json => @items.to_json(:methods => [:image_url]) }
  end
end

class TradesController < ApplicationController
 def create
  @trade = current_user.requested_trades.build(trade_params)
  respond_to do |format|
   if @trade.save
    format.html { redirect_to @trade, notice: "Your request for trade has been submitted. You will be notified once it is approved or denied." }
    format.json { render :index, status: :created, location: @trade }
   else
    format.html { redirect_to @trade, notice: "Pick another amount" }
   end
  end
 end

 private
 def trade_params
  params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item, :collateral_item, :shares)
 end
end
</code>```

And then here's my Trade model

```<code>class Trade < ActiveRecord::Base
 belongs_to :trade_requester, class_name: "User"
 belongs_to :trade_recipient, class_name: "User"
 belongs_to :wanted_item, class_name: "Item"
 belongs_to :collateral_item, class_name: "Item"
end
</code>```

Here's the form in my Item's show view:

```<code><%= form_for(@trade) do |f| %>
 <%= f.hidden_field :wanted_item, value: @item.id %>
 <div class="field">
  <%= f.text_field :shares, placeholder: "Pick a number between 1 and #{@item.shares}" %>
  <%= f.submit "Trade", class: "button minty-button wide-button" %>
 </div>
<% end %>
</code>```

The above code for the ItemsController posts to the TradesController create action, but I'm getting an error that says ActiveRecord::AssociationTypeMismatch in TradesController#createItem(#70095717466760) expected, got String(#70095657672800)

Why is that expecting an Item? It seems that if @trade creation results in error, then it should redirect to @trade.

答:
The quick solution is to change your hidden field from :wanted_item to :wanted_item_id:

```<code>  <%= form_for(@trade) do |f| %>
    <%= f.hidden_field :wanted_item_id, value: @item.id %>
    <div class="field">
      <%= f.text_field :shares, placeholder: "Pick a number between 1 and #{@item.shares}" %>
      <%= f.submit "Trade", class: "button minty-button wide-button" %>
    </div>
  <% end %>
</code>```

Also, make sure your trade_params method permits wanted_item_id:

```<code>def trade_params
  params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item_id, :collateral_item_id, :shares)
end
</code>```

You may have a similar issue with :collateral_item in another form.

Body:
I have two controllers - ItemsController and TradesController. I'm building a @trade inside the ItemsController #show action, which is sent to the TradesController #create action with a form.

class ItemsController < ApplicationController
 def show
  @item = Item.friendly.find(params[:id])
  @trade = current_user.requested_trades.build
  @approved_trades = @item.trades
  respond_to do |format|
   format.html
   format.json { render :json => @items.to_json(:methods => [:image_url]) }
  end
end

class TradesController < ApplicationController
 def create
  @trade = current_user.requested_trades.build(trade_params)
  respond_to do |format|
   if @trade.save
    format.html { redirect_to @trade, notice: "Your request for trade has been submitted. You will be notified once it is approved or denied." }
    format.json { render :index, status: :created, location: @trade }
   else
    format.html { redirect_to @trade, notice: "Pick another amount" }
   end
  end
 end

 private
 def trade_params
  params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item, :collateral_item, :shares)
 end
end

And then here's my Trade model

class Trade < ActiveRecord::Base
 belongs_to :trade_requester, class_name: "User"
 belongs_to :trade_recipient, class_name: "User"
 belongs_to :wanted_item, class_name: "Item"
 belongs_to :collateral_item, class_name: "Item"
end

Here's the form in my Item's show view:

<%= form_for(@trade) do |f| %>
 <%= f.hidden_field :wanted_item, value: @item.id %>

  <%= f.text_field :shares, placeholder: "Pick a number between 1 and #{@item.shares}" %>
  <%= f.submit "Trade", class: "button minty-button wide-button" %>

<% end %>

The above code for the ItemsController posts to the TradesController create action, but I'm getting an error that says ActiveRecord::AssociationTypeMismatch in TradesController#createItem(#70095717466760) expected, got String(#70095657672800)

Why is that expecting an Item? It seems that if @trade creation results in error, then it should redirect to @trade.

Body:
The quick solution is to change your hidden field from :wanted_item to :wanted_item_id:

  <%= form_for(@trade) do |f| %>
    <%= f.hidden_field :wanted_item_id, value: @item.id %>
    <div class="field">
      <%= f.text_field :shares, placeholder: "Pick a number between 1 and #{@item.shares}" %>
      <%= f.submit "Trade", class: "button minty-button wide-button" %>
    </div>
  <% end %>

Also, make sure your trade_params method permits wanted_item_id:

def trade_params
  params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item_id, :collateral_item_id, :shares)
end

You may have a similar issue with :collateral_item in another form.


问:
How do I install packages/modules for Python 3.6?
I'm super new to Python, and can't figure out how to install packages or modules. I know you can use Pip to easily install them, but none of the commands I've found have done anything but give me errors. Any help would be appreciated.</p>

答: Have you tried pip install? A good thing to remember is pip usually requires sudo on linux distributions. Also, for some modules it's easier to use conda, since it takes care of dependencies. It this is the best general information I can give. If you told me some packages you've tried to install, that would help a lot!