问:
ReactJS: onClick() sorting for dynamically rendered  elements
I am printing the data fetched from an API into a table, and I am facing some difficulties to sort the column values, alphabetically and numerically. If the columns data within the API consists of numerical values, i.e. 10.01, 333.01, 8.99 or 100.88, etc. to sort it ascending from 0 -> 100 on first click and on the second click descending 100 -> 0 and in the same logic for alphabetically values, i.e a-z && Z-A and reverse versa.

The function that I am familiar with onclick="sortTable(0)", doesn't function in the same way in React, as I used to code it in javaScript. Probably I am misleading the ES6 standard, but I am not sure.

Here is my code sample with onclick="sortTable(0)", but it's doesn't function well:

```<code>class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: [],
            clicked: false
        }

        this.handleClick = this.handleClick.bind( this );
    }

    handleClick()
    {
        this.setState( {
            clicked: true
        } );
    }

     sortTable( n )
{
            var table, columns, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById( "datagrid" );
            switching = true;
            //Set the sorting direction to ascending:
            dir = "asc";
            /*Make a loop that will continue until
            no switching has been done:*/
            while ( switching )
            {
                //start by saying: no switching is done:
                switching = false;
                columns = table.getElementsByTagName( "TH" );
                /*Loop through all table rows (except the
                first, which contains table headers):*/
                for ( i = 1; i < ( columns.length - 1 ); i++ )
                {
                    //start by saying there should be no switching:
                    shouldSwitch = false;
                    /*Get the two elements you want to compare,
                    one from current row and one from the next:*/
                    x = columns[i].getElementsByTagName( "TH" )[n];
                    y = columns[i + 1].getElementsByTagName( "TH" )[n];
                    /*check if the two rows should switch place,
                    based on the direction, asc or desc:*/
                    if ( dir == "asc" )
                    {
                        if ( x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    } else if ( dir == "desc" )
                    {
                        if ( x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                if ( shouldSwitch )
                {
                    /*If a switch has been marked, make the switch
                    and mark that a switch has been done:*/
                    rows[i].parentNode.insertBefore( rows[i + 1], rows[i] );
                    switching = true;
                    //Each time a switch is done, increase this count by 1:
                    switchcount++;
                } else
                {
                    /*If no switching has been done AND the direction is "asc",
                    set the direction to "desc" and run the while loop again.*/
                    if ( switchcount == 0 && dir == "asc" )
                    {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (
            <div id="container" className="container">
                <h1>Final Table with React JS</h1>
                <table className="datagrid">
                    <thead>
                        <tr> {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( <th onClick={this.handleClick}>{column}</th> )
                            }
                            )
                        }
                        </tr>
                    </thead>
                    <tbody> {
                        this.state.rows.map( row => (
                            <tr>{row.map( cell => (
                                <td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
                            ) )}
                            </tr>
                        ) )
                    }
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
</code>```

You are welcome to contribute directly to my Repo: Fetching API data into a table

My example, right after the onclick="sortTable(0)" has been used, doesn't htow any errors in the console, but it prints the same result. I guess I am not handling correct the {column}	 elements.

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function the onClick event at all, so that I can't debug the sor functionality either.

Any suggestions will be appreciated!

答:
I don't see where your code actually calls the sortTable method, but I believe there is a larger issue here.

You shouldn't be doing DOM manipulation manually unless you have a very good reason to. Instead, rely on React to manipulate the DOM, it's why you are using it. You are responsible for describing a Component's display based on its internal state and its props, which is what the render() function should reflect. In your case, the order of the rows would depend on the current sort column and the direction of the sort. So, you could add additional state for sort, which might be an object that includes the column to sort and direction of the sort. Whenever a column is clicked, you update sort, which will cause your component to re-render. Then, your render() function would take the current sort state into consideration when displaying the rows.

So to render the rows, you might write:

```<code>renderRows() {
  const sortFn = getSortFunction(this.state.sort); // defined elsewhere

  // shallow copy so we don't mutate the state
  return [ ...this.state.rows ]
    .sort(sortFn)
    .map((row, i) => (
      <tr key={i}>
        { row.map((cell, j) => <td key={j}>{ cell }</td>) }
      </tr>
    ));
}

render() {
  return (
    <table>
      <thead>{ renderHeader() }</thead>
      <tbody>{ renderRows() }</tbody>
    </table>
  );
}
</code>```

Also, when rendering a React app, the ReactDOM.render() call replaces the content of the DOM element with the React element you provide. It is common practice to have a
 used as the app container, then replace its content with your app.

```<code>ReactDOM.render(<App />, document.getElementById("root"));
</code>```

Title: ReactJS: onClick() sorting for dynamically rendered <th> elements

Body:
I am printing the data fetched from an API into a table, and I am facing some difficulties to sort the column values, alphabetically and numerically. If the columns data within the API consists of numerical values, i.e. 10.01, 333.01, 8.99 or 100.88, etc. to sort it ascending from 0 -> 100 on first click and on the second click descending 100 -> 0 and in the same logic for alphabetically values, i.e a-z && Z-A and reverse versa.

The function that I am familiar with onclick="sortTable(0)", doesn't function in the same way in React, as I used to code it in javaScript. Probably I am misleading the ES6 standard, but I am not sure.

Here is my code sample with onclick="sortTable(0)", but it's doesn't function well:

class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: [],
            clicked: false
        }

        this.handleClick = this.handleClick.bind( this );
    }

    handleClick()
    {
        this.setState( {
            clicked: true
        } );
    }

     sortTable( n )
{
            var table, columns, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById( "datagrid" );
            switching = true;
            //Set the sorting direction to ascending:
            dir = "asc";
            /*Make a loop that will continue until
            no switching has been done:*/
            while ( switching )
            {
                //start by saying: no switching is done:
                switching = false;
                columns = table.getElementsByTagName( "TH" );
                /*Loop through all table rows (except the
                first, which contains table headers):*/
                for ( i = 1; i < ( columns.length - 1 ); i++ )
                {
                    //start by saying there should be no switching:
                    shouldSwitch = false;
                    /*Get the two elements you want to compare,
                    one from current row and one from the next:*/
                    x = columns[i].getElementsByTagName( "TH" )[n];
                    y = columns[i + 1].getElementsByTagName( "TH" )[n];
                    /*check if the two rows should switch place,
                    based on the direction, asc or desc:*/
                    if ( dir == "asc" )
                    {
                        if ( x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    } else if ( dir == "desc" )
                    {
                        if ( x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                if ( shouldSwitch )
                {
                    /*If a switch has been marked, make the switch
                    and mark that a switch has been done:*/
                    rows[i].parentNode.insertBefore( rows[i + 1], rows[i] );
                    switching = true;
                    //Each time a switch is done, increase this count by 1:
                    switchcount++;
                } else
                {
                    /*If no switching has been done AND the direction is "asc",
                    set the direction to "desc" and run the while loop again.*/
                    if ( switchcount == 0 && dir == "asc" )
                    {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (

Final Table with React JS

 {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( {column}	 )
                            }
                            )
                        }

 {
                        this.state.rows.map( row => (

{row.map( cell => (
                                {typeof cell === 'number' ? cell.toFixed( 2 ) : cell}
                            ) )}

                        ) )
                    }

        )
    }
}

ReactDOM.render(
<App />
, document.querySelector( 'body' ) );

You are welcome to contribute directly to my Repo: Fetching API data into a table

My example, right after the onclick="sortTable(0)" has been used, doesn't htow any errors in the console, but it prints the same result. I guess I am not handling correct the {column}	 elements.

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function the onClick event at all, so that I can't debug the sor functionality either.

Any suggestions will be appreciated!

Body:
I don't see where your code actually calls the sortTable method, but I believe there is a larger issue here.

You shouldn't be doing DOM manipulation manually unless you have a very good reason to. Instead, rely on React to manipulate the DOM, it's why you are using it. You are responsible for describing a Component's display based on its internal state and its props, which is what the render() function should reflect. In your case, the order of the rows would depend on the current sort column and the direction of the sort. So, you could add additional state for sort, which might be an object that includes the column to sort and direction of the sort. Whenever a column is clicked, you update sort, which will cause your component to re-render. Then, your render() function would take the current sort state into consideration when displaying the rows.

So to render the rows, you might write:

renderRows() {
  const sortFn = getSortFunction(this.state.sort); // defined elsewhere

  // shallow copy so we don't mutate the state
  return [ ...this.state.rows ]
    .sort(sortFn)
    .map((row, i) => (
      <tr key={i}>
        { row.map((cell, j) => <td key={j}>{ cell }</td>) }
      </tr>
    ));
}

render() {
  return (
    <table>
      <thead>{ renderHeader() }</thead>
      <tbody>{ renderRows() }</tbody>
    </table>
  );
}

Also, when rendering a React app, the ReactDOM.render() call replaces the content of the DOM element with the React element you provide. It is common practice to have a <div id="root"> used as the app container, then replace its content with your app.

ReactDOM.render(<App />, document.getElementById("root"));


来源: stackexchange

问:
How can you check if a type is Optional in Swift?
How can you check if a type is Optional in Swift?

Say I have a variable of type PartialKeyPath where:

```<code>struct Foo {
    let bar: String
    let baz: String?
}

typealias Property<Root> = (key: PartialKeyPath<Root>, value: Any?)
typealias Properties<Root> = [Property<Root>]
</code>```

Now say I iterate thru an instance of Properties:

```<code>properties.forEach { prop in
    let valueType1 = type(of: prop.key).valueType
    let valueType2 = type(of: value)

    ...
</code>```

How can I check here whether valueType1 is Optional<valueType2>, or whether it is Optional of any other flavor for that matter?

So far the only way I’ve found is really ugly...

答:
could you use a mirror reflecting Any and check displayStyle is optional?.

```<code>func isOptional(any:Any) -> Bool {

  let mirror = Mirror(reflecting: any)
  if mirror.displayStyle == .Optional {
      return true
  } else {
      return false
  }

}
</code>```

More on mirror display style:
https://developer.apple.com/documentation/swift/mirror.displaystyle

ContentLicense: CC BY-SA 3.0

Body:
How can you check if a type is Optional in Swift?

Say I have a variable of type PartialKeyPath where:

struct Foo {
    let bar: String
    let baz: String?
}

typealias Property<Root> = (key: PartialKeyPath<Root>, value: Any?)
typealias Properties<Root> = [Property<Root>]

Now say I iterate thru an instance of Properties:

properties.forEach { prop in
    let valueType1 = type(of: prop.key).valueType
    let valueType2 = type(of: value)

    ...

How can I check here whether valueType1 is Optional<valueType2>, or whether it is Optional of any other flavor for that matter?

So far the only way I’ve found is really ugly...

Body:
could you use a mirror reflecting Any and check displayStyle is optional?.

func isOptional(any:Any) -> Bool {

  let mirror = Mirror(reflecting: any)
  if mirror.displayStyle == .Optional {
      return true
  } else {
      return false
  }

}

More on mirror display style:
https://developer.apple.com/documentation/swift/mirror.displaystyle


问:
Support for object tags with embedded ActiveX in Mozilla/Safari
I am using an object tag to load ActiveX extension controls like so:

```<code><object name="controlcontainer"
    width=320
    height=240
    codebase="./library.cab#version=1,2">
</object>
</code>```

This works fine in IE, but we are looking into creating a port of our application for the iPad. Is there any way we can load ActiveX controls on the Mozilla/Safari platform?

Thanks,

答:
ActiveX controls do not and will not ever work on Mac, the iPad, or any other non-microsoft platform. There is currently no method that I know of for creating a browser plugin of any kind on an iPad, though if there were it would be either a WebKit plugin or a NPAPI plugin.

If you want to port your application to work on firefox, chrome, etc and work on Mac, you may want to look at the FireBreath project, but since Apple doesn't allow such software on the iPad you'll need to approach it a different way there.

ContentLicense: CC BY-SA 2.5

Body:
I am using an object tag to load ActiveX extension controls like so:

<object name="controlcontainer"
    width=320
    height=240
    codebase="./library.cab#version=1,2">
</object>

This works fine in IE, but we are looking into creating a port of our application for the iPad. Is there any way we can load ActiveX controls on the Mozilla/Safari platform?

Thanks,


问:
For loop in python - beginner
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between

```<code>years = [n[1] for n in data]
</code>```

and

```<code>for n in data:
         years = n[1]
</code>```

here is the rest of the body

```<code>for m in years:
    if m not in year_counts:
        year_counts[m] = 0
    year_counts[m] += 1

print(year_counts)
</code>```

So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.

答:
In

```<code>for n in data:
         years = n[1]
</code>```

years will be replaced for each n1.  The "random" entry you are seeing is probably the second letter of the last entry in data.

You could do this instead to match the comprehension:

```<code>years = list()
data = ['a1', 'a2', 'a3', 'a4']
for n in data:
  years.append(n[1])  # years = ['1', '2', '3', '4']
</code>```

but

```<code>years = [n[1] for n in data]
</code>```

will tend to be faster overall.

For your overall script, you might consider a using map.

Title: For loop in python - beginner

Body:
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between

years = [n[1] for n in data]

and

for n in data:
         years = n[1]

here is the rest of the body

for m in years:
    if m not in year_counts:
        year_counts[m] = 0
    year_counts[m] += 1

print(year_counts)

So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.

Body:
In

for n in data:
         years = n[1]

years will be replaced for each n1.  The "random" entry you are seeing is probably the second letter of the last entry in data.

You could do this instead to match the comprehension:

years = list()
data = ['a1', 'a2', 'a3', 'a4']
for n in data:
  years.append(n[1])  # years = ['1', '2', '3', '4']

but

years = [n[1] for n in data]

will tend to be faster overall.

For your overall script, you might consider a using map.


问:
How to pass the curl --insecure alternative when using R?
How can I download this file with R and save it to disk?

I have managed to download it already using curl on the command line by adding the --insecure flag to it. But I cannot figure out how to do it in R.

This is the command line way:

```<code>curl https://www.stf.jus.br/arquivo/djEletronico/DJE_20171123_266.pdf --insecure --output ~/Desktop/test2.pdf
</code>```

答:
You can use the curl library:

```<code>library(curl)

URL <- "https://www.stf.jus.br/arquivo/djEletronico/DJE_20171123_266.pdf"
h <- new_handle()
handle_setopt(h, ssl_verifyhost = 0, ssl_verifypeer=0)

curl_download(url=URL, "file_test2.pdf", handle = h)
</code>```

Body:
How can I download this file with R and save it to disk?

I have managed to download it already using curl on the command line by adding the --insecure flag to it. But I cannot figure out how to do it in R.

This is the command line way:

curl https://www.stf.jus.br/arquivo/djEletronico/DJE_20171123_266.pdf --insecure --output ~/Desktop/test2.pdf

Body:
You can use the curl library:

library(curl)

URL <- "https://www.stf.jus.br/arquivo/djEletronico/DJE_20171123_266.pdf"
h <- new_handle()
handle_setopt(h, ssl_verifyhost = 0, ssl_verifypeer=0)

curl_download(url=URL, "file_test2.pdf", handle = h)


问:
Domain validation using the notification pattern
Historically I have performed validation of my objects within their constructors and thrown an exception when validation fails.  For example:

```<code>class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $value;

    public function __construct(string $name)
    {
        if (!$this->isValidNameLength($name)) {
            throw new InvalidArgumentException(
                sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
            );
        }
        $this->value = $name;
    }

    public function changeName(string $name)
    {
        return new self($name);
    }

    private function isValidNameLength(string $name)
    {
        return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
    }
}
</code>```

Whilst I like this approach as my object is responsible for enforcing its consistency and ensuring it is always-valid, I've never been overly enthusiastic about the use of exceptions.  Whilst there are people who would argue for and against the use of exceptions as above, it does limit the number of validation messages I can return when performing validation over multiple objects.  For example:

```<code>class Room
{
    private $name;

    private $description;

    public function __construct(Name $name, Description $description)
    {
        $this->name = $name;
        $this->description = $description;
    }
}

class Name
{
    public function __construct(string $name)
    {
        // do some validation
    }
}

class Description
{
    public function __construct(string $description)
    {
        // do some validation
    }
}
</code>```

Should both Name and Description fail validation, I want to be able to return the failure messages for both objects, not just a single exception from whichever object failed first.

Having done some reading on the notification pattern I feel this would be a good fit for my scenario.  Where I become stuck is how I perform validation and prevent my object from entering an invalid state should validation fail.

```<code>class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $notification;

    private $value;

    public function __construct(string $name, Notification $notification)
    {
        $this->notification = $notification;
        $this->setName($name);
    }

    private function setName(string $name)
    {
        if ($this->isValidNameLength($name)) {
            $this->value = $name;
        }
    }

    private function isValidNameLength(string $name)
    {
        if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
            $this->notification->addError('NAME_LENGTH_INVALID');
            return false;
        }
        return true;
    }

    public function hasError()
    {
        return $this->notification->hasError();
    }

    public function getError()
    {
        return $this->notification->getError();
    }
}
</code>```

I have a few concerns about the above:

If validation fails, then the object is still constructed but its $value is null which is not a valid state.

After creating a Name, I must remember to call hasError to determine if a validation error has occured.

I am now pebbling my domain objects with hasError/getError functions which I'm not sure is good practice.

Is there a piece of this puzzle I am missing?  How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?

答:
Well, you pretty much did it already but if you share all your validation in one validate() method, you could just call it before proceeding in your business logic.

So something like

```<code>if (model.validate())
{
   // You can safely proceed
}

After this you can for example throw an exception so you will know that you have an object in an invalid state.
</code>```

Body:
Historically I have performed validation of my objects within their constructors and thrown an exception when validation fails.  For example:

class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $value;

    public function __construct(string $name)
    {
        if (!$this->isValidNameLength($name)) {
            throw new InvalidArgumentException(
                sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
            );
        }
        $this->value = $name;
    }

    public function changeName(string $name)
    {
        return new self($name);
    }

    private function isValidNameLength(string $name)
    {
        return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
    }
}

Whilst I like this approach as my object is responsible for enforcing its consistency and ensuring it is always-valid, I've never been overly enthusiastic about the use of exceptions.  Whilst there are people who would argue for and against the use of exceptions as above, it does limit the number of validation messages I can return when performing validation over multiple objects.  For example:

class Room
{
    private $name;

    private $description;

    public function __construct(Name $name, Description $description)
    {
        $this->name = $name;
        $this->description = $description;
    }
}

class Name
{
    public function __construct(string $name)
    {
        // do some validation
    }
}

class Description
{
    public function __construct(string $description)
    {
        // do some validation
    }
}

Should both Name and Description fail validation, I want to be able to return the failure messages for both objects, not just a single exception from whichever object failed first.

Having done some reading on the notification pattern I feel this would be a good fit for my scenario.  Where I become stuck is how I perform validation and prevent my object from entering an invalid state should validation fail.

class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $notification;

    private $value;

    public function __construct(string $name, Notification $notification)
    {
        $this->notification = $notification;
        $this->setName($name);
    }

    private function setName(string $name)
    {
        if ($this->isValidNameLength($name)) {
            $this->value = $name;
        }
    }

    private function isValidNameLength(string $name)
    {
        if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
            $this->notification->addError('NAME_LENGTH_INVALID');
            return false;
        }
        return true;
    }

    public function hasError()
    {
        return $this->notification->hasError();
    }

    public function getError()
    {
        return $this->notification->getError();
    }
}

I have a few concerns about the above:

If validation fails, then the object is still constructed but its $value is null which is not a valid state.

After creating a Name, I must remember to call hasError to determine if a validation error has occured.

I am now pebbling my domain objects with hasError/getError functions which I'm not sure is good practice.

Is there a piece of this puzzle I am missing?  How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?

Body:
Well, you pretty much did it already but if you share all your validation in one validate() method, you could just call it before proceeding in your business logic.

So something like

if (model.validate())
{
   // You can safely proceed
}

After this you can for example throw an exception so you will know that you have an object in an invalid state.


问:
Tox WARNING:test command found but not installed in testenv
I am using tox for my project.

Here is my tox.ini file:

```<code>[tox]
envlist =
    py27,
    lint,
    coverage

skipsdist = True

[testenv:py27]
deps = -rrequirements.txt
commands = python -m unittest discover -s ./tests

[testenv:coverage]
commands =
    coverage run --source=tests -m unittest discover -s tests/
    coverage html
    coverage report

[testenv:lint]
commands = pylint ./foo
</code>```

whenever I run tox, everything is getting executed which basically is linting, coverage.

but Tox is displaying warning for everything.

```<code>WARNING:test command found but not installed in testenv
Maybe you forgot to specify a dependency? See also the whitelist_externals envconfig setting.
</code>```

Everything succeeds, but it is still displaying warning and errors. Can anyone tell me to what I am doing wrong?

My requirements.txt file is this:

```<code>requests==2.18.4
JsonForm==0.0.2
jsonify==0.5
jsonschema==2.6.0
JsonSir==0.0.2
python-dateutil==1.5
DateTime==4.2
urllib3==1.22
contextlib2==0.5.5
mock==2.0.0
patch==1.16
</code>```

答:
Programs that you use in commands must either be installed in tox' virtual environment or whitelisted:

```<code>[tox]
envlist =
    py27,
    lint,
    coverage

skipsdist = True

[testenv:py27]
deps = -rrequirements.txt
whitelist_externals = python
commands = python -m unittest discover -s ./tests

[testenv:coverage]
whitelist_externals = coverage
commands =
    coverage run --source=tests -m unittest discover -s tests/
    coverage html
    coverage report

[testenv:lint]
whitelist_externals = pylint
commands = pylint ./foo
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using tox for my project.

Here is my tox.ini file:

[tox]
envlist =
    py27,
    lint,
    coverage

skipsdist = True

[testenv:py27]
deps = -rrequirements.txt
commands = python -m unittest discover -s ./tests

[testenv:coverage]
commands =
    coverage run --source=tests -m unittest discover -s tests/
    coverage html
    coverage report

[testenv:lint]
commands = pylint ./foo

whenever I run tox, everything is getting executed which basically is linting, coverage.

but Tox is displaying warning for everything.

WARNING:test command found but not installed in testenv
Maybe you forgot to specify a dependency? See also the whitelist_externals envconfig setting.

Everything succeeds, but it is still displaying warning and errors. Can anyone tell me to what I am doing wrong?

My requirements.txt file is this:

requests==2.18.4
JsonForm==0.0.2
jsonify==0.5
jsonschema==2.6.0
JsonSir==0.0.2
python-dateutil==1.5
DateTime==4.2
urllib3==1.22
contextlib2==0.5.5
mock==2.0.0
patch==1.16

Body:
Programs that you use in commands must either be installed in tox' virtual environment or whitelisted:

[tox]
envlist =
    py27,
    lint,
    coverage

skipsdist = True

[testenv:py27]
deps = -rrequirements.txt
whitelist_externals = python
commands = python -m unittest discover -s ./tests

[testenv:coverage]
whitelist_externals = coverage
commands =
    coverage run --source=tests -m unittest discover -s tests/
    coverage html
    coverage report

[testenv:lint]
whitelist_externals = pylint
commands = pylint ./foo


问:
Change the output directory for .css and .js in Semantic UI's gulp tasks
I changed the output paths in my semantic.json which is working fine. However I would like the following files to be built in ../../static/css (../../static/js):

semantic.css

semantic.js

semantic.min.css

semantic.min.js

What do I have to change in order to achieve this?

File content:

```<code>{
  "base": "semantic/",
  "paths": {
    "source": {
      "config": "src/theme.config",
      "definitions": "src/definitions/",
      "site": "src/site/",
      "themes": "src/themes/"
    },
    "output": {
      "packaged": "../static/",
      "uncompressed": "../static/components/",
      "compressed": "../static/components/",
      "themes": "../static/themes/"
    },
    "clean": "../static/"
  },
  "permission": false,
  "autoInstall": false,
  "rtl": false,
  "components": [
    /* Components come here... */
  ],
  "version": "2.2.13"
}
</code>```

答:
Changing the output directories in the Semantic.json didn't work for me, but changing it in semantic/tasks/config/defaults.js worked. I don't know why or if that's good, but the files have been created correctly now.

As to your problem with separating CSS and JS:
Here (https://github.com/Semantic-Org/Semantic-UI/issues/2221) it says:

JS and CSS files are not set up to have separate output directories in
  the current build system.

As of July 2016 there was no solution yet.

Body:
I changed the output paths in my semantic.json which is working fine. However I would like the following files to be built in ../../static/css (../../static/js):

semantic.css

semantic.js

semantic.min.css

semantic.min.js

What do I have to change in order to achieve this?

File content:

{
  "base": "semantic/",
  "paths": {
    "source": {
      "config": "src/theme.config",
      "definitions": "src/definitions/",
      "site": "src/site/",
      "themes": "src/themes/"
    },
    "output": {
      "packaged": "../static/",
      "uncompressed": "../static/components/",
      "compressed": "../static/components/",
      "themes": "../static/themes/"
    },
    "clean": "../static/"
  },
  "permission": false,
  "autoInstall": false,
  "rtl": false,
  "components": [
    /* Components come here... */
  ],
  "version": "2.2.13"
}


问:
Is there a way to automatically schedule the bootup of a Lightsail instance every 3 months?
I'm looking to automatically renew my SSL certificates for a website I'm hosting on GitLab pages using certbot auto. I already have this working, but I have to keep my Lightsail instance running continuously.

I'm just looking for an automatic way to boot up my Lightsail instance every 3 months, and once booted run a little script, and then power down again. At the moment it's costing me $5 month, and I'm only using it for a few minutes each time.

Is there a way to automatically schedule the bootup of a Lightsail instance every 3 months?

答:
There are two options I can think of. There may be more.

AWS Data Pipeline: Schedule a shell activity every 3 months and choose a micro instance. Specify the AWS CLI commands to start your instance and have your instance send stop instance command once it is done with its work. Cost: 1 hour of micro instance.

AWS Lambda(Preferred): Schedule a Lambda event to start your instance every 3 months. Specify the AWS CLI commands to start your instance and have your instance send stop instance command once it is done with its work. Cost: Nothing (likely to be within free limits)

aws lightsail start-instance

Starts a specific Amazon Lightsail instance from a stopped state. To
  restart an instance, use the reboot instance operation.

In my opinion, installing an agent on your instance is an overkill just to send a command.


问:
Equation (expression) parser with precedence?
I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis.

Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis.

So right now "1+11*5" returns 60, not 56 as one might expect.

While this is suitable for the current project, I want to have a general purpose routine I can use for later projects.

Edited for clarity:

What is a good algorithm for parsing equations with precedence?

I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code.

Grammar:

I don't understand the grammar question - I've written this by hand.  It's simple enough that I don't see the need for YACC or Bison.  I merely need to calculate strings with equations such as "2+3 * (42/13)".

Language:

I'm doing this in C, but I'm interested in an algorithm, not a language specific solution.  C is low level enough that it'll be easy to convert to another language should the need arise.

Code Example

I posted the test code for the simple expression parser I was talking about above.  The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project.  It's in the original verbose form, and should be readily understandable.  If I do anything further with it in terms of operator precedence, I'll probably choose the macro hack because it matches the rest of the program in simplicity.  If I ever use this in a real project, though, I'll be going for a more compact/speedy parser.

Related question

Smart design of a math parser?

-Adam

答:
The shunting yard algorithm is the right tool for this. Wikipedia is really confusing about this, but basically the algorithm works like this:

Say, you want to evaluate 1 + 2 * 3 + 4. Intuitively, you "know" you have to do the 2 * 3 first, but how do you get this result? The key is to realize that when you're scanning the string from left to right, you will evaluate an operator when the operator that follows it has a lower (or equal to) precedence. In the context of the example, here's what you want to do:

Look at: 1 + 2, don't do anything.

Now look at 1 + 2 * 3, still don't do anything.

Now look at 1 + 2 * 3 + 4, now you know that 2 * 3 has to to be  evaluated because the next operator has lower precedence.

How do you implement this?

You want to have two stacks, one for numbers, and another for operators. You push numbers onto the stack all the time. You compare each new operator with the one at the top of the stack, if the one on top of the stack has higher priority, you pop it off the operator stack, pop the operands off the number stack, apply the operator and push the result onto the number stack. Now you repeat the comparison with the top of stack operator.

Coming back to the example, it works like this:

N = [ ]
Ops = [ ]

Read 1. N = [1], Ops = [ ]

Read +. N = [1], Ops = [+]

Read 2. N = [1 2], Ops = [+]

Read *. N = [1 2], Ops = [+ *]

Read 3. N = [1 2 3], Ops = [+ *]

Read +. N = [1 2 3], Ops = [+ *]

Pop 3, 2 and execute 2*3, and push result onto N. N = [1 6], Ops = [+]

+ is left associative, so you want to pop 1, 6 off as well and execute the +. N = [7], Ops = [].

Finally push the [+] onto the operator stack. N = [7], Ops = [+].

Read 4. N = [7 4]. Ops = [+].

You're run out off input, so you want to empty the stacks now. Upon which you will get the result 11.

There, that's not so difficult, is it? And it makes no invocations to any grammars or parser generators.

OwnerDisplayName: Adam Davis

LastEditorDisplayName: John Millikin

OwnerDisplayName: Pramod


问:
How do I fix this simple CSS floating issue in IE?
I've got four div elements floated to the left. The third div is cleared.

In Firefox and Chrome the elements are positioned as expected: The first and second divs are adjacent to each other and are above the third and fourth divs which are also adjacent to each other.

IE7 on the other hand places the fourth div adjacent to the first and second divs with the third div below.

I know I can fix it by adding a br element after the second div but I'd rather not edit the markup if I don't have to. Is there a more elegant way of fixing the problem?

I've been trying to Google for a fix for a while now but haven't found one, which is rather surprising considering how elementary the problem seems. Perhaps I'm missing something obvious, is there a reference site that lists simple CSS issues like this one or am I just ignorant about basic CSS?

Edit: I've made the sample code slightly more complex after Nazgulled "solved" the problem (see the comments). There are now four divs instead of three and the third div is cleared instead of the second.

Here is the complete source code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>IE Float Test</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <style type="text/css">
            div
            {
                width: 100px;
                height: 100px;
                color: white;
                font-size: 3em;
                float: left;
            }

            #divone
            {
                background-color: red;
            }

            #divtwo
            {
                background-color: blue;
            }

            #divthree
            {
                background-color: green;
                clear: both;
            }

            #divfour
            {
                background-color: purple;
            }
        </style>
    </head>
    <body>
        <div id="divone">one</div>
        <div id="divtwo">two</div>
        <div id="divthree">three</div>
        <div id="divfour">four</div>
    </body>
</html>
</code>```

Here is what is looks like in Chrome:

Here is what is looks like in IE7:

答:
Try adding:

```<code>display:inline-block;
</code>```

in #divtwo.  If that works, I would of course add some conditional commenting for IE7

OwnerDisplayName: brianpeiris

Body:
I've got four div elements floated to the left. The third div is cleared.

In Firefox and Chrome the elements are positioned as expected: The first and second divs are adjacent to each other and are above the third and fourth divs which are also adjacent to each other.

IE7 on the other hand places the fourth div adjacent to the first and second divs with the third div below.

I know I can fix it by adding a br element after the second div but I'd rather not edit the markup if I don't have to. Is there a more elegant way of fixing the problem?

I've been trying to Google for a fix for a while now but haven't found one, which is rather surprising considering how elementary the problem seems. Perhaps I'm missing something obvious, is there a reference site that lists simple CSS issues like this one or am I just ignorant about basic CSS?

Edit: I've made the sample code slightly more complex after Nazgulled "solved" the problem (see the comments). There are now four divs instead of three and the third div is cleared instead of the second.

Here is the complete source code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>IE Float Test</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

one

two

three

four

Here is what is looks like in Chrome:

Here is what is looks like in IE7:

LastEditorDisplayName: brianpeiris

Body:
Try adding:

display:inline-block;

in #divtwo.  If that works, I would of course add some conditional commenting for IE7

OwnerDisplayName: GregD


问:
Shiny CSS not work for fonts
I have the following css in which I set the background and font:

```<code>    .my_style_1{  background-image:url(field.jpg);
                  background-repeat: no-repeat;
                  background-size: cover;
                  height:950px;
                  font-size: 1.5em;
                  font-family:Arial, Helvetica, sans-serif; ;
                  font-weight:500;
                  color: rgb(255,255,255)}
</code>```

and in ui.R I am using the following:

```<code>    fluidRow(
              box(width=12,
                  class="my_style_1",
                  div(br(),h1("Travel Diary"),style="position:relative;right:150px;text-align: center;")
              )
</code>```

My problem now is it seems like only the background css is working- not matter how I changed the font size it didnt work! However I did observe that when I increased the font size- the br() height increases but i don't know what is going wrong here.

答: Okay I figured it out. I used the wrong tag h1. Once I changed it to p it actuallly worked.

Title: Shiny CSS not work for fonts

Body:
I have the following css in which I set the background and font:

    .my_style_1{  background-image:url(field.jpg);
                  background-repeat: no-repeat;
                  background-size: cover;
                  height:950px;
                  font-size: 1.5em;
                  font-family:Arial, Helvetica, sans-serif; ;
                  font-weight:500;
                  color: rgb(255,255,255)}

and in ui.R I am using the following:

    fluidRow(
              box(width=12,
                  class="my_style_1",
                  div(br(),h1("Travel Diary"),style="position:relative;right:150px;text-align: center;")
              )

My problem now is it seems like only the background css is working- not matter how I changed the font size it didnt work! However I did observe that when I increased the font size- the br() height increases but i don't know what is going wrong here.


问:
"Permission denied" using PostgreSQL COPY in Travis-CI
I'm using travis-ci.org to test a Node.js module.
It uses the latest pg package to access a PostgreSQL database.

The integration tests need to use the Postgres copy command (from within a transaction... not psql's \copy) to populate a temporary table with some CSV data.
Everything passes locally... but running on Travis-CI I'm hitting:

```<code>"COPY some_table(column_a,column_b) FROM
'/home/travis/build/my_org/my_repo/test/fixtures/some_file.csv' CSV HEADER;"
{ error: could not open file
"/home/travis/build/my_org/my_repo/test/fixtures/some_file.csv" for reading:
Permission denied
    at Connection.parseE
(/home/travis/build/my_org/my_repo/node_modules/pg/lib/connection.js:567:11)
    at Connection.parseMessage   name: 'error',
...
</code>```

So a file Permission denied is the thing. My noob Linux skills tell me the file at that location exists. I've tried chmoding it to 777, but that didn't have any effect.

I'm connecting to Postgres on Travis with the string:

```<code>postgres://postgres:postgres@localhost:5432
</code>```

And all's well with that.
One thing, I do need PostgreSQL V9.6, so my .travis.yml file looks like:

```<code>language: node_js

node_js:
  - "6"

services:
  - postgresql

addons:
  postgresql: "9.6"

sudo: false
dist: trusty
</code>```

...which has worked great in the past, but this is the first time I've ever had to use copy.

I guess it's something to do with whatever user Postgres is running as somehow?

Any help very gratefully received!

Tim

答:
I actually ran into this issue when I was working on an inherited code base which was using the old Travis infrastructure (based on Ubuntu Precise) and wanted to update it to Trusty.

The Precise-based image had no problem reading a file from the travis home directory - maybe the PostgreSQL server was running as the travis user, not as postgres, but on Trusty this was not the case and I got this error.

Using chmod on the file itself is not enough, the server still can't read from the travis home directory. So you could create a file using mktemp, copy your file to it, change those permissions to 666 using chmod. Now you're able to read it in using PostgreSQLs COPY FROM.

Body:
I'm using travis-ci.org to test a Node.js module.
It uses the latest pg package to access a PostgreSQL database.

The integration tests need to use the Postgres copy command (from within a transaction... not psql's \copy) to populate a temporary table with some CSV data.
Everything passes locally... but running on Travis-CI I'm hitting:

"COPY some_table(column_a,column_b) FROM
'/home/travis/build/my_org/my_repo/test/fixtures/some_file.csv' CSV HEADER;"
{ error: could not open file
"/home/travis/build/my_org/my_repo/test/fixtures/some_file.csv" for reading:
Permission denied
    at Connection.parseE
(/home/travis/build/my_org/my_repo/node_modules/pg/lib/connection.js:567:11)
    at Connection.parseMessage   name: 'error',
...

So a file Permission denied is the thing. My noob Linux skills tell me the file at that location exists. I've tried chmoding it to 777, but that didn't have any effect.

I'm connecting to Postgres on Travis with the string:

postgres://postgres:postgres@localhost:5432

And all's well with that.
One thing, I do need PostgreSQL V9.6, so my .travis.yml file looks like:

language: node_js

node_js:
  - "6"

services:
  - postgresql

addons:
  postgresql: "9.6"

sudo: false
dist: trusty

...which has worked great in the past, but this is the first time I've ever had to use copy.

I guess it's something to do with whatever user Postgres is running as somehow?

Any help very gratefully received!

Tim


问:
Configuring Oracle XStream
I'm trying to configure Oracle XStream out by official documentation

So, shortly, I'm connecting as sysdba

```<code>    sqlplus / as sysdba
</code>```

Then executing commands create create CDB user and give him privileges

```<code>    > CREATE TABLESPACE xstream_tbs DATAFILE '$ORACLE/cdb/orcl/xstream_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;
    > CREATE USER c##xstrmadmin IDENTIFIED BY password DEFAULT TABLESPACE xstream_tbs   QUOTA UNLIMITED ON xstream_tbs container=all;
    > GRANT CREATE SESSION, SET CONTAINER TO c##xstrmadmin CONTAINER=ALL;
</code>```

After this step I should give permissions to user to use XStream

```<code>    > BEGIN
        DBMS_XSTREAM_AUTH.GRANT_ADMIN_PRIVILEGE(
          grantee                 => 'c##xstrmadmin',
          privilege_type          => 'CAPTURE',
          grant_select_privileges => TRUE,
          container => 'ALL');
      END;
      /
</code>```

On this stage, I'm getting this error:

```<code>ERROR at line 1:
ORA-44001: invalid schema
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH_IVK", line 3383
ORA-06512: at line 1
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH_IVK", line 3500
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH", line 34
ORA-06512: at line 2
</code>```

Current container is cdb$root

Googling gives actually nothing and I have no idea whats wrong as I'm following DBA documentation.

答:
I guess I found workaround.

If you connect to oracle with

```<code>> sqlplus /nolog
</code>```

And then connect as sysdba

```<code>> conn / as sysdba
</code>```

Then all works fine!

If this is only one way to resolve problem with creating permissions then problem is in sqlplus or oracle itself. Sad!

Title: Configuring Oracle XStream

Body:
I'm trying to configure Oracle XStream out by official documentation

So, shortly, I'm connecting as sysdba

    sqlplus / as sysdba

Then executing commands create create CDB user and give him privileges

    > CREATE TABLESPACE xstream_tbs DATAFILE '$ORACLE/cdb/orcl/xstream_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;
    > CREATE USER c##xstrmadmin IDENTIFIED BY password DEFAULT TABLESPACE xstream_tbs   QUOTA UNLIMITED ON xstream_tbs container=all;
    > GRANT CREATE SESSION, SET CONTAINER TO c##xstrmadmin CONTAINER=ALL;

After this step I should give permissions to user to use XStream

    > BEGIN
        DBMS_XSTREAM_AUTH.GRANT_ADMIN_PRIVILEGE(
          grantee                 => 'c##xstrmadmin',
          privilege_type          => 'CAPTURE',
          grant_select_privileges => TRUE,
          container => 'ALL');
      END;
      /

On this stage, I'm getting this error:

ERROR at line 1:
ORA-44001: invalid schema
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH_IVK", line 3383
ORA-06512: at line 1
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH_IVK", line 3500
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH", line 34
ORA-06512: at line 2

Current container is cdb$root

Googling gives actually nothing and I have no idea whats wrong as I'm following DBA documentation.

Body:
I guess I found workaround.

If you connect to oracle with

> sqlplus /nolog

And then connect as sysdba

> conn / as sysdba

Then all works fine!

If this is only one way to resolve problem with creating permissions then problem is in sqlplus or oracle itself. Sad!


问:
DocuSign API Create Envelope
Currently I am using #DocuSignAPI to create envelope in which API required x and y position to add signature from recipients.
So my requirement is like if i upload the document it should be redirect to the Docusign UI where recipient would login and sign the document.
So the thing is instead of creating rest call via API.
I need some api where Docusign is going to handle by its way so i do not need to create UI for that which is very complex to build from my side.
Anyone can help me with is will be really great.

Thanks in advance

答:
Check out this DocuSign recipe: Sign from Your App.

This sample (and many others) are available on the DocuSign Developer Center, along with tons of documentation about various integration scenarios and API reference.

Title: DocuSign API Create Envelope


问:
consuming webservice with asp.net and C#
I am learning asp.net, and trying to understand in consuming a webservice. I am using the following wsdl file

http://www.webservicex.net/uszip.asmx?WSDL

I am using a textbox to enter the zipcode, added the wsdl in the web reference , and am using C# to retrieve data. The structure of the data is as follows:

http://www.webservicex.net/uszip.asmx/GetInfoByZIP

I am not able to understand on how to display the results  on a webpage. The following code is what I have until now..

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    USZip s1 = new USZip();
    var input = zipcode.Text.ToString();
    String result = s1.GetInfoByZIP(input);

}
</code>```

It would be great if anyone can give me helpful pointers

Thanks a lot

答:
You can either assign result to a control's Text property (such as a Literal, or a Label), or you can use Response.Write().  Assigning it to a control is a better way to go, as just pumping it out to the response stream probably isn't going to get it displayed where and how you want.

In your aspx page you should add a control:

```<code><asp:Literal Id="postCodeInfo" runat="server"></asp:Literal>
</code>```

And at the end of your Button1_Click event, assign result to that literal's Text property:

```<code>postCodeInfo.Text = result;
</code>```

Also on the second line, I'm assuming that zipcode.Text is a string, so you don't need to call ToString() on it again (if it isn't a string, maybe you do).

Body:
I am learning asp.net, and trying to understand in consuming a webservice. I am using the following wsdl file

http://www.webservicex.net/uszip.asmx?WSDL

I am using a textbox to enter the zipcode, added the wsdl in the web reference , and am using C# to retrieve data. The structure of the data is as follows:

http://www.webservicex.net/uszip.asmx/GetInfoByZIP

I am not able to understand on how to display the results  on a webpage. The following code is what I have until now..

protected void Button1_Click(object sender, EventArgs e)
{
    USZip s1 = new USZip();
    var input = zipcode.Text.ToString();
    String result = s1.GetInfoByZIP(input);

}

It would be great if anyone can give me helpful pointers

Thanks a lot

Body:
You can either assign result to a control's Text property (such as a Literal, or a Label), or you can use Response.Write().  Assigning it to a control is a better way to go, as just pumping it out to the response stream probably isn't going to get it displayed where and how you want.

In your aspx page you should add a control:

<asp:Literal Id="postCodeInfo" runat="server"></asp:Literal>

And at the end of your Button1_Click event, assign result to that literal's Text property:

postCodeInfo.Text = result;

Also on the second line, I'm assuming that zipcode.Text is a string, so you don't need to call ToString() on it again (if it isn't a string, maybe you do).


问:
nuspec file with dependencies
My company has set up a nuget repository for packages that are proprietary to our business. I have a nuspec file for a package that lists dependencies that are located on the main nuget repository. When I install a package from our repository the dependencies are not installed.

```<code><dependencies>
    <group targetFramework="uap">
        <dependency id="FluentNHibernate" version="2.0.3.0" />
        <dependency id="log4net" version="2.0.8.0" />
        <dependency id="Newtonsoft.Json" version="6.0.0.0" />
        <dependency id="UserModel.SMDC" version="1.0.0.0" />
    <dependency id="Microsoft.AspNet.Identity.Core" version="2.2.1" />
    <dependency id="Microsoft.AspNet.WebPages.Core" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.Data" version="3.2.5" />
    <dependency id="Microsoft.AspNet.WebApi.WebData" version="3.2.5" />
    <dependency id="Npgsql" version="3.2.5" />

    </group>
</dependencies>
</code>```

Is there something I need to do to tell the "push" to look at the main nuget site?

答:
The Dependencies section is you can specify the other nuget packages to target (as you are doing). Check out the Dependency Groups section in the first link. You likely have the wrong group type specified for your dependencies. Here is a list of the Target Frameworks. I would suspect you could remove the group tag and keep the <dependency> tags.

Here is an example of the dependencies (from your provided list):

<dependencies>
  <group>
    <dependency id="log4net" version="2.0.8.0" />
    <dependency id="Newtonsoft.Json" version="6.0.0.0" />
  </group>
  <group targetFramework="net46">
    <dependency id="log4net" version="2.0.8.0" />
    <dependency id="Newtonsoft.Json" version="6.0.0.0" />
    <dependency id="FluentNHibernate" version="2.0.3.0" />
    <dependency id="UserModel.SMDC" version="1.0.0.0" />
    <dependency id="Microsoft.AspNet.Identity.Core" version="2.2.1" />
    <dependency id="Microsoft.AspNet.WebPages.Core" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.Data" version="3.2.5" />
    <dependency id="Microsoft.AspNet.WebApi.WebData" version="3.2.5" />
    <dependency id="Npgsql" version="3.2.5" />
  </group>
</dependencies>
```

This example shows that we need log4net and Newtonsoft.Json as a non-specific group. This is what is used for all groups not specified as the target.

Title: nuspec file with dependencies

Body:
My company has set up a nuget repository for packages that are proprietary to our business. I have a nuspec file for a package that lists dependencies that are located on the main nuget repository. When I install a package from our repository the dependencies are not installed.

<dependencies>
    <group targetFramework="uap">
        <dependency id="FluentNHibernate" version="2.0.3.0" />
        <dependency id="log4net" version="2.0.8.0" />
        <dependency id="Newtonsoft.Json" version="6.0.0.0" />
        <dependency id="UserModel.SMDC" version="1.0.0.0" />
    <dependency id="Microsoft.AspNet.Identity.Core" version="2.2.1" />
    <dependency id="Microsoft.AspNet.WebPages.Core" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.Data" version="3.2.5" />
    <dependency id="Microsoft.AspNet.WebApi.WebData" version="3.2.5" />
    <dependency id="Npgsql" version="3.2.5" />

    </group>
</dependencies>

Is there something I need to do to tell the "push" to look at the main nuget site?

Body:
The Dependencies section is you can specify the other nuget packages to target (as you are doing). Check out the Dependency Groups section in the first link. You likely have the wrong group type specified for your dependencies. Here is a list of the Target Frameworks. I would suspect you could remove the group tag and keep the <dependency> tags.

Here is an example of the dependencies (from your provided list):

<dependencies>
  <group>
    <dependency id="log4net" version="2.0.8.0" />
    <dependency id="Newtonsoft.Json" version="6.0.0.0" />
  </group>
  <group targetFramework="net46">
    <dependency id="log4net" version="2.0.8.0" />
    <dependency id="Newtonsoft.Json" version="6.0.0.0" />
    <dependency id="FluentNHibernate" version="2.0.3.0" />
    <dependency id="UserModel.SMDC" version="1.0.0.0" />
    <dependency id="Microsoft.AspNet.Identity.Core" version="2.2.1" />
    <dependency id="Microsoft.AspNet.WebPages.Core" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" />
    <dependency id="Microsoft.AspNet.WebApi.Data" version="3.2.5" />
    <dependency id="Microsoft.AspNet.WebApi.WebData" version="3.2.5" />
    <dependency id="Npgsql" version="3.2.5" />
  </group>
</dependencies>

This example shows that we need log4net and Newtonsoft.Json as a non-specific group. This is what is used for all groups not specified as the target.


问:
Django Queryset - Sort alphabetical then move specific entries to top

Edit (Background info)

I've created a custom UserModelChoiceField class that takes a QuerySet of users and populates a select field with their full names:

```<code>class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.get_full_name(), obj.username)
</code>```

I'm now attempting to use this class like:

```<code>calibrated_by_internal = UserModelChoiceField(
                                              queryset=total_qs,
                                              required=False,
                                              widget=forms.Select(attrs={"class": "form-control"})
                                              )
</code>```

.

Original Question

I'm trying to create a custom sorted QuerySet that will allow me to put a User ModelChoice select field on a form that is sorted alphabetically, but 3 members of a particular permissions group are put at the top.

For example:

Members of the group:
Charlie, Alan, Brian

Not members of the group:
Ben, Chris, Alicia... etc.

Required QuerySet / Select Field ordering:
Alan, Brian, Charlie, Alicia, Ben, Chris... etc.

Given that I'm using Django 1.11 I thought I'd try the new .union ORM function:

```<code>group_members = User.objects.filter(groups__name="AddEditCalibrations").order_by("first_name", "last_name")
everyone_else = User.objects.exclude(username__in="group_members").order_by("first_name", "last_name")
total_qs = group_members.union(everyone_else)
</code>```

Which just raises the error:

```<code>DATABASE ERROR - ORDER BY not allowed in subqueries of compound statements
</code>```

It seems to work OK without the 2 ORDER_BYs, but then the list isn't sorted alphabetically and the members of that group that need to be at the top of the select (first in the QS) are just mixed in with everyone else.

So I tried the even simpler:

```<code>total_qs = User.objects.order_by(groups__name="AddEditCalibrations", "first_name", "last_name")
</code>```

Which raises error:

```<code>SyntaxError: positional argument follows keyword argument
</code>```

Edit

Following rajkris' suggestion of using itertools I tried:

```<code>total_list = list(chain(group_members, everyone_else))
</code>```

Given that I need a QS to populate the select field I then tried to convert it back to a QS with:

```<code>total_qs = User.objects.filter(username__in=total_list)
</code>```

But this only got me an unsorted list with all users mixed together without any ordering.

答:
You cannot order by a condition with that syntax. You could order by groups__name but that's not what you want. Instead you need to translate it into another field by which you can order—let's call it the weight; groups__name="AddEditCalibrations" should get a weight of 0 and every other should get a weight of 1.

You can try this:

```<code>from django.db.models import IntegerField, Value

group_members = User.objects.filter(groups__name="AddEditCalibrations").annotate(weight=Value(0, IntegerField()))
everyone_else = User.objects.exclude(groups__name="AddEditCalibrations").annotate(weight=Value(1, IntegerField()))
total_qs = group_members.union(everyone_else).order_by("weight", "first_name", "last_name")
</code>```

If your union still doesn't work as expected, you might need all=True.

Alternatively, in one go:

```<code>from django.db.models import Case, IntegerField, Value, When

total_qs = User.objects.annotate(weight=Case(
    When(groups__name="AddEditCalibrations", then=Value(0)),
    default=Value(1),
    output_field=IntegerField()
)).order_by("weight", "first_name", "last_name")
</code>```

Body:
Edit (Background info)

I've created a custom UserModelChoiceField class that takes a QuerySet of users and populates a select field with their full names:

class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.get_full_name(), obj.username)

I'm now attempting to use this class like:

calibrated_by_internal = UserModelChoiceField(
                                              queryset=total_qs,
                                              required=False,
                                              widget=forms.Select(attrs={"class": "form-control"})
                                              )

.

Original Question

I'm trying to create a custom sorted QuerySet that will allow me to put a User ModelChoice select field on a form that is sorted alphabetically, but 3 members of a particular permissions group are put at the top.

For example:

Members of the group:
Charlie, Alan, Brian

Not members of the group:
Ben, Chris, Alicia... etc.

Required QuerySet / Select Field ordering:
Alan, Brian, Charlie, Alicia, Ben, Chris... etc.

Given that I'm using Django 1.11 I thought I'd try the new .union ORM function:

group_members = User.objects.filter(groups__name="AddEditCalibrations").order_by("first_name", "last_name")
everyone_else = User.objects.exclude(username__in="group_members").order_by("first_name", "last_name")
total_qs = group_members.union(everyone_else)

Which just raises the error:

DATABASE ERROR - ORDER BY not allowed in subqueries of compound statements

It seems to work OK without the 2 ORDER_BYs, but then the list isn't sorted alphabetically and the members of that group that need to be at the top of the select (first in the QS) are just mixed in with everyone else.

So I tried the even simpler:

total_qs = User.objects.order_by(groups__name="AddEditCalibrations", "first_name", "last_name")

Which raises error:

SyntaxError: positional argument follows keyword argument

Edit

Following rajkris' suggestion of using itertools I tried:

total_list = list(chain(group_members, everyone_else))

Given that I need a QS to populate the select field I then tried to convert it back to a QS with:

total_qs = User.objects.filter(username__in=total_list)

But this only got me an unsorted list with all users mixed together without any ordering.

Body:
You cannot order by a condition with that syntax. You could order by groups__name but that's not what you want. Instead you need to translate it into another field by which you can order—let's call it the weight; groups__name="AddEditCalibrations" should get a weight of 0 and every other should get a weight of 1.

You can try this:

from django.db.models import IntegerField, Value

group_members = User.objects.filter(groups__name="AddEditCalibrations").annotate(weight=Value(0, IntegerField()))
everyone_else = User.objects.exclude(groups__name="AddEditCalibrations").annotate(weight=Value(1, IntegerField()))
total_qs = group_members.union(everyone_else).order_by("weight", "first_name", "last_name")

If your union still doesn't work as expected, you might need all=True.

Alternatively, in one go:

from django.db.models import Case, IntegerField, Value, When

total_qs = User.objects.annotate(weight=Case(
    When(groups__name="AddEditCalibrations", then=Value(0)),
    default=Value(1),
    output_field=IntegerField()
)).order_by("weight", "first_name", "last_name")


问:
Angular 5 file-saver saveAs CSV file encoding to ANSI
I use Angular 5 + "file-saver": "^1.3.3" + "@types/file-saver": "^1.3.0"

```<code>import { saveAs } from 'file-saver';
const filename = parts[1].split('=')[1];
const blob = new Blob(['\ufeff', response.body], { type: 'text/csv' });
saveAs(blob, filename);
</code>```

create UTF-8 file

```<code>import { saveAs } from 'file-saver';
const filename = parts[1].split('=')[1];
const blob = new Blob([response.body], { type: 'text/csv' });
saveAs(blob, filename);
</code>```

create UTF-8 w/o BOM file

But I need create ANSI file (for Excel and an other client)

I try { type: 'text/csv;charset=ansi;' } but do not work.

答:
it is not possible change UTF-8 to ANSI in Front-End part(Angular). I change

```<code>@RequestMapping(value = "/export", method = RequestMethod.GET, produces = "text/csv")
</code>```

by

```<code>@RequestMapping(value = "/export", method = RequestMethod.GET, produces = "text/csv;charset=ISO-8859-1")
</code>```

in my Back-End (Springboot)

Body:
I use Angular 5 + "file-saver": "^1.3.3" + "@types/file-saver": "^1.3.0"

import { saveAs } from 'file-saver';
const filename = parts[1].split('=')[1];
const blob = new Blob(['\ufeff', response.body], { type: 'text/csv' });
saveAs(blob, filename);

create UTF-8 file

import { saveAs } from 'file-saver';
const filename = parts[1].split('=')[1];
const blob = new Blob([response.body], { type: 'text/csv' });
saveAs(blob, filename);

create UTF-8 w/o BOM file

But I need create ANSI file (for Excel and an other client)

I try { type: 'text/csv;charset=ansi;' } but do not work.

Body:
it is not possible change UTF-8 to ANSI in Front-End part(Angular). I change

@RequestMapping(value = "/export", method = RequestMethod.GET, produces = "text/csv")

by

@RequestMapping(value = "/export", method = RequestMethod.GET, produces = "text/csv;charset=ISO-8859-1")

in my Back-End (Springboot)