问:
How to make Kotlin getter give me actual data?
As I know, Kotlin generates getters when you invoke a class for the first time. So, for example, following code will always give me the same answer:

```<code>val instance
    get() = getFromDb() ?: MyData()
</code>```

If there is a non-null MyData instance then it will give this instance all the time and if result from DB is null, I will always get new instance of MyData. I could be wrong here, so correct me if I am.

The question is how can I update the value of the getter? I.e. most of the time I want to get the data from database but after logout I want to request data from DB or just give me a new instance once again.

答:
If I understand the situation correctly:

If the field is not null you want to get the value

If it is null you want to get it from the Database

If it does not exist in Database you want to create a new instance

And all of those instances should be saved to instance variable. If this is what you want you can do something like this:

```<code>var instance
    get() = field ?: getFromDb().also { field = it } ?: MyData().also { field = it }
</code>```

Please noice the var instead of val

Body:
As I know, Kotlin generates getters when you invoke a class for the first time. So, for example, following code will always give me the same answer:

val instance
    get() = getFromDb() ?: MyData()

If there is a non-null MyData instance then it will give this instance all the time and if result from DB is null, I will always get new instance of MyData. I could be wrong here, so correct me if I am.

The question is how can I update the value of the getter? I.e. most of the time I want to get the data from database but after logout I want to request data from DB or just give me a new instance once again.

Body:
If I understand the situation correctly:

If the field is not null you want to get the value

If it is null you want to get it from the Database

If it does not exist in Database you want to create a new instance

And all of those instances should be saved to instance variable. If this is what you want you can do something like this:

var instance
    get() = field ?: getFromDb().also { field = it } ?: MyData().also { field = it }

Please noice the var instead of val


来源: stackexchange

问:
Ant task to determine if a file is readonly
I need to write an ant task to determine if a certain file is readonly, and if it is, fail.  I would like to avoid using a custom selector to do this do to the nature of our build system.  Anyone have any ideas how to go about doing this? I'm using ant 1.8 + ant-contrib.

Thanks!

答:
What about writing a custom condition to be used by the condition task? It is more flexible.

```<code>public class IsReadOnly extends ProjectComponent implements Condition
{
  private Resource resource;

  /**
   * The resource to test.
   */
  public void add(Resource r) {
    if (resource != null) {
        throw new BuildException("only one resource can be tested");
    }
    resource = r;
  }

  /**
   * Argument validation.
   */
  protected void validate() throws BuildException {
    if (resource == null) {
        throw new BuildException("resource is required");
    }
  }

  public boolean eval() {
    validate();
    if (resource instanceof FileProvider) {
      return !((FileProvider)resource).getFile().canWrite();
    }
    try {
      resource.getOutputStream();
      return false;
    } catch (FileNotFoundException no) {
      return false;
    } catch (IOException no) {
      return true;
    }
  }
}
</code>```

Integrate with

```<code><typedef
  name="isreadonly"
  classname="IsReadOnly"
  classpath="${myclasses}"/>
</code>```

and use it like

```<code><condition property="readonly">
  <isreadonly>
    <file file="${file}"/>
  </isreadonly>
</condition>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What about writing a custom condition to be used by the condition task? It is more flexible.

public class IsReadOnly extends ProjectComponent implements Condition
{
  private Resource resource;

  /**
   * The resource to test.
   */
  public void add(Resource r) {
    if (resource != null) {
        throw new BuildException("only one resource can be tested");
    }
    resource = r;
  }

  /**
   * Argument validation.
   */
  protected void validate() throws BuildException {
    if (resource == null) {
        throw new BuildException("resource is required");
    }
  }

  public boolean eval() {
    validate();
    if (resource instanceof FileProvider) {
      return !((FileProvider)resource).getFile().canWrite();
    }
    try {
      resource.getOutputStream();
      return false;
    } catch (FileNotFoundException no) {
      return false;
    } catch (IOException no) {
      return true;
    }
  }
}

Integrate with

<typedef
  name="isreadonly"
  classname="IsReadOnly"
  classpath="${myclasses}"/>

and use it like

<condition property="readonly">
  <isreadonly>
    <file file="${file}"/>
  </isreadonly>
</condition>


问:
How to use window, document event in reactjs and createElement like appendChild
I am confuse some idea about reactjs need to solve,

I have try it first vanilla javascript and I need the same design also reactjs

See my snippet  below.

For Vanilla Js

```<code>document.onmousemove = myFunction;

function myFunction(e){
  let span = document.createElement('span');
  document.body.appendChild(span);

  span.setAttribute('style', `width: 20px; height: 20px; background: red; position: absolute; top: ${e.clientY}px; left: ${e.clientX}px`)
}

</code>```

and for
reactjs I have tried,

```<code>class App extends React.Component {
  state = {
    setTop: '',
    setLeft: '',

  }
  componentDidMount() {
    document.onmousemove = this.myFunction;
  }
  myFunction = (e) => {
    this.setState({
      setTop: e.clientY,
      setLeft: e.clientX
    });

  }
  render() {
    const spanStyle = {
      position: 'absolute',
      width: '20px',
      height: '20px',
      background: 'red',
      top: this.state.setTop + 'px',
      left: this.state.setLeft + 'px'
    }
    return ( <
      div className = "App" >
      <
      span style = {
        spanStyle
      } > < /span> < /
      div >
    )
  }
}

ReactDOM.render( < App / > , window.root)

</code>```

for ReactJs the span tag not increasing which vanilla js does and one thing for reactjs the code doesn't make good sense I need pure idea for reactjs this code, if without component and short code concept that will me fine.

答:
I have created code on codeSandBox, click here.

This will answer your question. I have made exact copy of your vanilla code with React.

The issue was with your code you were not creating new span, in your code we have only one span and its style is keep on updating as the mouse move.

import React, { Fragment } from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      divs: []
    };

    this.myFunction.bind(this);
  }

  componentDidMount() {
    document.addEventListener("mousemove", this.myFunction.bind(this), false);
  }

  myFunction(e) {
    let style = {
      width: "20px",
      height: "20px",
      background: "red",
      position: "absolute",
      top: `${e.clientY}px`,
      left: `${e.clientX}px`
    };

    let s = ;

    this.setState(prevState => ({
      divs: [...prevState.divs, s]
    }));
  }

  render() {
    return (
      <Fragment>
        Test loadeed.
        {this.state.divs}
      </Fragment>
    );
  }
}

export default Test;

```

Just add <Test /> inside your App.js file and you will get what you want.

ContentLicense: CC BY-SA 4.0

Body:
I am confuse some idea about reactjs need to solve,

I have try it first vanilla javascript and I need the same design also reactjs

See my snippet  below.

For Vanilla Js

document.onmousemove = myFunction;

function myFunction(e){
  let span = document.createElement('span');
  document.body.appendChild(span);

  span.setAttribute('style', `width: 20px; height: 20px; background: red; position: absolute; top: ${e.clientY}px; left: ${e.clientX}px`)
}

and for
reactjs I have tried,

class App extends React.Component {
  state = {
    setTop: '',
    setLeft: '',

  }
  componentDidMount() {
    document.onmousemove = this.myFunction;
  }
  myFunction = (e) => {
    this.setState({
      setTop: e.clientY,
      setLeft: e.clientX
    });

  }
  render() {
    const spanStyle = {
      position: 'absolute',
      width: '20px',
      height: '20px',
      background: 'red',
      top: this.state.setTop + 'px',
      left: this.state.setLeft + 'px'
    }
    return ( <
      div className = "App" >
      <
      span style = {
        spanStyle
      } >  < /
      div >
    )
  }
}

ReactDOM.render( < App / > , window.root)

for ReactJs the span tag not increasing which vanilla js does and one thing for reactjs the code doesn't make good sense I need pure idea for reactjs this code, if without component and short code concept that will me fine.

Body:
I have created code on codeSandBox, click here.

This will answer your question. I have made exact copy of your vanilla code with React.

The issue was with your code you were not creating new span, in your code we have only one span and its style is keep on updating as the mouse move.

import React, { Fragment } from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      divs: []
    };

    this.myFunction.bind(this);
  }

  componentDidMount() {
    document.addEventListener("mousemove", this.myFunction.bind(this), false);
  }

  myFunction(e) {
    let style = {
      width: "20px",
      height: "20px",
      background: "red",
      position: "absolute",
      top: `${e.clientY}px`,
      left: `${e.clientX}px`
    };

    let s = <span style={style} />;

    this.setState(prevState => ({
      divs: [...prevState.divs, s]
    }));
  }

  render() {
    return (
      <Fragment>
        Test loadeed.
        {this.state.divs}
      </Fragment>
    );
  }
}

export default Test;

Just add <Test /> inside your App.js file and you will get what you want.


问:
Running Mean of Circular Data: Average and Standard Deviation?
Given such a list:

mylist = [1, 2, 3, 4, 5, 6, 7]

with N = 3 as the size of running mean at each step.

What is the fastest way to calculate the average and standard deviation of this list?

If it was only average np.convolve could do the job, but what about the standard deviation? or standard error?

答:
Try:

import numpy as np
N=3
mylist = [1, 2, 3, 4, 5, 6, 7]

res=np.vstack([mylist[i:]+mylist[:i] for i in range(N)])

ma=res.mean(axis=0)
std=res.std(axis=0)
```

Just for moving average you can do: https://stackoverflow.com/a/14314054/11610186

Body:
Try:

import numpy as np
N=3
mylist = [1, 2, 3, 4, 5, 6, 7]

res=np.vstack([mylist[i:]+mylist[:i] for i in range(N)])

ma=res.mean(axis=0)
std=res.std(axis=0)

Just for moving average you can do: https://stackoverflow.com/a/14314054/11610186


问:
Creating figure with exact size and no padding (and legend outside the axes)
I am trying to make some figures for a scientific article, so I want my figures to have a specific size. I also see that Matplotlib by default adds a lot of padding on the border of the figures, which I don't need (since the figures will be on a white background anyway).

To set a specific figure size I simply use plt.figure(figsize = [w, h]), and I add the argument tight_layout = {'pad': 0} to remove the padding. This works perfectly, and even works if I add a title, y/x-labels etc. Example:

```<code>fig = plt.figure(
    figsize = [3,2],
    tight_layout = {'pad': 0}
)
ax = fig.add_subplot(111)
plt.title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
plt.savefig('figure01.pdf')
</code>```

This creates a pdf file with exact size 3x2 (inches).

The issue I have is that when I for example add a text box outside the axis (typically a legend box), Matplotlib does not make room for the text box like it does when adding titles/axis labels. Typically the text box is cut off, or does not show in the saved figure at all. Example:

```<code>plt.close('all')
fig = plt.figure(
    figsize = [3,2],
    tight_layout = {'pad': 0}
)
ax = fig.add_subplot(111)
plt.title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
t = ax.text(0.7, 1.1, 'my text here', bbox = dict(boxstyle = 'round'))
plt.savefig('figure02.pdf')
</code>```

A solution I found elsewhere on SO was to add the argument bbox_inches = 'tight' to the savefig command. The text box is now included like I wanted, but the pdf is now the wrong size. It seems like Matplotlib just makes the figure bigger, instead of reducing the size of the axes like it does when adding titles and x/y-labels.

Example:

```<code>plt.close('all')
fig = plt.figure(
    figsize = [3,2],
    tight_layout = {'pad': 0}
)
ax = fig.add_subplot(111)
plt.title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
t = ax.text(0.7, 1.1, 'my text here', bbox = dict(boxstyle = 'round'))
plt.savefig('figure03.pdf', bbox_inches = 'tight')
</code>```

(This figure is 3.307x2.248)

Is there any solution to this that covers most cases with a legend just outside the axes?

答:
As of matplotlib==3.1.3, you can use constrained_layout=True to achieve the desired result. This is currently experimental, but see the docs for a very helpful guide (and the section specifically on legends). Note that the legend will steal space from the plot, but this is unavoidable. I've found that as long as the legend does not take up too much space relative to the size of the plot, then the figure gets saved without cropping anything.

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(3, 2), constrained_layout=True)
ax.set_title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
ax.plot([0,1], [0,1], label='my text here')
ax.legend(loc='center left', bbox_to_anchor=(1.1, 0.5))
fig.savefig('figure03.pdf')
</code>```

Body:
I am trying to make some figures for a scientific article, so I want my figures to have a specific size. I also see that Matplotlib by default adds a lot of padding on the border of the figures, which I don't need (since the figures will be on a white background anyway).

To set a specific figure size I simply use plt.figure(figsize = [w, h]), and I add the argument tight_layout = {'pad': 0} to remove the padding. This works perfectly, and even works if I add a title, y/x-labels etc. Example:

fig = plt.figure(
    figsize = [3,2],
    tight_layout = {'pad': 0}
)
ax = fig.add_subplot(111)
plt.title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
plt.savefig('figure01.pdf')

This creates a pdf file with exact size 3x2 (inches).

The issue I have is that when I for example add a text box outside the axis (typically a legend box), Matplotlib does not make room for the text box like it does when adding titles/axis labels. Typically the text box is cut off, or does not show in the saved figure at all. Example:

plt.close('all')
fig = plt.figure(
    figsize = [3,2],
    tight_layout = {'pad': 0}
)
ax = fig.add_subplot(111)
plt.title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
t = ax.text(0.7, 1.1, 'my text here', bbox = dict(boxstyle = 'round'))
plt.savefig('figure02.pdf')

A solution I found elsewhere on SO was to add the argument bbox_inches = 'tight' to the savefig command. The text box is now included like I wanted, but the pdf is now the wrong size. It seems like Matplotlib just makes the figure bigger, instead of reducing the size of the axes like it does when adding titles and x/y-labels.

Example:

plt.close('all')
fig = plt.figure(
    figsize = [3,2],
    tight_layout = {'pad': 0}
)
ax = fig.add_subplot(111)
plt.title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
t = ax.text(0.7, 1.1, 'my text here', bbox = dict(boxstyle = 'round'))
plt.savefig('figure03.pdf', bbox_inches = 'tight')

(This figure is 3.307x2.248)

Is there any solution to this that covers most cases with a legend just outside the axes?

Body:
As of matplotlib==3.1.3, you can use constrained_layout=True to achieve the desired result. This is currently experimental, but see the docs for a very helpful guide (and the section specifically on legends). Note that the legend will steal space from the plot, but this is unavoidable. I've found that as long as the legend does not take up too much space relative to the size of the plot, then the figure gets saved without cropping anything.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(3, 2), constrained_layout=True)
ax.set_title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
ax.plot([0,1], [0,1], label='my text here')
ax.legend(loc='center left', bbox_to_anchor=(1.1, 0.5))
fig.savefig('figure03.pdf')


问:
JavaScript passing argument problem
I have following code

```<code>for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }
</code>```

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

答:
This is assuming that pag is an element, and that you are using jquery.

for (var i = 0; i < that.$el.mini.length; i++) {

```<code>var pag = that.$el.mini[i].pagination;

// Mini-Slider Pagination
$('li', pag).each( function(j, el) {

    $(el).data('page-index', i); // add data to the element being clicked
    $(el).click( function() {

        /*
         * Toggle Mini-Slide
         */
        that.slider_fn.mini.show($(this).data('page-index'), j);

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

}

Title: JavaScript passing argument problem

Body:
I have following code

for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

Body:
This is assuming that pag is an element, and that you are using jquery.

for (var i = 0; i < that.$el.mini.length; i++) {

var pag = that.$el.mini[i].pagination;

// Mini-Slider Pagination
$('li', pag).each( function(j, el) {

    $(el).data('page-index', i); // add data to the element being clicked
    $(el).click( function() {

        /*
         * Toggle Mini-Slide
         */
        that.slider_fn.mini.show($(this).data('page-index'), j);

        return false;
    });
});

}


问:
Regex pattern with positive lookahead and lookbehind
I have a file looking like:

```<code>maar beroepsmensen
    p( maar | <s> )     =  0.005859305 [ -2.232154 ]
    p( beroepsmensen | maar ...)    =  7.865118e-06 [ -5.104295 ] # <- first match: 7.865118e-06
    p( kunnen | beroepsmensen ...)  =  6.842439e-08 [ -5.104295 ]
    p( </s> | kunnen ...)   =  0.04018713 [ -1.395913 ]
1 sentences, 2 words, 0 OOVs
0 zeroprobs, logprob= -8.732362 ppl= 814.3052 ppl1= 23237.04

dan scootermobiel
    p( dan | <s> )  =  0.005859305 [ -2.232154 ]
    p( scootermobiel | dan)     =  0.827746 [ -9.106363 ] # <- second match: 0.827746
    p( he | scootermobiel)  =  0.2520393 [ -3.123365 ]
    p( </s> | he ...)   =  0.04499642 [ -1.346822 ]
1 sentences, 2 words, 0 OOVs
</code>```

and a list with some word, e.g. mylst = ['beroepsmensen', 'scootermobiel'].

I want to loop through the list and find the first number in the line with the pattern p( ithwordfromlist | anotherword )    = 9.999999999. (Please see above for the matches concerning the toyexample). Note that the other word after the | can be succeeded by three dots, and that the number sometimes consists of a e- structure.

So far, I managed do write a regex, that finds all numbers in front of the [ with an optional . and optional e- using a positive lookahead:

\d+(\.\d+)?(e-\d+)?(?=( )+\[) #the number of spaces after the number can vary too.

However, I failed to write a positive lookbehind that matches the pattern before the number. For instance, a lookbehind like (?<=\=( )+) elicits the error A quantifier inside a lookbehind makes it non-fixed width. (Maybe using a lookbehind is not the best approach, so please don't hesitate to propose other solutions too.)

Up to now, I split the long file into a list of lines and apply the regex on every element in that list. However, I could of course also apply it on the whole list, if it would be faster. So if you have solutions for both approaches, please let me know, I will compare the runtime then. Thx!!!

Edit: Insert new lines, which start with structure p( word1 | word2 ) and should not be matched

Edit2: Make the question more concrete

Body:
I have a file looking like:

maar beroepsmensen
    p( maar | <s> )     =  0.005859305 [ -2.232154 ]
    p( beroepsmensen | maar ...)    =  7.865118e-06 [ -5.104295 ] # <- first match: 7.865118e-06
    p( kunnen | beroepsmensen ...)  =  6.842439e-08 [ -5.104295 ]
    p( </s> | kunnen ...)   =  0.04018713 [ -1.395913 ]
1 sentences, 2 words, 0 OOVs
0 zeroprobs, logprob= -8.732362 ppl= 814.3052 ppl1= 23237.04

dan scootermobiel
    p( dan | <s> )  =  0.005859305 [ -2.232154 ]
    p( scootermobiel | dan)     =  0.827746 [ -9.106363 ] # <- second match: 0.827746
    p( he | scootermobiel)  =  0.2520393 [ -3.123365 ]
    p( </s> | he ...)   =  0.04499642 [ -1.346822 ]
1 sentences, 2 words, 0 OOVs

and a list with some word, e.g. mylst = ['beroepsmensen', 'scootermobiel'].

I want to loop through the list and find the first number in the line with the pattern p( ithwordfromlist | anotherword )    = 9.999999999. (Please see above for the matches concerning the toyexample). Note that the other word after the | can be succeeded by three dots, and that the number sometimes consists of a e- structure.

So far, I managed do write a regex, that finds all numbers in front of the [ with an optional . and optional e- using a positive lookahead:

\d+(\.\d+)?(e-\d+)?(?=( )+\[) #the number of spaces after the number can vary too.

However, I failed to write a positive lookbehind that matches the pattern before the number. For instance, a lookbehind like (?<=\=( )+) elicits the error A quantifier inside a lookbehind makes it non-fixed width. (Maybe using a lookbehind is not the best approach, so please don't hesitate to propose other solutions too.)

Up to now, I split the long file into a list of lines and apply the regex on every element in that list. However, I could of course also apply it on the whole list, if it would be faster. So if you have solutions for both approaches, please let me know, I will compare the runtime then. Thx!!!

Edit: Insert new lines, which start with structure p( word1 | word2 ) and should not be matched

Edit2: Make the question more concrete

Body:
How about a regex like this:

\s*p\s*\(\s*\w+\s*\|\s*\w+\s*\)\s*=\s*([\de\-\.]+)\s*\[\s*[\-\.\de]+\s*\]\s*

As seen here

All you need to do is extract group 1 from each match.

The complete code would look like this:

import re

pattern = r'\s*p\s*\(\s*\w+\s*\|\s*\w+\s*\)\s*=\s*([\de\-\.]+)\s*\[\s*[\-\.\de]+\s*\]\s*'

f = """maar beroepsmensen
    p( maar | <s> )     =  0.005859305 [ -2.232154 ]
    p( beroepsmensen | maar )    =  7.865118e-06 [ -5.104295 ] # <- first match: 7.865118e-06
    p( </s> | beroepsmensen ...)    =  0.04018713 [ -1.395913 ]
1 sentences, 2 words, 0 OOVs
0 zeroprobs, logprob= -8.732362 ppl= 814.3052 ppl1= 23237.04

dan scootermobiel
    p( dan | <s> )  =  0.005859305 [ -2.232154 ]
    p( scootermobiel | dan)     =  0.827746 [ -9.106363 ] # <- second match: 0.827746
    p( </s> | scootermobiel ...)    =  0.04499642 [ -1.346822 ]
1 sentences, 2 words, 0 OOVs"""

print(re.findall(pattern, f))

The output will be ['7.865118e-06', '0.827746']


问:
ValueError: ValueError: invalid literal for int() with base 10 in Python
It says ValueError. I've tried using int('') as well. Didn't work.</p>

```<code>first = []
a=int(input());

for i in range(0,a):
    ele = int(input());
    first.append(ele);

second = first[::-1];

th = [x + y for x, y in zip(first, second)];
print(th);
</code>```

答:
According to the official documentation, the class constructor for int is as follows.

class int(x, base=10)
```

<p>So a base of 10 is assumed (I guess because a decimal number system is the most prevalent) unless and otherwise you state something else.</p>

<p>So what should be x?</p>

<p>Again as per the docs.</p>

<blockquote>
  <p>If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.</p>
</blockquote>

<p>So the x should be an integer literal of that base. If you supply an alphabet say 'A' for int like below, the 'A' can not be represented as an integer using a decimal number system. Trying to do the below ..</p>

<pre class="lang-py prettyprint-override"><code>Num = int('A')
print(Num)
</code>```

will get you an error ...

ValueError: invalid literal for int() with base 10: 'A'
```

<p>However, if your number system (base) is hexadecimal then you can say base=16 and it will faithfully convert 'A' it into an integer. So the below ...</p>

<pre class="lang-py prettyprint-override"><code>Num = int('A', base=16)
print(Num)
</code>```

gives ..

10
```

So please check what is your number system (base) is and see if the string (that you are trying to convert to an integer) makes sense for that particular number system.

Body:
It says ValueError. I've tried using int('') as well. Didn't work.

first = []
a=int(input());

for i in range(0,a):
    ele = int(input());
    first.append(ele);

second = first[::-1];

th = [x + y for x, y in zip(first, second)];
print(th);

Body:
According to the official documentation, the class constructor for int is as follows.

class int(x, base=10)

So a base of 10 is assumed (I guess because a decimal number system is the most prevalent) unless and otherwise you state something else.

So what should be x?

Again as per the docs.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.

So the x should be an integer literal of that base. If you supply an alphabet say 'A' for int like below, the 'A' can not be represented as an integer using a decimal number system. Trying to do the below ..

Num = int('A')
print(Num)

will get you an error ...

ValueError: invalid literal for int() with base 10: 'A'

However, if your number system (base) is hexadecimal then you can say base=16 and it will faithfully convert 'A' it into an integer. So the below ...

Num = int('A', base=16)
print(Num)

gives ..

10

So please check what is your number system (base) is and see if the string (that you are trying to convert to an integer) makes sense for that particular number system.


问:
Use Octokit to list all commits in all repos on Github using Asp.net Core Razor
I want to be able to show all commits from my Github profile, i did manage to list repos and commits of one repo but can t for all.

Error msg
Below is my code :

```<code>    public IReadOnlyList<Repository> Repositories { get; set; }

    public IReadOnlyList<GitHubCommit> Commits = new List<GitHubCommit>();

    public async Task OnGetAsync()
    {
        if (User.Identity.IsAuthenticated)
        {
            GitHubName = User.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;
            GitHubLogin = User.FindFirst(c => c.Type == "urn:github:login")?.Value;
            GitHubUrl = User.FindFirst(c => c.Type == "urn:github:url")?.Value;
            GitHubAvatar = User.FindFirst(c => c.Type == "urn:github:avatar")?.Value;

            string accessToken = await HttpContext.GetTokenAsync("access_token");

            var github = new GitHubClient(new ProductHeaderValue("CommitView"), new InMemoryCredentialStore(new Credentials(accessToken)));

            Repositories = await github.Repository.GetAllForCurrent();

            foreach (var reppo in Repositories)
            {

                var repoCommits = await github.Repository.Commit.GetAll(reppo.Id);
                Commits.Append(repoCommits);

            }

        }
    }
</code>```

答:
Octokit.net maintainer here.

The IReadOnlyList<T> returned from each collection-based API in Octokit.net is an interface that's part of the .NET Framework which we use to signal that the response returned from the GitHub API is not mutable, and it lacks the mutable APIs like Add or Append, which is why your sample doesn't compile.

In particular it's this line:

public IReadOnlyList<GitHubCommit> Commits = new List<GitHubCommit>();
```

<p><code>IReadOnlyList<T></code> can be enumerated like other collection types, so the quickest way to get your sample working would be to use the <code>List<T></code> APIs instead that support adding a range of elements:</p>

<pre class="lang-cs prettyprint-override"><code>public List<Repository> Repositories { get; set; }
public List<GitHubCommit> Commits = new List<GitHubCommit>();

public async Task OnGetAsync()
{
  if (User.Identity.IsAuthenticated)
  {
    GitHubName = User.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;
    GitHubLogin = User.FindFirst(c => c.Type == "urn:github:login")?.Value;
    GitHubUrl = User.FindFirst(c => c.Type == "urn:github:url")?.Value;
    GitHubAvatar = User.FindFirst(c => c.Type == "urn:github:avatar")?.Value;

    string accessToken = await HttpContext.GetTokenAsync("access_token");

    var github = new GitHubClient(new ProductHeaderValue("CommitView"), new InMemoryCredentialStore(new Credentials(accessToken)));

    var repositories = await github.Repository.GetAllForCurrent();
    Repositories = new List<Repository>(repositories);

    foreach (var repo in Repositories)
    {
      var repoCommits = await github.Repository.Commit.GetAll(repo.Id);
      Commits.AddRange(repoCommits);
    }
  }
}
</code>```

Body:
I want to be able to show all commits from my Github profile, i did manage to list repos and commits of one repo but can t for all.

Error msg
Below is my code :

    public IReadOnlyList<Repository> Repositories { get; set; }

    public IReadOnlyList<GitHubCommit> Commits = new List<GitHubCommit>();

    public async Task OnGetAsync()
    {
        if (User.Identity.IsAuthenticated)
        {
            GitHubName = User.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;
            GitHubLogin = User.FindFirst(c => c.Type == "urn:github:login")?.Value;
            GitHubUrl = User.FindFirst(c => c.Type == "urn:github:url")?.Value;
            GitHubAvatar = User.FindFirst(c => c.Type == "urn:github:avatar")?.Value;

            string accessToken = await HttpContext.GetTokenAsync("access_token");

            var github = new GitHubClient(new ProductHeaderValue("CommitView"), new InMemoryCredentialStore(new Credentials(accessToken)));

            Repositories = await github.Repository.GetAllForCurrent();

            foreach (var reppo in Repositories)
            {

                var repoCommits = await github.Repository.Commit.GetAll(reppo.Id);
                Commits.Append(repoCommits);

            }

        }
    }

Body:
Octokit.net maintainer here.

The IReadOnlyList<T> returned from each collection-based API in Octokit.net is an interface that's part of the .NET Framework which we use to signal that the response returned from the GitHub API is not mutable, and it lacks the mutable APIs like Add or Append, which is why your sample doesn't compile.

In particular it's this line:

public IReadOnlyList<GitHubCommit> Commits = new List<GitHubCommit>();

IReadOnlyList<T> can be enumerated like other collection types, so the quickest way to get your sample working would be to use the List<T> APIs instead that support adding a range of elements:

public List<Repository> Repositories { get; set; }
public List<GitHubCommit> Commits = new List<GitHubCommit>();

public async Task OnGetAsync()
{
  if (User.Identity.IsAuthenticated)
  {
    GitHubName = User.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;
    GitHubLogin = User.FindFirst(c => c.Type == "urn:github:login")?.Value;
    GitHubUrl = User.FindFirst(c => c.Type == "urn:github:url")?.Value;
    GitHubAvatar = User.FindFirst(c => c.Type == "urn:github:avatar")?.Value;

    string accessToken = await HttpContext.GetTokenAsync("access_token");

    var github = new GitHubClient(new ProductHeaderValue("CommitView"), new InMemoryCredentialStore(new Credentials(accessToken)));

    var repositories = await github.Repository.GetAllForCurrent();
    Repositories = new List<Repository>(repositories);

    foreach (var repo in Repositories)
    {
      var repoCommits = await github.Repository.Commit.GetAll(repo.Id);
      Commits.AddRange(repoCommits);
    }
  }
}


问:
pip package loses package data after reboot
I have installed my python project with the help of setuptools and defined some static txt,conf and html files. But my problem is that, after rebooting my debian System, the script doesn't finds the static files anymore. I defined them in the MANIFEST.in as follows:

```<code>include data/*.conf
include data/*.html
include data/*.txt
</code>```

this is my setup.py

```<code>#!/usr/bin/python3
from setuptools import setup, find_packages
setup(
    name="dnwtools",
    version = "0.0.4",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
          'jinja2',
          'pymysql'
    ],
    entry_points = {
        "console_scripts": [
            "dnwtools = dnwtools.main:main",
        ]
    },
    python_requires='>=3.6',
)
</code>```

Thank you for your help in advance !

答: i solved the problem on my on: id just had to ad the <code>__file__</code> variable to </p>

Body:
I have installed my python project with the help of setuptools and defined some static txt,conf and html files. But my problem is that, after rebooting my debian System, the script doesn't finds the static files anymore. I defined them in the MANIFEST.in as follows:

include data/*.conf
include data/*.html
include data/*.txt

this is my setup.py

#!/usr/bin/python3
from setuptools import setup, find_packages
setup(
    name="dnwtools",
    version = "0.0.4",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
          'jinja2',
          'pymysql'
    ],
    entry_points = {
        "console_scripts": [
            "dnwtools = dnwtools.main:main",
        ]
    },
    python_requires='>=3.6',
)

Thank you for your help in advance !

Body: i solved the problem on my on: id just had to ad the __file__ variable to


问:
regex to match content not containing multiple sentences including line breaks
I'm trying to match content that does not include three separate sentences including line breaks.

```<code>one sentence
another one
last one
</code>```

I tried this:

^((?!this sentence|another one|last one).)*$

which works but only along a single line, how can I make it match across multiple line breaks? It should match something like this:

```<code>None of the sentences
are included in this
paragraph, so it should
match the whole content
</code>```

答: This is what you looking for ^(((?!this sentence|another one|last one)(?:.|\n))*)$.

Body:
I'm trying to match content that does not include three separate sentences including line breaks.

one sentence
another one
last one

I tried this:

^((?!this sentence|another one|last one).)*$

which works but only along a single line, how can I make it match across multiple line breaks? It should match something like this:

None of the sentences
are included in this
paragraph, so it should
match the whole content


问:
xmlTreeParse and html content
I can't get (web scrape) html tree content with R function xmlTreeParse - I mean common page with products.

I get library Rcurl and XML.

```<code>myurln3<-"www.amazon.com/s?k=router+hand+plane+cheap&i=arts-crafts-intl-ship&ref=nb_sb_noss"
html_page<-xmlTreeParse(myurln3, useInternalNodes = TRUE)
</code>```

Error: XML content does not seem to be XML:
'www.amazon.com/s?k=router+hand+plane+cheap&i=arts-crafts-intl-ship&ref=nb_sb_noss'

I expect to scrape page and get full html structure.

答:
I back after some other projects to web scraping with R and still with problems.

```<code>> library(XML)

Warning message:
XML package is in R 3.5.3 version

> my_url99 <- "https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2"
> html_page99 <- htmlTreeParse(my_url99, useInternalNode=TRUE)

Warning message:
XML content does not seem to be XML: 'https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2'

> head(html_page99)

Error in `[.XMLInternalDocument`(x, seq_len(n)) :
  No method for subsetting an XMLInternalDocument with integer

> html_page99

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2</p></body></html>
</code>```

But I need to scrape above page with full content = I mean content with $ sign on the left (fmaybe that's not the best direct description) and all the tags.

Title: xmlTreeParse and html content

Body:
I can't get (web scrape) html tree content with R function xmlTreeParse - I mean common page with products.

I get library Rcurl and XML.

myurln3<-"www.amazon.com/s?k=router+hand+plane+cheap&i=arts-crafts-intl-ship&ref=nb_sb_noss"
html_page<-xmlTreeParse(myurln3, useInternalNodes = TRUE)

Error: XML content does not seem to be XML:
'www.amazon.com/s?k=router+hand+plane+cheap&i=arts-crafts-intl-ship&ref=nb_sb_noss'

I expect to scrape page and get full html structure.

Body:
I back after some other projects to web scraping with R and still with problems.

> library(XML)

Warning message:
XML package is in R 3.5.3 version

> my_url99 <- "https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2"
> html_page99 <- htmlTreeParse(my_url99, useInternalNode=TRUE)

Warning message:
XML content does not seem to be XML: 'https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2'

> head(html_page99)

Error in `[.XMLInternalDocument`(x, seq_len(n)) :
  No method for subsetting an XMLInternalDocument with integer

> html_page99

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>https://www.amazon.com/s?k=Dell+laptop+windows+10&amp;ref=nb_sb_noss_2</p></body></html>

But I need to scrape above page with full content = I mean content with $ sign on the left (fmaybe that's not the best direct description) and all the tags.


问:
Valgrind + C: Handling uninitialized pointers without error
Maybe I got too involved with testing my assignment, but here's my dilemma:

This is my offending function (more or less):

```<code>struct thing{
    char* data;
}

int function(struct thing* arg){
    if(arg->data == NULL)
        return -1;
}
</code>```

This is my offending input:

```<code>struct thing *x = malloc(sizeof(struct thing));
function(x);
</code>```

And valgrind outputs this when I test it:

Conditional jump or move depends on uninitialised value(s)
```

I'm about 99% sure that this is because valgrind has an issue with evaluating x->data when it hasn't been initialized to NULL or malloced. Is there a workaround for this?

答:
To my opinion valgrind is right in complaining here because data is in fact not initialized and function is not able to determine if it was. The function can only check if it has the defined value you used for initialization.

So I would consider using a creation function that does the initialization as well. This way you could also allocate the memory for data right away when passing its size as parameter (or just NULL if you want to do that later).

```<code>struct thing *newThing(size_t dataSize)
{
   struct thing *t = malloc(sizeof (struct thing));

   if (t)
      t->data = malloc(sizeof(char) * dataSize);
      // or t->data = NULL if it should be done later

   return t;
}
</code>```

Body:
Maybe I got too involved with testing my assignment, but here's my dilemma:

This is my offending function (more or less):

struct thing{
    char* data;
}

int function(struct thing* arg){
    if(arg->data == NULL)
        return -1;
}

This is my offending input:

struct thing *x = malloc(sizeof(struct thing));
function(x);

And valgrind outputs this when I test it:

Conditional jump or move depends on uninitialised value(s)

I'm about 99% sure that this is because valgrind has an issue with evaluating x->data when it hasn't been initialized to NULL or malloced. Is there a workaround for this?

Body:
To my opinion valgrind is right in complaining here because data is in fact not initialized and function is not able to determine if it was. The function can only check if it has the defined value you used for initialization.

So I would consider using a creation function that does the initialization as well. This way you could also allocate the memory for data right away when passing its size as parameter (or just NULL if you want to do that later).

struct thing *newThing(size_t dataSize)
{
   struct thing *t = malloc(sizeof (struct thing));

   if (t)
      t->data = malloc(sizeof(char) * dataSize);
      // or t->data = NULL if it should be done later

   return t;
}


问:
iOS 7 Custom UINavigationBar TitleView moves when Pushing or Popping new View Controller
I am using a custom title view for a UINavigationBar with the following code:

```<code>// Set a label to the nav bar
THLabel *titleLabel = [[THLabel alloc] init];
titleLabel.text = @"Test";
titleLabel.font = [UIFont fontWithName:APP_FONT size:22.0];
titleLabel.frame = CGRectMake(0, 0, 100, 30);
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = CUSTOM_LIGHT_BLUE;
titleLabel.strokeColor = kStrokeColor;
titleLabel.strokeSize = kStrokeSize;
self.navigationItem.titleView = titleLabel;
</code>```

The problem is that when presenting a new viewcontroller and then returning to the original view controller this custom view shifts and then re-centers itself. Please see the video for a demonstration of that.

Please see the video here:
https://www.youtube.com/watch?v=961CCVQmpJM&feature=youtu.be

I have disabled autoresizing of every subview for the navigation controller with both the storyboard and in code for each view controller:

```<code>    // Set the navigation bar hidded on the log in view
    UINavigationController* mainViewController = (UINavigationController*)self.appDelegate.window.rootViewController;
    [mainViewController setNavigationBarHidden:YES];
    [[mainViewController navigationBar] setAutoresizesSubviews:NO];
</code>```

However it still resizes! How can I stop this - what am I doing wrong? Thanks!

答:
I tried all the answers above, and ended up creating the view and label like this:

I added a UIView variable for my VC:

```<code>let titleView: UIView = {
    // A factory method that returns a customised `UILabel`
    let label = Factory.Label.title()

    let view = UIView()
    view.addSubview(label)
    label.text = localized.mainMenuItemSettings()
    //I use EasyPeasy for my constraints,
    //but essentially I set top, left, bottom and right anchors to fill my UIView
    label.easy.layout(Edges())
    return view
}()
</code>```

Then in my viewWillAppear(animated:) method I set the view as the titleView of my navigationItem:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationItem.titleView = titleView
}
</code>```

I use EasyPeasy for constraints as I find them super easy to use and very compact.

Body:
I am using a custom title view for a UINavigationBar with the following code:

// Set a label to the nav bar
THLabel *titleLabel = [[THLabel alloc] init];
titleLabel.text = @"Test";
titleLabel.font = [UIFont fontWithName:APP_FONT size:22.0];
titleLabel.frame = CGRectMake(0, 0, 100, 30);
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = CUSTOM_LIGHT_BLUE;
titleLabel.strokeColor = kStrokeColor;
titleLabel.strokeSize = kStrokeSize;
self.navigationItem.titleView = titleLabel;

The problem is that when presenting a new viewcontroller and then returning to the original view controller this custom view shifts and then re-centers itself. Please see the video for a demonstration of that.

Please see the video here:
https://www.youtube.com/watch?v=961CCVQmpJM&feature=youtu.be

I have disabled autoresizing of every subview for the navigation controller with both the storyboard and in code for each view controller:

    // Set the navigation bar hidded on the log in view
    UINavigationController* mainViewController = (UINavigationController*)self.appDelegate.window.rootViewController;
    [mainViewController setNavigationBarHidden:YES];
    [[mainViewController navigationBar] setAutoresizesSubviews:NO];

However it still resizes! How can I stop this - what am I doing wrong? Thanks!

Body:
I tried all the answers above, and ended up creating the view and label like this:

I added a UIView variable for my VC:

let titleView: UIView = {
    // A factory method that returns a customised `UILabel`
    let label = Factory.Label.title()

    let view = UIView()
    view.addSubview(label)
    label.text = localized.mainMenuItemSettings()
    //I use EasyPeasy for my constraints,
    //but essentially I set top, left, bottom and right anchors to fill my UIView
    label.easy.layout(Edges())
    return view
}()

Then in my viewWillAppear(animated:) method I set the view as the titleView of my navigationItem:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationItem.titleView = titleView
}

I use EasyPeasy for constraints as I find them super easy to use and very compact.


问:
Use "arp -a" to retreive MAC address of corresponding IP Adress
I was trying to convert the MAC address of my phone to it's IP address.

```<code>var arpStream = ExecuteCommandLine("arp", "-a");
List<string> result = new List<string>();
   while (!arpStream.EndOfStream)
  {
      var line = arpStream.ReadLine().Trim();
      result.Add(line);
  }
</code>```

Using the above code, I store it in a list in the following form:

```<code>  192.168.137.1         2e-bb-58-0a-2f-34     dynamic
  192.168.137.44        a8-3e-0e-61-3f-db     dynamic
  192.168.137.91        d4-63-c6-b2-ac-38     dynamic
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.252           01-00-5e-00-00-fc     static
</code>```

What I can't figure out is, how to retrieve a specific IP for the given MAC.
Assume that my phone is the device with the physical address: a8-3e-0e-61-3f-db, how can I store it's IP as a string somewhere?

答:
I'm assuming you've got the list of strings somehow (ExecuteCommandLine method) and want to be able to filter it based on arp value. Regex can be an option then:

void Main()
{
    // just setting it up for testing
    List<string> result = new List<string>();
    result.Add("192.168.137.1         2e-bb-58-0a-2f-34     dynamic");
    result.Add("192.168.137.44        a8-3e-0e-61-3f-db     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("192.168.137.91        d4-63-c6-b2-ac-38     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.252           01-00-5e-00-00-fc     static");

    // this is the part you want
    ConcurrentDictionary<string,string> arps = new ConcurrentDictionary<string, string>();
    foreach (var s in result)
    {
        var matches = Regex.Match(s, @"((?:\d+\.?){4})\s+((?:[0-9a-f]{2}-?){6}).*");
        arps.TryAdd(matches.Groups[2].Value, matches.Groups[1].Value);
    }

    Console.WriteLine(arps["01-00-5e-00-00-16"]);
}
```

note: opting for dictionary here has benefits as well as drawbacks.
you will get O(1) element access times, but you can't have duplicate MAC addresses there. Without knowing your specific use case it's a bit hard to say whether this tradeoff will apply to you, I'm just pointing this out as an option.

Body:
I was trying to convert the MAC address of my phone to it's IP address.

var arpStream = ExecuteCommandLine("arp", "-a");
List<string> result = new List<string>();
   while (!arpStream.EndOfStream)
  {
      var line = arpStream.ReadLine().Trim();
      result.Add(line);
  }

Using the above code, I store it in a list in the following form:

  192.168.137.1         2e-bb-58-0a-2f-34     dynamic
  192.168.137.44        a8-3e-0e-61-3f-db     dynamic
  192.168.137.91        d4-63-c6-b2-ac-38     dynamic
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.252           01-00-5e-00-00-fc     static

What I can't figure out is, how to retrieve a specific IP for the given MAC.
Assume that my phone is the device with the physical address: a8-3e-0e-61-3f-db, how can I store it's IP as a string somewhere?

Body:
I'm assuming you've got the list of strings somehow (ExecuteCommandLine method) and want to be able to filter it based on arp value. Regex can be an option then:

void Main()
{
    // just setting it up for testing
    List<string> result = new List<string>();
    result.Add("192.168.137.1         2e-bb-58-0a-2f-34     dynamic");
    result.Add("192.168.137.44        a8-3e-0e-61-3f-db     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("192.168.137.91        d4-63-c6-b2-ac-38     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.252           01-00-5e-00-00-fc     static");

    // this is the part you want
    ConcurrentDictionary<string,string> arps = new ConcurrentDictionary<string, string>();
    foreach (var s in result)
    {
        var matches = Regex.Match(s, @"((?:\d+\.?){4})\s+((?:[0-9a-f]{2}-?){6}).*");
        arps.TryAdd(matches.Groups[2].Value, matches.Groups[1].Value);
    }

    Console.WriteLine(arps["01-00-5e-00-00-16"]);
}

note: opting for dictionary here has benefits as well as drawbacks.
you will get O(1) element access times, but you can't have duplicate MAC addresses there. Without knowing your specific use case it's a bit hard to say whether this tradeoff will apply to you, I'm just pointing this out as an option.


问:
How to serve a lot of pages
I want to create a web server with many subpages. For example

www.mainpage.com - main page and I have many subpages

www.mainpage.com/1page; www.mainpage.com/2page; www.mainpage.com/3page; ..... www.mainpage.com/999page

I have no idea how to handle all of this pages. I think that this way isn't correct

```<code>func main() {
    http.HandleFunc("/1page", PageHandler)
    http.HandleFunc("/2page", PageHandler)
    ......
    http.HandleFunc("/999page", PageHandler)

    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}
</code>```

答:
The documentation for http.HandleFunc says:

The documentation for ServeMux explains how patterns are matched.

ServeMux says:

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

The Request object passed to the handler function contains the request URL.

So just register a single pattern at the root:

```<code>    http.HandleFunc("/", PageHandler)
</code>```

Title: How to serve a lot of pages

Body:
I want to create a web server with many subpages. For example

www.mainpage.com - main page and I have many subpages

www.mainpage.com/1page; www.mainpage.com/2page; www.mainpage.com/3page; ..... www.mainpage.com/999page

I have no idea how to handle all of this pages. I think that this way isn't correct

func main() {
    http.HandleFunc("/1page", PageHandler)
    http.HandleFunc("/2page", PageHandler)
    ......
    http.HandleFunc("/999page", PageHandler)

    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}

Body:
The documentation for http.HandleFunc says:

The documentation for ServeMux explains how patterns are matched.

ServeMux says:

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

The Request object passed to the handler function contains the request URL.

So just register a single pattern at the root:

    http.HandleFunc("/", PageHandler)


问:
WCF 4.0's analog to WCF REST Starter Kit's RequestInterceptor?
Does WCF 4.0 have an analog class/module/whatever to WCF REST Starter Kit's RequestInterceptor?</p>

答: There isn't anything which maps 1-1 to it, but you can use an IDispatchMessageInspector from WCF core to implement most of the scenarios for which the RequestInspector would do. The post at http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx has some detailed information about the message inspectors.</p>


问:
How to check if dropdown is toggle on and add class
I want to check if the dropdown menu is toggled. If the menu has a class: mega-toggle-on then add a class to id #submenu-new.

Here is my code:

```<code>  <div id="submenu-new" class="submenu-balk active" style="padding-top: 226px;">

      </div>

<script type="text/javascript">
if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).is( ".mega-toggle-on" ) ) {

 jQuery("#submenu-new").addClass("active");
alert('ss');

}
</script>
</code>```

Example where you can find the mega-toggle-on class

答:
As you are using JQuery, you can use hasClass to check whether given class is exists at the current moment and if exists you can change class to the otherClass.</p>

```<code>if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).hasClass( "mega-toggle-on" ) ) { // class "mega-toggle-on" exists...
  jQuery("#submenu-new").addClass("active");
} else {  // class "mega-toggle-on" does not exists...
  jQuery("#submenu-new").removeClass("active");
}
</code>```

Body:
I want to check if the dropdown menu is toggled. If the menu has a class: mega-toggle-on then add a class to id #submenu-new.

Here is my code:

Example where you can find the mega-toggle-on class

Body:
As you are using JQuery, you can use hasClass to check whether given class is exists at the current moment and if exists you can change class to the otherClass.

if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).hasClass( "mega-toggle-on" ) ) { // class "mega-toggle-on" exists...
  jQuery("#submenu-new").addClass("active");
} else {  // class "mega-toggle-on" does not exists...
  jQuery("#submenu-new").removeClass("active");
}


问:
2D array of characters, printing extra character over limit?
The output of code

I want to create an array of character in which there are 'n' rows and each row have a character. In the given code I asked the user to enter the number of rows(n) then I create a variable 'chr' and each row contain only one character. Then I asked the characters one by one and store them in their respective rows but when I take the print of those characters something strange happens. The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?

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

int main(void) {
    int n;
    scanf("%d", &n);

    char chr[n][1];

    for (int i = 0; i < n; i++) {
        printf("Enter the %d character?\n", i);
        scanf("%s", chr[i]);
    }
    // printing
    for (int i = 0; i < n; i++) {
        printf("\n%s\n", chr[i]);
    }
    return 0;
}
</code>```

答:
The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?

```<code>scanf("%s", chr[i]);
</code>```

%s reads a whole string until it encounters a white space character, such as newline \n, and writes it (excluding the white space character) into the first dimension; not only one character.

You also forgot that since you are trying to read a string a \0 is automatically appended to each string, but since the declaration of chr there is just place for one character in a dimension, not two.

A multi-dimensional array is allocated continously in memory, which provides the effect that the \0 character for the string in the previous dimension is stored at the first and only character of the next dimension; in the next iteration scanf overwrites then this \0 character to store the second character but again writes the \0 of this string into the first an only object of the following dimension and goes so on and on for each iteration, which ends up in a complete mess of Undefined Behavior, plus the \0 of the last string is written beyond the bounds of the complete multi-dimensional array.

So you can´t even say that they were stored in just one dimension, which isn´t the case, even if it seems like it would.

For more information about Undefined Behavior look at this question:

Undefined, unspecified and implementation-defined behavior

Rather use

```<code>scanf(" %c", &chr[i][0]);
</code>```

with the %c format specifier to read only one character per iteration and implement a white space character before the %cformat specifier to catch the newline \n left in stdin by the scanf consumption of the previous loop walkthrough or any leading white space.

Also, change:

```<code>  for(int i = 0; i<n; i++) {
    printf("\n%s\n", chr[i]);
</code>```

to

```<code>  for(int i = 0; i<n; i++) {
    printf("\n %c \n", chr[i][0]);
</code>```

The whole code shall then be:

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

int main(void) {

  int n;
  scanf("%d", &n);

  char chr[n][1];

  for(int i = 0; i<n; i++) {
    printf("Enter the %d character?\n", i);
    scanf(" %c", &chr[i][0]);
  }
  // printing
  for(int i = 0; i<n; i++) {
    printf("\n %c \n", chr[i][0]);
  }
return 0;
}
</code>```

Body:
The output of code

I want to create an array of character in which there are 'n' rows and each row have a character. In the given code I asked the user to enter the number of rows(n) then I create a variable 'chr' and each row contain only one character. Then I asked the characters one by one and store them in their respective rows but when I take the print of those characters something strange happens. The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?

#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    char chr[n][1];

    for (int i = 0; i < n; i++) {
        printf("Enter the %d character?\n", i);
        scanf("%s", chr[i]);
    }
    // printing
    for (int i = 0; i < n; i++) {
        printf("\n%s\n", chr[i]);
    }
    return 0;
}

Body:
The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?

scanf("%s", chr[i]);

%s reads a whole string until it encounters a white space character, such as newline \n, and writes it (excluding the white space character) into the first dimension; not only one character.

You also forgot that since you are trying to read a string a \0 is automatically appended to each string, but since the declaration of chr there is just place for one character in a dimension, not two.

A multi-dimensional array is allocated continously in memory, which provides the effect that the \0 character for the string in the previous dimension is stored at the first and only character of the next dimension; in the next iteration scanf overwrites then this \0 character to store the second character but again writes the \0 of this string into the first an only object of the following dimension and goes so on and on for each iteration, which ends up in a complete mess of Undefined Behavior, plus the \0 of the last string is written beyond the bounds of the complete multi-dimensional array.

So you can´t even say that they were stored in just one dimension, which isn´t the case, even if it seems like it would.

For more information about Undefined Behavior look at this question:

Undefined, unspecified and implementation-defined behavior

Rather use

scanf(" %c", &chr[i][0]);

with the %c format specifier to read only one character per iteration and implement a white space character before the %cformat specifier to catch the newline \n left in stdin by the scanf consumption of the previous loop walkthrough or any leading white space.

Also, change:

  for(int i = 0; i<n; i++) {
    printf("\n%s\n", chr[i]);

to

  for(int i = 0; i<n; i++) {
    printf("\n %c \n", chr[i][0]);

The whole code shall then be:

#include <stdio.h>

int main(void) {

  int n;
  scanf("%d", &n);

  char chr[n][1];

  for(int i = 0; i<n; i++) {
    printf("Enter the %d character?\n", i);
    scanf(" %c", &chr[i][0]);
  }
  // printing
  for(int i = 0; i<n; i++) {
    printf("\n %c \n", chr[i][0]);
  }
return 0;
}


问:
Updating a field for all children in self referencing relationship
HI all,

I am using Entity Framework and ASP.NET MVC 3. In one part of the app, I have a self -referencing relationship in a table (ID, ParentID, etc...) This table also has a Status field. When a user updates a Status, it needs to update the statuses of all of it's children. The depth is variable.

I'm looking to do this without using the Load() function as I heard that is not efficient. I also came across a way to do it with a stored procedure, but I want this functionality to be done in EF and ideally just in the POST action.

答: Unfortunately, Entity Framework is very weak on self-referencing relationships. There are some tricks you can do if there are a finite number of possible levels to your hierarchy, but you'll probably be better off just using a Stored Procedure.</p>


问:
Azure web site FTP access / 530 User cannot log in
I'm trying to update an Azure Web Site using FTP.  In the past, I was able to do this fine using the credentials from the .publishsettings file as has been widely documented.  Today, I can't do that.  Instead, I get a 530 User cannot log in. - even if I regenerate the publish settings and redownload them, the new ones give me the same issue.

Back in October 2013, there was a set of these, e. g. Windows Azure and FileZilla FTP and Trying to access FTP with deployment credentials: 530 User cannot log in, that were a service failure on the Azure side, but the dashboard at http://azure.microsoft.com/en-us/status/ shows clean at the moment, so I don't think that's the same issue.

I don't want to create a new FTP/Git deployment user, because according to both the old and new portals, those credentials apply to all sites in the subscription, and I only want credentials for this site specifically.

What else should I be looking at here?

Thanks!

答:
When I set user_name\$user_name by git command config git-ftp.user it was not working.

But when I edited .git/config file I noticed that \ was missing.
I replaced it to double \

Whole config file:

```<code>[git-ftp]
    url = ftp://waws-prod-qwerty.ftp.azurewebsites.windows.net:21/site/
    password = qwerty
    user = user_name\\$user_name
</code>```

And now it's working.

OwnerDisplayName: MikeBaz

Body:
When I set user_name\$user_name by git command config git-ftp.user it was not working.

But when I edited .git/config file I noticed that \ was missing.
I replaced it to double \

Whole config file:

[git-ftp]
    url = ftp://waws-prod-qwerty.ftp.azurewebsites.windows.net:21/site/
    password = qwerty
    user = user_name\\$user_name

And now it's working.


问:
Confusion transferring PyOpenGL from PyGame to PyQt5
I am trying to piece example code for a PyGame PyOpenGL tutorial into example code for a PyQt5 QOpenGLWidget. The goal of this code is to set up a cube with one corner skewed upward in order to identify the angle of the camera. It works fine in PyGame, but there are several problems with the PyQt5 version:

First, the aspect ratio seems to be off.
Second, the window recalls paintGL every time I make it active again.
Third, most of the variables are not transferring the same in regards to glTranslatef and glRotatef.

The code I am using for PyGame:

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 2),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

colors = (
    (1,0,0),
    (0,1,0),
    (0,0,1),
    (0,1,0),
    (1,1,1),
    (0,1,1),
    (1,0,0),
    (0,1,0),
    (0,0,1),
    (1,0,0),
    (1,1,1),
    (0,1,1),
    )

surfaces = (
    (0,1,2,3),
    (3,2,7,6),
    (6,7,5,4),
    (4,5,1,0),
    (1,5,7,2),
    (4,0,3,6)
    )

def Cube():
    glBegin(GL_QUADS)
    for surface in surfaces:
        x = 0
        for vertex in surface:
            x+=1
            glColor3fv(colors[x])
            glVertex3fv(verticies[vertex])
    glEnd()

    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
    glTranslatef(0,0, -10)    #these two lines set the camera facing at the cube from the position 0, -10, 0.
    glRotatef(-90, 2, 0, 0)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    glTranslatef(-0.5,0,0)
                if event.key == pygame.K_RIGHT:
                    glTranslatef(0.5,0,0)

                if event.key == pygame.K_UP:
                    glTranslatef(0,1,0)
                if event.key == pygame.K_DOWN:
                    glTranslatef(0,-1,0)

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 4:
                    glTranslatef(0,0,1.0)

                if event.button == 5:
                    glTranslatef(0,0,-1.0)

        #glRotatef(1, 3, 1, 1)    #rotation code that was commented out.
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)
main()
```

<p>The result:
<img src="https://i.stack.imgur.com/1LB0f.png" alt="PyGame version of the cube"></p>

<p>The PyQt5 code:</p>

<pre class="lang-py prettyprint-override"><code>import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import *

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

class mainWindow(QMainWindow):    #Main class.

    verticies = (
                 (1, -1, -1),
                 (1, 1, -1),
                 (-1, 1, -1),
                 (-1, -1, -1),
                 (1, -1, 2),
                 (1, 1, 1),
                 (-1, -1, 1),
                 (-1, 1, 1)
                )

    edges = (
             (0,1),
             (0,3),
             (0,4),
             (2,1),
             (2,3),
             (2,7),
             (6,3),
             (6,4),
             (6,7),
             (5,1),
             (5,4),
             (5,7)
            )

    colors = (
              (1,0,0),
              (0,1,0),
              (0,0,1),
              (0,1,0),
              (1,1,1),
              (0,1,1),
              (1,0,0),
              (0,1,0),
              (0,0,1),
              (1,0,0),
              (1,1,1),
              (0,1,1),
             )

    surfaces = (
                (0,1,2,3),
                (3,2,7,6),
                (6,7,5,4),
                (4,5,1,0),
                (1,5,7,2),
                (4,0,3,6)
               )

    def __init__(self):
        super(mainWindow, self).__init__()
        self.width = 700    #Variables used for the setting of the size of everything
        self.height = 600
        self.setGeometry(0, 0, self.width, self.height)    #Set the window size

    def setupUI(self):
        self.openGLWidget = QOpenGLWidget(self)    #Create the GLWidget
        self.openGLWidget.setGeometry(0, 0, self.width, self.height)    #Size it the same as the window.
        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(self.width, self.height)    #Resize GL's knowledge of the window to match the physical size?
        self.openGLWidget.paintGL = self.paintGL    #override the default function with my own?

    def paintGL(self):
        gluPerspective(45, self.width / self.height, 0.1, 50.0)    #set perspective?
        glTranslatef(0, 0, -2)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(-90, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)    #Straight from the PyGame version, with 'self' inserted occasionally

        glBegin(GL_QUADS)    #tell GL to draw surfaces
        for surface in self.surfaces:
            x = 0
            for vertex in surface:
                x+=1
                glColor3fv(self.colors[x])
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing surfaces

        glBegin(GL_LINES)    #tell GL to draw lines
        for edge in self.edges:
            for vertex in edge:
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing lines.

app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())
</code>```

The result:

When I switch to another window, then switch back to the Qt window, the scene updates and paintGL is called again. Also, the cube appears to be squashed and the camera acts differently. What can I do to fix these?

Python 3.8
Windows 10

答:
The OpenGL matrix operations (like gluPerspective, glTranslate, glRotate, ...) do not just set a matrix. The operations define a new matrix and multiply the current matrix by the new matrix. The causes that the matrix continuously and progressively changes, every time when paintGL is called.

The issue can be solved with ease, by loading the identity matrix by glLoadIdentity at the begin of paintGL::

class mainWindow(QMainWindow):
    # [...]

    def paintGL(self):
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 50.0)    #set perspective?
        glTranslatef(0, 0, -10)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(-90, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
```

<p>But Legacy OpenGL provides different matrices (see <code>glMatrixMode</code>).<br>
It is recommend to pout the projection matrix to the current <code>GL_PROJECTION</code> matrix and the model view matrix to the current <code>GL_MODELVIEW</code> matrix.<br>
Update the viewport rectangle (<code>glViewport</code>) and the projection matrix in the resize event callback (<code>resizeGL</code>). Set the model view matrix in <code>paintGL</code>: </p>

<pre class="lang-py prettyprint-override"><code>class mainWindow(QMainWindow):
    # [...]

    def setupUI(self):
        # [...]

        self.openGLWidget.paintGL  = self.paintGL
        self.openGLWidget.resizeGL = self.resizeGL

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        # update viewport
        glViewport(0, 0, self.width, self.height)
        # set projection matrix
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 50.0)    #set perspective?

    def paintGL(self):
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslatef(0, 0, -10)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(-90, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)    #Straight from the PyGame version, with 'self' inserted occasionally

        glBegin(GL_QUADS)    #tell GL to draw surfaces
        for surface in self.surfaces:
            x = 0
            for vertex in surface:
                x+=1
                glColor3fv(self.colors[x])
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing surfaces

        glBegin(GL_LINES)    #tell GL to draw lines
        for edge in self.edges:
            for vertex in edge:
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing lines.
</code>```

Body:
I am trying to piece example code for a PyGame PyOpenGL tutorial into example code for a PyQt5 QOpenGLWidget. The goal of this code is to set up a cube with one corner skewed upward in order to identify the angle of the camera. It works fine in PyGame, but there are several problems with the PyQt5 version:

First, the aspect ratio seems to be off.
Second, the window recalls paintGL every time I make it active again.
Third, most of the variables are not transferring the same in regards to glTranslatef and glRotatef.

The code I am using for PyGame:

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 2),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

colors = (
    (1,0,0),
    (0,1,0),
    (0,0,1),
    (0,1,0),
    (1,1,1),
    (0,1,1),
    (1,0,0),
    (0,1,0),
    (0,0,1),
    (1,0,0),
    (1,1,1),
    (0,1,1),
    )

surfaces = (
    (0,1,2,3),
    (3,2,7,6),
    (6,7,5,4),
    (4,5,1,0),
    (1,5,7,2),
    (4,0,3,6)
    )

def Cube():
    glBegin(GL_QUADS)
    for surface in surfaces:
        x = 0
        for vertex in surface:
            x+=1
            glColor3fv(colors[x])
            glVertex3fv(verticies[vertex])
    glEnd()

    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
    glTranslatef(0,0, -10)    #these two lines set the camera facing at the cube from the position 0, -10, 0.
    glRotatef(-90, 2, 0, 0)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    glTranslatef(-0.5,0,0)
                if event.key == pygame.K_RIGHT:
                    glTranslatef(0.5,0,0)

                if event.key == pygame.K_UP:
                    glTranslatef(0,1,0)
                if event.key == pygame.K_DOWN:
                    glTranslatef(0,-1,0)

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 4:
                    glTranslatef(0,0,1.0)

                if event.button == 5:
                    glTranslatef(0,0,-1.0)

        #glRotatef(1, 3, 1, 1)    #rotation code that was commented out.
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)
main()

The result:

The PyQt5 code:

import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import *

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

class mainWindow(QMainWindow):    #Main class.

    verticies = (
                 (1, -1, -1),
                 (1, 1, -1),
                 (-1, 1, -1),
                 (-1, -1, -1),
                 (1, -1, 2),
                 (1, 1, 1),
                 (-1, -1, 1),
                 (-1, 1, 1)
                )

    edges = (
             (0,1),
             (0,3),
             (0,4),
             (2,1),
             (2,3),
             (2,7),
             (6,3),
             (6,4),
             (6,7),
             (5,1),
             (5,4),
             (5,7)
            )

    colors = (
              (1,0,0),
              (0,1,0),
              (0,0,1),
              (0,1,0),
              (1,1,1),
              (0,1,1),
              (1,0,0),
              (0,1,0),
              (0,0,1),
              (1,0,0),
              (1,1,1),
              (0,1,1),
             )

    surfaces = (
                (0,1,2,3),
                (3,2,7,6),
                (6,7,5,4),
                (4,5,1,0),
                (1,5,7,2),
                (4,0,3,6)
               )

    def __init__(self):
        super(mainWindow, self).__init__()
        self.width = 700    #Variables used for the setting of the size of everything
        self.height = 600
        self.setGeometry(0, 0, self.width, self.height)    #Set the window size

    def setupUI(self):
        self.openGLWidget = QOpenGLWidget(self)    #Create the GLWidget
        self.openGLWidget.setGeometry(0, 0, self.width, self.height)    #Size it the same as the window.
        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(self.width, self.height)    #Resize GL's knowledge of the window to match the physical size?
        self.openGLWidget.paintGL = self.paintGL    #override the default function with my own?

    def paintGL(self):
        gluPerspective(45, self.width / self.height, 0.1, 50.0)    #set perspective?
        glTranslatef(0, 0, -2)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(-90, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)    #Straight from the PyGame version, with 'self' inserted occasionally

        glBegin(GL_QUADS)    #tell GL to draw surfaces
        for surface in self.surfaces:
            x = 0
            for vertex in surface:
                x+=1
                glColor3fv(self.colors[x])
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing surfaces

        glBegin(GL_LINES)    #tell GL to draw lines
        for edge in self.edges:
            for vertex in edge:
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing lines.

app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())

The result:

When I switch to another window, then switch back to the Qt window, the scene updates and paintGL is called again. Also, the cube appears to be squashed and the camera acts differently. What can I do to fix these?

Python 3.8
Windows 10

Body:
The OpenGL matrix operations (like gluPerspective, glTranslate, glRotate, ...) do not just set a matrix. The operations define a new matrix and multiply the current matrix by the new matrix. The causes that the matrix continuously and progressively changes, every time when paintGL is called.

The issue can be solved with ease, by loading the identity matrix by glLoadIdentity at the begin of paintGL::

class mainWindow(QMainWindow):
    # [...]

    def paintGL(self):
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 50.0)    #set perspective?
        glTranslatef(0, 0, -10)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(-90, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.

But Legacy OpenGL provides different matrices (see glMatrixMode).

It is recommend to pout the projection matrix to the current GL_PROJECTION matrix and the model view matrix to the current GL_MODELVIEW matrix.

Update the viewport rectangle (glViewport) and the projection matrix in the resize event callback (resizeGL). Set the model view matrix in paintGL:

class mainWindow(QMainWindow):
    # [...]

    def setupUI(self):
        # [...]

        self.openGLWidget.paintGL  = self.paintGL
        self.openGLWidget.resizeGL = self.resizeGL

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        # update viewport
        glViewport(0, 0, self.width, self.height)
        # set projection matrix
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 50.0)    #set perspective?

    def paintGL(self):
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslatef(0, 0, -10)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(-90, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)    #Straight from the PyGame version, with 'self' inserted occasionally

        glBegin(GL_QUADS)    #tell GL to draw surfaces
        for surface in self.surfaces:
            x = 0
            for vertex in surface:
                x+=1
                glColor3fv(self.colors[x])
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing surfaces

        glBegin(GL_LINES)    #tell GL to draw lines
        for edge in self.edges:
            for vertex in edge:
                glVertex3fv(self.verticies[vertex])
        glEnd()    #tell GL to stop drawing lines.


问:
Add libraries for static compilation CentOS 8
How do I install static versions of glibc on CentOS 8?

I am trying to compile a version of rsync using static linked libraries.

答:
How do I install static versions of glibc on CentOS 8

```<code># dnf search glibc
# dnf provides */libc.a
         // both commands will (also) reply: glibc-static
# dnf install glibc-static
</code>```

Note : glibc-static is in this repo: /etc/yum.repos.d/CentOS-PowerTools.repo

```<code># dnf config-manager --enable PowerTools
</code>```

Package list, "PowerTools" http://mirror.centos.org/centos/8/PowerTools/x86_64/os/Packages/

Example mirror, "PowerTools" http://mirror.centos.org/centos/8/PowerTools/x86_64/os/

Body:
How do I install static versions of glibc on CentOS 8

# dnf search glibc
# dnf provides */libc.a
         // both commands will (also) reply: glibc-static
# dnf install glibc-static

Note : glibc-static is in this repo: /etc/yum.repos.d/CentOS-PowerTools.repo

# dnf config-manager --enable PowerTools

Package list, "PowerTools" http://mirror.centos.org/centos/8/PowerTools/x86_64/os/Packages/

Example mirror, "PowerTools" http://mirror.centos.org/centos/8/PowerTools/x86_64/os/


问:
Android, Canvas and Screens
I think I've got quiet a common problem in regards to Android development, but cant seem to find the answer I'm looking for.

If I make a canvas on Photoshop 800x480px (240ppi) and make a logo within that canvas that is 282 x 121px, I cant understand why when I display the image it takes up 3/4 of the screen in my emulator with the same 800x480px.

The code I use to display the logo is the following

```<code>Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);

//in the onDraw
canvas.drawBitmap(logo, 0, 0, null);
</code>```

Thanks in advance!

Possible Solution

Not sure if this is the best way to do things and would appriciate any feedback, I came across this solution (typically when you've already posted a question :D ) was to code the image as follows:

```<code>BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;

//Load images
logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo, options);
</code>```

答:
The image was probably only taking up 3/4 of the screen in the emulator because of the pre-scaling android sometimes does.

Check out this article on how to handle multiple resolutions and screen sizes.

You could try placing the drawable into a 'res/drawable-mdpi/' directory or a 'res/drawable-ldpi/' to differentiate between medium density and low density screens. Another option is to place it in a 'res/drawable-nodpi/' directory to prevent any pre-scaling. I've even placed some images in the 'res/raw' folder to get the same effect.

However, if your current method works, go for it!

Title: Android, Canvas and Screens

Body:
I think I've got quiet a common problem in regards to Android development, but cant seem to find the answer I'm looking for.

If I make a canvas on Photoshop 800x480px (240ppi) and make a logo within that canvas that is 282 x 121px, I cant understand why when I display the image it takes up 3/4 of the screen in my emulator with the same 800x480px.

The code I use to display the logo is the following

Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);

//in the onDraw
canvas.drawBitmap(logo, 0, 0, null);

Thanks in advance!

Possible Solution

Not sure if this is the best way to do things and would appriciate any feedback, I came across this solution (typically when you've already posted a question :D ) was to code the image as follows:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;

//Load images
logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo, options);


问:
Nested JSON data via AJAX with jquery but getting undefined value
Javascript

JSON

Web Inspect

I have got an error message.
Uncaught ReferenceError: products is not defined.

```<code>$(document).ready(function(){
    $("div").on("click", "a", function(){
        var delivery_id = $(this).attr("id");
        $.ajax({
            url:"http://localhost:8888/dashboard/fetch_edit.php",
            method:"POST",
            data:{products:products},}
        });
    });
</code>```

JSON

```<code>
{
     "id": "2",
     "send_id": "10",
     "tracking_id": "TI-000000010",
     "user_id": "10",
     "username": "istiaqahmed",
     "email": "istiaqahmed121998@gmail.com",
     "phone": "0176430886",
     "company_name": "EVALY.COM.BD",
     "company_phone": "01747588386",
     "company_address": "Dhanmondi 28",
     "com_email": "evaly@gmail.com",
     "delivery_type": "Standard",
     "packing": "regular",
     "product_weight": "1",
     "preferred_time": "morning",
     "delivery_charge": "60",
     "customer_name": "Zenith Jhony",
     "to_address1": "75\/1 Jafrabad Pulpar Pabna House Goli",
     "to_phone": "01776065208",
     "to_zone": "Dhaka",
     "to_post_code": "1207",
     "date": "2020-01-09 23:26:10",
     "u_status": "Approve",
     "notes": "note",
     "products": [
          {
               "product_id": "1",
               "product_name": "shampoo",
               "product_quantity": "2",
               "product_price": "2333",
               "customer_send_id": "10"
          },
          {
                "product_id": "2",
               "product_name": "assf",
               "product_quantity": "1",
               "product_price": "232",
               "customer_send_id": "10"
          }
     ]
 }
</code>```

答:
Hope this help you.</p>

```<code>var products_obj = '{ "id": "2", "send_id": "10", "tracking_id": "TI-000000010", "user_id": "10", "username": "istiaqahmed", "email": "istiaqahmed121998@gmail.com", "phone": "0176430886", "company_name": "EVALY.COM.BD", "company_phone": "01747588386", "company_address": "Dhanmondi 28", "com_email": "evaly@gmail.com", "delivery_type": "Standard", "packing": "regular", "product_weight": "1", "preferred_time": "morning", "delivery_charge": "60", "customer_name": "Zenith Jhony", "to_address1": "75\/1 Jafrabad Pulpar Pabna House Goli", "to_phone": "01776065208", "to_zone": "Dhaka", "to_post_code": "1207", "date": "2020-01-09 23:26:10", "u_status": "Approve", "notes": "note", "products": [ { "product_id": "1", "product_name": "shampoo", "product_quantity": "2", "product_price": "2333", "customer_send_id": "10" }, { "product_id": "2", "product_name": "assf", "product_quantity": "1", "product_price": "232", "customer_send_id": "10" } ] }';
products_obj = JSON.parse(products_obj);
var products= products_obj.products;
console.log(products);

$(document).ready(function(){
    $("div").on("click", "a", function(){
        var delivery_id = $(this).attr("id");
        $.ajax({
            url:"http://localhost:8888/dashboard/fetch_edit.php",
            method:"POST",
            data:{products:products},}
        });
});
</code>```

Body:
Javascript

JSON

Web Inspect

I have got an error message.
Uncaught ReferenceError: products is not defined.

$(document).ready(function(){
    $("div").on("click", "a", function(){
        var delivery_id = $(this).attr("id");
        $.ajax({
            url:"http://localhost:8888/dashboard/fetch_edit.php",
            method:"POST",
            data:{products:products},}
        });
    });

JSON

{
     "id": "2",
     "send_id": "10",
     "tracking_id": "TI-000000010",
     "user_id": "10",
     "username": "istiaqahmed",
     "email": "istiaqahmed121998@gmail.com",
     "phone": "0176430886",
     "company_name": "EVALY.COM.BD",
     "company_phone": "01747588386",
     "company_address": "Dhanmondi 28",
     "com_email": "evaly@gmail.com",
     "delivery_type": "Standard",
     "packing": "regular",
     "product_weight": "1",
     "preferred_time": "morning",
     "delivery_charge": "60",
     "customer_name": "Zenith Jhony",
     "to_address1": "75\/1 Jafrabad Pulpar Pabna House Goli",
     "to_phone": "01776065208",
     "to_zone": "Dhaka",
     "to_post_code": "1207",
     "date": "2020-01-09 23:26:10",
     "u_status": "Approve",
     "notes": "note",
     "products": [
          {
               "product_id": "1",
               "product_name": "shampoo",
               "product_quantity": "2",
               "product_price": "2333",
               "customer_send_id": "10"
          },
          {
                "product_id": "2",
               "product_name": "assf",
               "product_quantity": "1",
               "product_price": "232",
               "customer_send_id": "10"
          }
     ]
 }

Body:
Hope this help you.

var products_obj = '{ "id": "2", "send_id": "10", "tracking_id": "TI-000000010", "user_id": "10", "username": "istiaqahmed", "email": "istiaqahmed121998@gmail.com", "phone": "0176430886", "company_name": "EVALY.COM.BD", "company_phone": "01747588386", "company_address": "Dhanmondi 28", "com_email": "evaly@gmail.com", "delivery_type": "Standard", "packing": "regular", "product_weight": "1", "preferred_time": "morning", "delivery_charge": "60", "customer_name": "Zenith Jhony", "to_address1": "75\/1 Jafrabad Pulpar Pabna House Goli", "to_phone": "01776065208", "to_zone": "Dhaka", "to_post_code": "1207", "date": "2020-01-09 23:26:10", "u_status": "Approve", "notes": "note", "products": [ { "product_id": "1", "product_name": "shampoo", "product_quantity": "2", "product_price": "2333", "customer_send_id": "10" }, { "product_id": "2", "product_name": "assf", "product_quantity": "1", "product_price": "232", "customer_send_id": "10" } ] }';
products_obj = JSON.parse(products_obj);
var products= products_obj.products;
console.log(products);

$(document).ready(function(){
    $("div").on("click", "a", function(){
        var delivery_id = $(this).attr("id");
        $.ajax({
            url:"http://localhost:8888/dashboard/fetch_edit.php",
            method:"POST",
            data:{products:products},}
        });
});