问:
How to programmatically generate a PDF from any document on OSX?
I'm working on a project for OSX where the user can pick a collection of documents (from any application) which I need to generate PDF's from.  The standard Macintosh Print dialog has a PDF button which has a number of PDF-related commands including "Save as PDF...". However, I need to generate the PDF file without requiring user interactions. I ideally want this to work with any type of document.

Here's the options I've explored so far:

Automator actions. There's a PDF library for Automator but it provides actions for working with PDF files, not generating them. There's a Finder action for printing any file but only to a real printer.

AppleScript. Some applications have the ability to generate PDF files (for instance, if you send 'save doc in "test.pdf"' to Pages it will generate a PDF (but this only works for Pages - I need support for any type of document).

Custom Printer. I could create a virtual printer driver and then use the automator action but I don't like the idea of confusing the user with an extra printer in the print list.

My hope is that there's some way to interact with the active application as if the user was carrying out the following steps:

Do Cmd-P (opens the print dialog)

Click the "PDF" button

Select "Save as PDF..." (second item in menu)

Type in filename in save dialog

Click "Save"

If that's the best approach (is it?) then the real problem is: how do I send UI Events to an external application (keystrokes, mouse events, menu selections) ?

Update: Just to clarify one point: the documents I need to convert to PDF are documents that are created by other applications. For example, the user might pick a Word document or a Numbers spreadsheet or an OmniGraffle drawing or a Web Page. The common denominator is that each of these documents has an associated application and that application knows how to print it (and OSX knows how to render print output to a PDF file).

So, the samples at Cocoa Dev Central don't help because they're about generating a PDF from my application.

答:
"/System/Library/Printers/Libraries/./convert"
has been removed in later version of MacOS.

You can use sips now. AppleScript example:
do shell script: sips -s format pdf Filename.jpg --out Filename.pdf

OwnerDisplayName: Denis Hennessy

LastEditorDisplayName: Denis Hennessy


来源: stackexchange

问:
How can I create an algorithm for display all possible character combinations as a list in python?
The inputs for the function are

a list of characters, eg: ['a','1']

length of combinations

The function should output a list of all possible character combinations as a list.

For example, for input ['a','1'] and length of 2, the function should output:

```<code>[['a','a'],
['a','1'],
['1','a'],
['1','1']]
</code>```

and if the length is 3, the output should be:

```<code>[['a','a','a'],
['a','a','1'],
['a','1','a'],
['a','1','1'],
['1','a','a'],
['1','a','1'],
['1','1','a'],
['1','1','1']]
</code>```

答:
You can use itertools.product with the repeat parameter:

from itertools import product

data = ['a', '1']
n = 3

print(list(list(p) for p in product(data, repeat=n)))
```
<p>This gives an output of:</p>
<pre class="lang-py prettyprint-override"><code>[['a', 'a', 'a'], ['a', 'a', '1'], ['a', '1', 'a'], ['a', '1', '1'],
['1', 'a', 'a'], ['1', 'a', '1'], ['1', '1', 'a'], ['1', '1', '1']]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The inputs for the function are

a list of characters, eg: ['a','1']

length of combinations

The function should output a list of all possible character combinations as a list.

For example, for input ['a','1'] and length of 2, the function should output:

[['a','a'],
['a','1'],
['1','a'],
['1','1']]

and if the length is 3, the output should be:

[['a','a','a'],
['a','a','1'],
['a','1','a'],
['a','1','1'],
['1','a','a'],
['1','a','1'],
['1','1','a'],
['1','1','1']]

Body:
You can use itertools.product with the repeat parameter:

from itertools import product

data = ['a', '1']
n = 3

print(list(list(p) for p in product(data, repeat=n)))

This gives an output of:

[['a', 'a', 'a'], ['a', 'a', '1'], ['a', '1', 'a'], ['a', '1', '1'],
['1', 'a', 'a'], ['1', 'a', '1'], ['1', '1', 'a'], ['1', '1', '1']]


问:
python : can reduce be translated into list comprehensions like map, lambda and filter?
When programming in python, I now avoid map, lambda and filter by using list comprehensions because it is easier to read and faster in execution. But can reduce be replaced as well?

E.g. an object has an operator union() that works on another object, a1.union(a2), and gives a 3rd object of same type.

I have a list of objects:

```<code>L = [a1, a2, a3, ...]
</code>```

How to have the union() of all these objects with list comprehensions, the equivalent of:

```<code>result = reduce(lambda a, b :a.union(b), L[1:], L[0])
</code>```

答:
Not the most readable reduce for unions, but assignment expressions can be used to solve it in a single expression:</p>
```<code>In [51]: L = [{1}, {2}, {3}, {4}, {5}]

In [52]: reduce(lambda a, b: a.union(b), L[1:], L[0])
Out[52]: {1, 2, 3, 4, 5}

In [53]: (s := set(), [s := s.union(x) for x in L][-1])[1]
Out[53]: {1, 2, 3, 4, 5}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When programming in python, I now avoid map, lambda and filter by using list comprehensions because it is easier to read and faster in execution. But can reduce be replaced as well?

E.g. an object has an operator union() that works on another object, a1.union(a2), and gives a 3rd object of same type.

I have a list of objects:

L = [a1, a2, a3, ...]

How to have the union() of all these objects with list comprehensions, the equivalent of:

result = reduce(lambda a, b :a.union(b), L[1:], L[0])

Body:
Not the most readable reduce for unions, but assignment expressions can be used to solve it in a single expression:

In [51]: L = [{1}, {2}, {3}, {4}, {5}]

In [52]: reduce(lambda a, b: a.union(b), L[1:], L[0])
Out[52]: {1, 2, 3, 4, 5}

In [53]: (s := set(), [s := s.union(x) for x in L][-1])[1]
Out[53]: {1, 2, 3, 4, 5}


问:
React Router - How to replace dynamically parameters in a string
I have a set of dynamically parameters in the URL, ad example the user locale, that looks like that:

/en/homepage

In my router config JSON file, I have something like:

/:locale/homepage

Which is the best way in order to replace these parameters directly in React Router?

I've come up with this solution that looks to me very far away from a standard or portable solution:

const urlTemplate = '/:language/homepage';
const mappedUrl = pathToRegexp.compile(urlTemplate);
const url = mappedUrl({
  'language': this.props.match.params.language
})
this.props.history.push(url);```

I'm able to retrieve the match parameters if the component is wrapped by withRouter ( HOC from React router ) and replace them with pathToRegexp (   pillarjs/path-to-regexp ), but if I need to use <Link to={}> in a stateless component it's very annoying.

Are there standard solutions in order to do that?

Thank you in advance :)

答:
This is an improved answer that allow you to place optional parameters also.

function placeParams(pathRegex, params) {
  const segments = pathRegex.split("/");
  return (
    segments
    .map((segment) => {
      let offset = segment.indexOf(":?") + 1;

      if (offset) {
        let key = segment.slice(offset + 1);
        return params[key];
      }

      offset = segment.indexOf(":") + 1;
      if (!offset) return segment;

      let key = segment.slice(offset);
      return params[key];
    })
    .join("/")
    // Remove trailing "/"
    .replace(/\/+$/, "")
    // Remove redundant "/"
    .replace(/\/{2,}/, "/")
  );
}

console.log(placeParams("/:locale/user/:?name/:?lastname", {
  locale: "en",
  name: "Nady",
  lastname: "Shalaby"
}))```

Body:
I have a set of dynamically parameters in the URL, ad example the user locale, that looks like that:

/en/homepage

In my router config JSON file, I have something like:

/:locale/homepage

Which is the best way in order to replace these parameters directly in React Router?

I've come up with this solution that looks to me very far away from a standard or portable solution:

const urlTemplate = '/:language/homepage';
const mappedUrl = pathToRegexp.compile(urlTemplate);
const url = mappedUrl({
  'language': this.props.match.params.language
})
this.props.history.push(url);

I'm able to retrieve the match parameters if the component is wrapped by withRouter ( HOC from React router ) and replace them with pathToRegexp (   pillarjs/path-to-regexp ), but if I need to use <Link to={}> in a stateless component it's very annoying.

Are there standard solutions in order to do that?

Thank you in advance :)


问:
Map unique strings to (incrementing) numbers in MongoDB
Assume that I have documents with timestamp, sensor_name, and value (modelling some measurements) such as

```<code>{
  timestamp: 1,
  sensor_name: "Sensor A",
  value: 10
}
{
  timestamp: 2,
  sensor_name: "Sensor B",
  value: 11
}
{
  timestamp: 7,
  sensor_name: "Sensor A",
  value: 5
}
{
  timestamp: 10,
  sensor_name: "Sensor A",
  value: 13
}
{
  timestamp: 12,
  sensor_name: "Sensor B",
  value: 20
}
</code>```

How could I map each unique sensor_name to a unique number and query it in the form

```<code>{
  timestamp: 1,
  sensor_nr: 1,
  value: 10
}
{
  timestamp: 2,
  sensor_nr: 2,
  value: 11
}
{
  timestamp: 7,
  sensor_nr: 1,
  value: 5
}
{
  timestamp: 10,
  sensor_nr: 1,
  value: 13
}
{
  timestamp: 12,
  sensor_nr: 2,
  value: 20
}
</code>```

In general, I do not care if Sensor A becomes 1 and Sensor B becomes 2 or vice-versa.

The answer should be general, there could be more than 20 sensors, no "hardcoding" of possible sensor names, they may not follow a certain naming pattern.

答:
I'm hoping someone provides a better solution than this - my gut feeling is that it is horribly inefficient, but it works!

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "sensor_names": {
        "$addToSet": "$sensor_name"
      }
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "pipeline": [],
      "as": "coll"
    }
  },
  {
    "$unwind": "$coll"
  },
  {
    "$set": {
      "coll.sensor_nr": {
        "$indexOfArray": [
          "$sensor_names",
          "$coll.sensor_name"
        ]
      }
    }
  },
  {
    "$replaceWith": "$coll"
  },
  {
    "$unset": [
      "_id",
      "sensor_name"
    ]
  }
])
```

Try it on mongoplayground.net.

Body:
Assume that I have documents with timestamp, sensor_name, and value (modelling some measurements) such as

{
  timestamp: 1,
  sensor_name: "Sensor A",
  value: 10
}
{
  timestamp: 2,
  sensor_name: "Sensor B",
  value: 11
}
{
  timestamp: 7,
  sensor_name: "Sensor A",
  value: 5
}
{
  timestamp: 10,
  sensor_name: "Sensor A",
  value: 13
}
{
  timestamp: 12,
  sensor_name: "Sensor B",
  value: 20
}

How could I map each unique sensor_name to a unique number and query it in the form

{
  timestamp: 1,
  sensor_nr: 1,
  value: 10
}
{
  timestamp: 2,
  sensor_nr: 2,
  value: 11
}
{
  timestamp: 7,
  sensor_nr: 1,
  value: 5
}
{
  timestamp: 10,
  sensor_nr: 1,
  value: 13
}
{
  timestamp: 12,
  sensor_nr: 2,
  value: 20
}

In general, I do not care if Sensor A becomes 1 and Sensor B becomes 2 or vice-versa.

The answer should be general, there could be more than 20 sensors, no "hardcoding" of possible sensor names, they may not follow a certain naming pattern.

Body:
I'm hoping someone provides a better solution than this - my gut feeling is that it is horribly inefficient, but it works!

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "sensor_names": {
        "$addToSet": "$sensor_name"
      }
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "pipeline": [],
      "as": "coll"
    }
  },
  {
    "$unwind": "$coll"
  },
  {
    "$set": {
      "coll.sensor_nr": {
        "$indexOfArray": [
          "$sensor_names",
          "$coll.sensor_name"
        ]
      }
    }
  },
  {
    "$replaceWith": "$coll"
  },
  {
    "$unset": [
      "_id",
      "sensor_name"
    ]
  }
])

Try it on mongoplayground.net.


问:
Select Query of third table
I have these three tables, and each contract can have several units bound to it.
What I need is the sum the field "area" of all units that are in the same contract.

The query should look like this. The last field "Price fraction" is going to be a calculated field, so I don't need it in the SQL query.

I've tried writing the query, but it always gives the wrong sum.

```<code>Select
Unit.description "Unit",
Unit.area "Area",
Contract.price "Contract Value",
(select sum(Unit.area) from Unit, ContractUnit where ContractUnit.unit_id = Unit.id) "area_sum"
from
Unit
JOIN ContractUnit ON ContractUnit.id_unit = Unit.id
JOIN Contract ON Contract.id = ContractUnit.contract_id
where Unit.id = :idUnit
</code>```

答:
Let's dissect the requirement and break it up into steps.

Evaluation:

There are  three tables:

Unit

Contract

ContractUnit

Unit and Contract entities have many-to-many relationship and hence there is the need of ContractUnit which is the associative entity (or bridge table).

Step 1: The following columns first needs listed:
Unit_id , Area (from table Unit)

Contract_value(dollars) and contract_id (from table contract)

Actually , the final output will not need contract_id but it is still needed in the first step because sum_area is calculated over it. In the final output , we will not display it.

So we get it here:

```<code>SELECT u.id    unit,
       u.area  area,
       c.price contract_value,
       c.id    contract_id
FROM   unit u
       INNER JOIN contractunit cu
               ON u.id = cu.unit_id
       INNER JOIN contract c
               ON c.id = cu.contract_id
</code>```

Output:

```<code> unit | area | contract_value | contract_id
------+------+----------------+-------------
    1 |  340 |         400000 |           1
    2 |  540 |         400000 |           1
    3 |  130 |         560000 |           2
    4 |  503 |         560000 |           2
(4 rows)
</code>```

Step 2 : we get the final value by doing a sum of area over contract_id on the output obtained above.

```<code>
SELECT unit,
       area,
       subq.contract_value,
       Sum(area)
         OVER (
           partition BY contract_id) sum_area
FROM   (<earlier query> ) subq;
</code>```

that is:

```<code>SELECT unit,
       area,
       subq.contract_value,
       Sum(area)
         OVER (
           partition BY contract_id) sum_area
FROM   (SELECT u.id    unit,
       u.area  area,
       c.price contract_value,
       c.id    contract_id
FROM   unit u
       INNER JOIN contractunit cu
               ON u.id = cu.unit_id
       INNER JOIN contract c
               ON c.id = cu.contract_id ) subq;

</code>```

Result:

```<code>unit | area | contract_value | sum_area
------+------+----------------+----------
    1 |  340 |         400000 |      880
    2 |  540 |         400000 |      880
    3 |  130 |         560000 |      633
    4 |  503 |         560000 |      633
(4 rows)
</code>```

--- In case your RDBMS type/version do not support window function or even CTE , you can get the same result with this query ---

```<code>SELECT b.unit,
       b.area,
       b.contract_value,
       a.sum_area
FROM   (SELECT contract_id,
               Sum(area) sum_area
        FROM   (SELECT u.id    unit,
                       u.area  area,
                       c.price contract_value,
                       c.id    contract_id
                FROM   unit u
                       INNER JOIN contractunit cu
                               ON u.id = cu.unit_id
                       INNER JOIN contract c
                               ON c.id = cu.contract_id) subq
        GROUP  BY contract_id) a
       INNER JOIN (SELECT u.id    unit,
                          u.area  area,
                          c.price contract_value,
                          c.id    contract_id
                   FROM   unit u
                          INNER JOIN contractunit cu
                                  ON u.id = cu.unit_id
                          INNER JOIN contract c
                                  ON c.id = cu.contract_id) b
               ON a.contract_id = b.contract_id;
</code>```

Title: Select Query of third table

Body:
I have these three tables, and each contract can have several units bound to it.
What I need is the sum the field "area" of all units that are in the same contract.

The query should look like this. The last field "Price fraction" is going to be a calculated field, so I don't need it in the SQL query.

I've tried writing the query, but it always gives the wrong sum.

Select
Unit.description "Unit",
Unit.area "Area",
Contract.price "Contract Value",
(select sum(Unit.area) from Unit, ContractUnit where ContractUnit.unit_id = Unit.id) "area_sum"
from
Unit
JOIN ContractUnit ON ContractUnit.id_unit = Unit.id
JOIN Contract ON Contract.id = ContractUnit.contract_id
where Unit.id = :idUnit

Body:
Let's dissect the requirement and break it up into steps.

Evaluation:

There are  three tables:

Unit

Contract

ContractUnit

Unit and Contract entities have many-to-many relationship and hence there is the need of ContractUnit which is the associative entity (or bridge table).

Step 1: The following columns first needs listed:
Unit_id , Area (from table Unit)

Contract_value(dollars) and contract_id (from table contract)

Actually , the final output will not need contract_id but it is still needed in the first step because sum_area is calculated over it. In the final output , we will not display it.

So we get it here:

SELECT u.id    unit,
       u.area  area,
       c.price contract_value,
       c.id    contract_id
FROM   unit u
       INNER JOIN contractunit cu
               ON u.id = cu.unit_id
       INNER JOIN contract c
               ON c.id = cu.contract_id

Output:

 unit | area | contract_value | contract_id
------+------+----------------+-------------
    1 |  340 |         400000 |           1
    2 |  540 |         400000 |           1
    3 |  130 |         560000 |           2
    4 |  503 |         560000 |           2
(4 rows)

Step 2 : we get the final value by doing a sum of area over contract_id on the output obtained above.

SELECT unit,
       area,
       subq.contract_value,
       Sum(area)
         OVER (
           partition BY contract_id) sum_area
FROM   (<earlier query> ) subq;

that is:

SELECT unit,
       area,
       subq.contract_value,
       Sum(area)
         OVER (
           partition BY contract_id) sum_area
FROM   (SELECT u.id    unit,
       u.area  area,
       c.price contract_value,
       c.id    contract_id
FROM   unit u
       INNER JOIN contractunit cu
               ON u.id = cu.unit_id
       INNER JOIN contract c
               ON c.id = cu.contract_id ) subq;

Result:

unit | area | contract_value | sum_area
------+------+----------------+----------
    1 |  340 |         400000 |      880
    2 |  540 |         400000 |      880
    3 |  130 |         560000 |      633
    4 |  503 |         560000 |      633
(4 rows)

--- In case your RDBMS type/version do not support window function or even CTE , you can get the same result with this query ---

SELECT b.unit,
       b.area,
       b.contract_value,
       a.sum_area
FROM   (SELECT contract_id,
               Sum(area) sum_area
        FROM   (SELECT u.id    unit,
                       u.area  area,
                       c.price contract_value,
                       c.id    contract_id
                FROM   unit u
                       INNER JOIN contractunit cu
                               ON u.id = cu.unit_id
                       INNER JOIN contract c
                               ON c.id = cu.contract_id) subq
        GROUP  BY contract_id) a
       INNER JOIN (SELECT u.id    unit,
                          u.area  area,
                          c.price contract_value,
                          c.id    contract_id
                   FROM   unit u
                          INNER JOIN contractunit cu
                                  ON u.id = cu.unit_id
                          INNER JOIN contract c
                                  ON c.id = cu.contract_id) b
               ON a.contract_id = b.contract_id;


问:
JUNIT test for binary search tree
I have implemented a binary search tree. Most of my test in JUNIT test is going through, including these two. I have implementedleavesIsCorrectWhenTreeIsPerfect() and insertValuesInAscendingOrderIncrementsHeight().

Both of these test goes through, however i do not know if it is correctly written based on what their description is asking.

//EDIT: I have added a test that might be a help to one of the test a need help with.

//TODO: help me understand if I have written the correct code for the test in insertValuesInAscendingOrderIncrementsHeight() and leavesIsCorrectWhenTreeIsPerfect() based on what the description for the test is saying.

Have in mind, that I have not included all the tests in the test class, Because the goes through with my implementation of the tree.

Down here I have included my tree class and the test class with both the test I need help with.

```<code>/**
 * An Binary Search tree implementation.
 * @param <T>
 */
public class Tree <T extends Comparable <T>> implements BSTInterface <T>{
    private int size;
    private Node root;
    public class Node{
        private Node Left;
        private Node Right;
        private T data;

        public Node(T data){
            this.data = data;
        }
        public Node getRight(){
            return Right;
        }

        public Node getLeft() {
            return Left;
        }

        public T getData() {
            return data;
        }
    }
    public Tree (){
        size = 0;
        root = null;
    }

    /**
     * Test for presence of a value.
     * @param elem
     * @return true/false
     */
    @Override
    public boolean search(T elem) {
        if(root == null ||elem == null){
        return false;
        }
        Node node = root;
        while(true){
            if(node.data.compareTo(elem) > 0){
                if(node.Right == null){
                    return false;
                } else{
                    node = node.Right;
                }
            } else if(node.data.compareTo(elem) == 0){
                break;
            } else{
                if(node.Left== null){
                    return false;
                }
                else{
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * Add value to tree; duplicates are not allowed.
     * Return true if the element is not already present (and is thus inserted),
     * false otherwise.
     *
     * @param elem
     * @return true/false
     */
    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * the number of elements in the tree
     * @return size.
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * The height of the tree.
     * The empty tree and the tree with only the root node both have height 0.
     * @return the height of the tree.
     */
    @Override
    public int height() {
        return countHeight(root);
    }
    /**
     * Helper method for height
     */
    private int countHeight(Node node){
        if(node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 0;
        }
        return 1 + Math.max(countHeight(node.getLeft()), countHeight(node.getRight()));
    }

    /**
     * The number of leaves in the tree.
     * @return the amount of leaves the tree has.
     */
    @Override
    public int leaves() {
        return countLeaves(root);
    }
    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

    /**
     * A string describing the tree
     * @return
     */
    public String toString(){
        String str = "[" + helpToString(root);
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 2);
        } return str + "]";
    }

    /**
     * Helper method for toString
     */
    private String helpToString(Node node) {
        String str = "";
        if (node != null) {
            str += helpToString(node.Right);
            str += node.data + ", ";
            str += helpToString(node.Left);
        }
        return str;
      }
}

</code>```
```<code>import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
 * Test class for a tree.
 */
public class TreeTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    Tree<Integer> tree;
    int[] elementsInTree;
    int[] elementsNotInTree;

    @Before
    public void setUp() {
        /**
         * This tree should look like this:
         *
         *               8
         *             /  \
         *            3   10
         *           / \    \
         *          1   6    14
         *             / \   /
         *            4   7 13
         */
        tree = new Tree<>();
        elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7};
        for (int elem : elementsInTree) {
            tree.insert(elem);
        }
        elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5};
    }
 @Test
    public void heightIsLogOfNumLeavesTreeIsPerfect() {
        // For a perfect tree, tree.height() == log2(tree.leaves()

        // Arrange
        Tree<Integer> tree = new Tree<>();
        int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14};
        int numLeaves = 4;
        int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2));
        for (int elem : elements) {
            tree.insert(elem);
        }

        // Act
        int height = tree.height();
        // Assert
        assertThat(height, equalTo(logNumLeaves));
    }

    @Test
    public void leavesIsCorrectWhenTreeIsPerfect() { //TEST
        // A perfect tree has all leaves at the same depth, and all internal nodes
        // (i.e. non-leaves) have two children
        //
        // This test should assert that a perfect tree with 2*n-1 nodes total,
        // has exactly n leaves (i.e. that Tree.leaves() returns n).
        //
        // An example is the perfect three-node tree from the test above:
        //
        //                        (1338)
        //                        /    \
        //                    (1337)  (1396)

        // You have to construct your own tree here, with n >= 4

    Tree <Integer> tree = new Tree<>();
       int n = 4;
       for(int i = 0; i>=n; i++) {
           tree.insert(i);
         int numLeaves = 2*n-1;
         int leaves = tree.leaves();
         assertThat(leaves,equalTo(numLeaves));
       }
    }

    // Tests for insert/height
    @Test
    public void insertValuesInAscendingOrderIncrementsHeight() { //TEST
        // When inserting elements in ascending order, each element is inserted
        // to the right of the deepest node, so the height should increment by
        // 1 for each element inserted.
        Tree <Integer> tree = new Tree<>();
        int val = 100;
        for(int i = 0; i < val; i++){
            tree.insert(i);

        }
            int treeHeight = tree.height();
        treeHeight++;
            assertThat(tree.size(),equalTo(treeHeight));
    }
}

</code>```

答:
It's awkward that "n" is used in the instructions to describe a tree with n leaves because "n" is traditionally used to describe your node count.  But picture a tree with 4 nodes at the bottom, then half that for the prior layer, then half again for the first layer, and you have a tree with 1+2+4 nodes, or 7 nodes total, which coincides with the formula 2*n-1 (2*4-1=7).</p>
```<code>@Test
public void leavesIsCorrectWhenTreeIsPerfect() {
    int n=4;
    int[] balanced=new int[] {4,2,6,1,3,5,7};
    for (int i=0; i<balanced.length; i++) {
         tree.insert(balanced[i]);
    }
    int leaves = tree.leaves();
    assertThat(balanced.length,equalTo(2*n-1));
    assertThat(leaves,equalTo(n));
}
</code>```

Title: JUNIT test for binary search tree

Body:
I have implemented a binary search tree. Most of my test in JUNIT test is going through, including these two. I have implementedleavesIsCorrectWhenTreeIsPerfect() and insertValuesInAscendingOrderIncrementsHeight().

Both of these test goes through, however i do not know if it is correctly written based on what their description is asking.

//EDIT: I have added a test that might be a help to one of the test a need help with.

//TODO: help me understand if I have written the correct code for the test in insertValuesInAscendingOrderIncrementsHeight() and leavesIsCorrectWhenTreeIsPerfect() based on what the description for the test is saying.

Have in mind, that I have not included all the tests in the test class, Because the goes through with my implementation of the tree.

Down here I have included my tree class and the test class with both the test I need help with.

/**
 * An Binary Search tree implementation.
 * @param <T>
 */
public class Tree <T extends Comparable <T>> implements BSTInterface <T>{
    private int size;
    private Node root;
    public class Node{
        private Node Left;
        private Node Right;
        private T data;

        public Node(T data){
            this.data = data;
        }
        public Node getRight(){
            return Right;
        }

        public Node getLeft() {
            return Left;
        }

        public T getData() {
            return data;
        }
    }
    public Tree (){
        size = 0;
        root = null;
    }

    /**
     * Test for presence of a value.
     * @param elem
     * @return true/false
     */
    @Override
    public boolean search(T elem) {
        if(root == null ||elem == null){
        return false;
        }
        Node node = root;
        while(true){
            if(node.data.compareTo(elem) > 0){
                if(node.Right == null){
                    return false;
                } else{
                    node = node.Right;
                }
            } else if(node.data.compareTo(elem) == 0){
                break;
            } else{
                if(node.Left== null){
                    return false;
                }
                else{
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * Add value to tree; duplicates are not allowed.
     * Return true if the element is not already present (and is thus inserted),
     * false otherwise.
     *
     * @param elem
     * @return true/false
     */
    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * the number of elements in the tree
     * @return size.
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * The height of the tree.
     * The empty tree and the tree with only the root node both have height 0.
     * @return the height of the tree.
     */
    @Override
    public int height() {
        return countHeight(root);
    }
    /**
     * Helper method for height
     */
    private int countHeight(Node node){
        if(node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 0;
        }
        return 1 + Math.max(countHeight(node.getLeft()), countHeight(node.getRight()));
    }

    /**
     * The number of leaves in the tree.
     * @return the amount of leaves the tree has.
     */
    @Override
    public int leaves() {
        return countLeaves(root);
    }
    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

    /**
     * A string describing the tree
     * @return
     */
    public String toString(){
        String str = "[" + helpToString(root);
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 2);
        } return str + "]";
    }

    /**
     * Helper method for toString
     */
    private String helpToString(Node node) {
        String str = "";
        if (node != null) {
            str += helpToString(node.Right);
            str += node.data + ", ";
            str += helpToString(node.Left);
        }
        return str;
      }
}

import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
 * Test class for a tree.
 */
public class TreeTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    Tree<Integer> tree;
    int[] elementsInTree;
    int[] elementsNotInTree;

    @Before
    public void setUp() {
        /**
         * This tree should look like this:
         *
         *               8
         *             /  \
         *            3   10
         *           / \    \
         *          1   6    14
         *             / \   /
         *            4   7 13
         */
        tree = new Tree<>();
        elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7};
        for (int elem : elementsInTree) {
            tree.insert(elem);
        }
        elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5};
    }
 @Test
    public void heightIsLogOfNumLeavesTreeIsPerfect() {
        // For a perfect tree, tree.height() == log2(tree.leaves()

        // Arrange
        Tree<Integer> tree = new Tree<>();
        int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14};
        int numLeaves = 4;
        int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2));
        for (int elem : elements) {
            tree.insert(elem);
        }

        // Act
        int height = tree.height();
        // Assert
        assertThat(height, equalTo(logNumLeaves));
    }

    @Test
    public void leavesIsCorrectWhenTreeIsPerfect() { //TEST
        // A perfect tree has all leaves at the same depth, and all internal nodes
        // (i.e. non-leaves) have two children
        //
        // This test should assert that a perfect tree with 2*n-1 nodes total,
        // has exactly n leaves (i.e. that Tree.leaves() returns n).
        //
        // An example is the perfect three-node tree from the test above:
        //
        //                        (1338)
        //                        /    \
        //                    (1337)  (1396)

        // You have to construct your own tree here, with n >= 4

    Tree <Integer> tree = new Tree<>();
       int n = 4;
       for(int i = 0; i>=n; i++) {
           tree.insert(i);
         int numLeaves = 2*n-1;
         int leaves = tree.leaves();
         assertThat(leaves,equalTo(numLeaves));
       }
    }

    // Tests for insert/height
    @Test
    public void insertValuesInAscendingOrderIncrementsHeight() { //TEST
        // When inserting elements in ascending order, each element is inserted
        // to the right of the deepest node, so the height should increment by
        // 1 for each element inserted.
        Tree <Integer> tree = new Tree<>();
        int val = 100;
        for(int i = 0; i < val; i++){
            tree.insert(i);

        }
            int treeHeight = tree.height();
        treeHeight++;
            assertThat(tree.size(),equalTo(treeHeight));
    }
}

Body:
It's awkward that "n" is used in the instructions to describe a tree with n leaves because "n" is traditionally used to describe your node count.  But picture a tree with 4 nodes at the bottom, then half that for the prior layer, then half again for the first layer, and you have a tree with 1+2+4 nodes, or 7 nodes total, which coincides with the formula 2*n-1 (2*4-1=7).

@Test
public void leavesIsCorrectWhenTreeIsPerfect() {
    int n=4;
    int[] balanced=new int[] {4,2,6,1,3,5,7};
    for (int i=0; i<balanced.length; i++) {
         tree.insert(balanced[i]);
    }
    int leaves = tree.leaves();
    assertThat(balanced.length,equalTo(2*n-1));
    assertThat(leaves,equalTo(n));
}


问:
File Storage Problem with Python Web Crawler
I am screen scraping data using a web crawler and storing the results - (tweets from a twitter page) as separate html files for each user I'm crawling. I intend to later parse the html files and store the data into a database for analysis. However, I am having a bizarre problem.

When I run the following program - a small snippet from the overall crawler - I am able to get a separate html file for each follower:

```<code>import re
import urllib2
import twitter

start_follower = "NYTimesKrugman"
depth = 3

searched = set()

api = twitter.Api()

def crawl(follower, in_depth):
    if in_depth > 0:
        searched.add(follower)
        directory = "C:\\Python28\\Followertest1\\" + follower + ".html"
        output = open(directory, 'a')
        output.write(follower)
        output.write('\n\n')
        users = api.GetFriends(follower)
        names = set([str(u.screen_name) for u in users])
        names -= searched
        for name in list(names)[0:5]:
            crawl(name, in_depth-1)

crawl(start_follower, depth)

for x in searched:
    print x
print "Program is completed."
</code>```

However, when I run the full crawler, I do not get a separate file for each follower:

```<code>import twitter
import urllib
from BeautifulSoup import BeautifulSoup
import re
import time

start_follower = "NYTimeskrugman"
depth = 2
searched = set()

api = twitter.Api()

def add_to_U(user):
    U.append(user)

def site(follower): #creates a twitter site url in string format based on the follower username
    followersite = "http://mobile.twitter.com/" + follower
    return followersite

def getPage(follower): #obtains access to a webapge
    url = site(follower)
    response = urllib.urlopen(url)
    return response

def getSoup(response): #creates the parsing module
    html = response.read()
    soup = BeautifulSoup(html)
    return soup

def gettweets(soup, output):
    tags = soup.findAll('div', {'class' : "list-tweet"})#to obtain tweet of a follower
    for tag in tags:
        a = tag.renderContents()
        b = str (a)
        output.write(b)
        output.write('\n\n')

def are_more_tweets(soup):#to check whether there is more than one page on mobile twitter
    links = soup.findAll('a', {'href': True}, {id: 'more_link'})
    for link in links:
        b = link.renderContents()
        test_b = str(b)
        if test_b.find('more') != -1:
            return True
    return False

def getnewlink(soup): #to get the link to go to the next page of tweets on twitter
    links = soup.findAll('a', {'href': True}, {id : 'more_link'})
    for link in links:
        b = link.renderContents()
        if str(b) == 'more':
            c = link['href']
            d = 'http://mobile.twitter.com' +c
            return d

def crawl(follower, in_depth): #main method of sorts
    if in_depth > 0:
        searched.add(follower)
        directory = "C:\\Python28\\Followertest2\\" + follower + ".html"
        output = open(directory, 'a')
        output.write(follower)
        output.write('\n\n')
        a = getPage(follower)
        soup = getSoup(a)
        gettweets(soup, output)
        tweets = are_more_tweets(soup)
        while(tweets):
            b = getnewlink(soup)
            red = urllib.urlopen(b)
            html = red.read()
            soup = BeautifulSoup(html)
            gettweets(soup, output)
            tweets = are_more_tweets(soup)
        users = api.GetFriends(follower)
        names = set([str(u.screen_name) for u in users])
        names -= searched
        for name in list(names)[0:5]:
            print name
            crawl(name, in_depth - 1)

crawl(start_follower, depth)
print("Program done. Look at output file.")
</code>```

More specifically, I seem to get a separate html file for about the first five followers and then no new files appear to be created. Any help would be appreciated!

答: The depth value is different between the snippet and the full code (you're only going to get one level of recursion in the full code). Also, you only grab the first five names from the followers list: for name in list(names)[0:5]: So you get six people total: the starting follower and their first five friends.

Body:
I am screen scraping data using a web crawler and storing the results - (tweets from a twitter page) as separate html files for each user I'm crawling. I intend to later parse the html files and store the data into a database for analysis. However, I am having a bizarre problem.

When I run the following program - a small snippet from the overall crawler - I am able to get a separate html file for each follower:

import re
import urllib2
import twitter

start_follower = "NYTimesKrugman"
depth = 3

searched = set()

api = twitter.Api()

def crawl(follower, in_depth):
    if in_depth > 0:
        searched.add(follower)
        directory = "C:\\Python28\\Followertest1\\" + follower + ".html"
        output = open(directory, 'a')
        output.write(follower)
        output.write('\n\n')
        users = api.GetFriends(follower)
        names = set([str(u.screen_name) for u in users])
        names -= searched
        for name in list(names)[0:5]:
            crawl(name, in_depth-1)

crawl(start_follower, depth)

for x in searched:
    print x
print "Program is completed."

However, when I run the full crawler, I do not get a separate file for each follower:

import twitter
import urllib
from BeautifulSoup import BeautifulSoup
import re
import time

start_follower = "NYTimeskrugman"
depth = 2
searched = set()

api = twitter.Api()

def add_to_U(user):
    U.append(user)

def site(follower): #creates a twitter site url in string format based on the follower username
    followersite = "http://mobile.twitter.com/" + follower
    return followersite

def getPage(follower): #obtains access to a webapge
    url = site(follower)
    response = urllib.urlopen(url)
    return response

def getSoup(response): #creates the parsing module
    html = response.read()
    soup = BeautifulSoup(html)
    return soup

def gettweets(soup, output):
    tags = soup.findAll('div', {'class' : "list-tweet"})#to obtain tweet of a follower
    for tag in tags:
        a = tag.renderContents()
        b = str (a)
        output.write(b)
        output.write('\n\n')

def are_more_tweets(soup):#to check whether there is more than one page on mobile twitter
    links = soup.findAll('a', {'href': True}, {id: 'more_link'})
    for link in links:
        b = link.renderContents()
        test_b = str(b)
        if test_b.find('more') != -1:
            return True
    return False

def getnewlink(soup): #to get the link to go to the next page of tweets on twitter
    links = soup.findAll('a', {'href': True}, {id : 'more_link'})
    for link in links:
        b = link.renderContents()
        if str(b) == 'more':
            c = link['href']
            d = 'http://mobile.twitter.com' +c
            return d

def crawl(follower, in_depth): #main method of sorts
    if in_depth > 0:
        searched.add(follower)
        directory = "C:\\Python28\\Followertest2\\" + follower + ".html"
        output = open(directory, 'a')
        output.write(follower)
        output.write('\n\n')
        a = getPage(follower)
        soup = getSoup(a)
        gettweets(soup, output)
        tweets = are_more_tweets(soup)
        while(tweets):
            b = getnewlink(soup)
            red = urllib.urlopen(b)
            html = red.read()
            soup = BeautifulSoup(html)
            gettweets(soup, output)
            tweets = are_more_tweets(soup)
        users = api.GetFriends(follower)
        names = set([str(u.screen_name) for u in users])
        names -= searched
        for name in list(names)[0:5]:
            print name
            crawl(name, in_depth - 1)

crawl(start_follower, depth)
print("Program done. Look at output file.")

More specifically, I seem to get a separate html file for about the first five followers and then no new files appear to be created. Any help would be appreciated!


问:
Moving points of a line based on collision
I have a line colliding with a sphere:

The grey spheres are the endpoints of the line.

The white sphere is colliding with the line.

The blue sphere is the point of collision.

What I want to do is essentially move the blue sphere (the point of collision) to the edge of the white sphere by moving the grey spheres (the line endpoints).

But, I want the grey spheres moved based on how close the colliding white sphere is.

e.g. in the image above, the white sphere is colliding roughly 80% to the right on the line. So the grey sphere on the left should have to perform 80% of the movement, with the left sphere doing 20%, resulting in the diagonal movement (shown below)

While a more central collision would result in equal movement from both:

Any advice on the maths required here?

What I have available in my equation is:
The collision position
The endpoint positions of the line
The position and radius of the white sphere

I'd like to use this information to move the two endpoint positions.

答:
So.. not as hard as I thought it would be:

```<code>        Vector3 d = (Vector3)lastCollisionPoint - sc;
        float dlen = d.magnitude;
        var movement = (sc + d * (r / dlen)) - (Vector3)lastCollisionPoint;

        t2.transform.position += Vector3.Lerp(Vector3.zero, movement, lerp);
        t1.transform.position += Vector3.Lerp(Vector3.zero, movement, 1f - lerp);
</code>```

sc = sphere centre

lastCollisonPoint = the blue sphere collision point

t1 & t2 = the two points of the line

Body:
So.. not as hard as I thought it would be:

        Vector3 d = (Vector3)lastCollisionPoint - sc;
        float dlen = d.magnitude;
        var movement = (sc + d * (r / dlen)) - (Vector3)lastCollisionPoint;

        t2.transform.position += Vector3.Lerp(Vector3.zero, movement, lerp);
        t1.transform.position += Vector3.Lerp(Vector3.zero, movement, 1f - lerp);

sc = sphere centre

lastCollisonPoint = the blue sphere collision point

t1 & t2 = the two points of the line


问:
What's the cleanest or most idiomatic way to remove all of a user's roles for a particular resource?
I can do this. Is there a more idiomatic way or something directly supported by the API?</p>
```<code>transaction do
  Organization.find_roles(:any, organization).where(resource_id: organization.id).pluck(:name).each |role_name|
    remove_role(role_name, organization)
  end
  add_role('new_role', organization)
end
</code>```

答:
If you just want to get rid of all of those roles then this should do it: (basically what remove_role does but without additional filters or callbacks)

```<code>roles
  .where(
    resource_type: 'Organization',
    resource_id: organization.id)
  .delete_all
</code>```

If you want it to act more like remove_role then this might be a better way to go:

```<code>self.class.adapter.remove(
  self,
  Organization
    .find_roles(:any, organization),
  organization)
</code>```

Rolify::Adapter::RoleAdapter

Body:
I can do this. Is there a more idiomatic way or something directly supported by the API?

transaction do
  Organization.find_roles(:any, organization).where(resource_id: organization.id).pluck(:name).each |role_name|
    remove_role(role_name, organization)
  end
  add_role('new_role', organization)
end

Body:
If you just want to get rid of all of those roles then this should do it: (basically what remove_role does but without additional filters or callbacks)

roles
  .where(
    resource_type: 'Organization',
    resource_id: organization.id)
  .delete_all

If you want it to act more like remove_role then this might be a better way to go:

self.class.adapter.remove(
  self,
  Organization
    .find_roles(:any, organization),
  organization)

Rolify::Adapter::RoleAdapter


问:
DB replication behind the scenes
Tried searching a lot on internet, but could not find any satisfactory information.
We create DB replicas so that the Primary DB instance does not have to deal with load of read queries, and the replica instances does not have deal with load from write queries. But, eventually the primary DB instance will have to somehow send write queries to replica instances. So does these replication write queries not increase load on replica instances? I know that it does not, but why not?
Secondly, since that our primary DB instance is now also responsible for replicating data across replica instances, does that not increase load on primary DB instance?
I am coming from AWS background, dealing with RDS instances and read replicas.</p>

答:
Does these replication write queries not increase load on replica
instances?

Yes, they are write operations, but that is how they stay sync'd - the read replica's are replicating on the WAL (check the note disclaimer below as not all replication is from the WAL) of the primary writer node, so their replication is merely a shadow of what the writer node has already experienced.

If the primary node has a long standing query, the replica sizing is not reflecting the storage sizing of the primary, etc... You might be become a victim of Replication Lag

Since that our primary DB instance is now also responsible for
replicating data across replica instances, does that not increase load
on primary DB instance?

Sure - any I/O operation is a computing cost, but the replication activities are managed by AWS off the primary node. That's what you are paying for when using the managed DBMS, the low level storage volume that the primary (writer) is using also being read and replicated by AWS

The DB cluster volume is physically made up of multiple copies of the
data for the DB cluster. The primary instance and the Aurora Replicas
in the DB cluster all see the data in the cluster volume as a single
logical volume.

take a read of the replication documentation provided by AWS

Note: The type of DB you are running also effects the replication method - AWS doc

Title: DB replication behind the scenes


问:
Text Inside of Object HTML
Tried everything and need some help. I'm trying to have text inside of the hexagon objects, but nothing is working. I can change the background-color of individual hexagons, add URLs, etc. However, I just want to put text inside of them and everything I have tried is not working correctly.

Code example here: https://jsfiddle.net/nullbyte/7dtbpu6f/20/

```<code>        <div class="lab_item">
        <div class="hexagon hexagon2">
            <div class="hexagon-in1">
                <div class="hexagon-in2" style="background-color: black; color: red;">test string</div>
</code>```

Thoughts? I've looked at this for hours now so maybe I'm missing something extremely easy.

Disclosure: I'm learning HTML/CSS and used this sample for hands on learning and to supplement my reading. Original credit to the creator: https://codepen.io/onediv/pen/npEWrj

答:
Your text is there, but its being obscured by all your masks because its not centered and all your divs extend way outside the visible hexagon (explanatory image below)

So all you need is to center the text for it to show up. There is many ways to do it, one easy way is to use flexbox (more information here)

so just add

```<code>display: flex;
align-items: center;
justify-content: center;
</code>```

to the div of your element and you are good

Here its a working example:

https://jsfiddle.net/3q89cnkg/

Title: Text Inside of Object HTML

Body:
Tried everything and need some help. I'm trying to have text inside of the hexagon objects, but nothing is working. I can change the background-color of individual hexagons, add URLs, etc. However, I just want to put text inside of them and everything I have tried is not working correctly.

Code example here: https://jsfiddle.net/nullbyte/7dtbpu6f/20/

test string

Thoughts? I've looked at this for hours now so maybe I'm missing something extremely easy.

Disclosure: I'm learning HTML/CSS and used this sample for hands on learning and to supplement my reading. Original credit to the creator: https://codepen.io/onediv/pen/npEWrj

Body:
Your text is there, but its being obscured by all your masks because its not centered and all your divs extend way outside the visible hexagon (explanatory image below)

So all you need is to center the text for it to show up. There is many ways to do it, one easy way is to use flexbox (more information here)

so just add

display: flex;
align-items: center;
justify-content: center;

to the div of your element and you are good

Here its a working example:

https://jsfiddle.net/3q89cnkg/


问:
OpenFileDialog InitialDirectory doesn't work
I have this code:

```<code>OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = GetDataPath(...);
dialog.AutoUpgradeEnabled = false;
dialog.Filter = GetFilter(...);
if (dialog.ShowDialog(this) == DialogResult.OK)
{...}
</code>```

I expect, at every run, to have the dialog in same folder - GetDataPath(...) folder, but it remains in the last selected folder.

Is this the correct behavior? Do you know how to fix this? If Windows saves last used path in registry do you know how to find it?

EDIT1:

With:

```<code>dialog.AutoUpgradeEnabled = true;
</code>```

is working as expected...

EDIT2: same problem as here Any known problems with getting SaveFileDialog's InitialDirectory property working in Windows 7?

答:
None of the other answers worked for me. See below

Use GetFolderPath for OpenFileDialog object's InitialDirectory.

```<code>using (this.openFile)
{
    this.openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
}
</code>```

this.openFile is just a OpenFileDialog object added to form instead of creating a new object in code.

Body:
I have this code:

OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = GetDataPath(...);
dialog.AutoUpgradeEnabled = false;
dialog.Filter = GetFilter(...);
if (dialog.ShowDialog(this) == DialogResult.OK)
{...}

I expect, at every run, to have the dialog in same folder - GetDataPath(...) folder, but it remains in the last selected folder.

Is this the correct behavior? Do you know how to fix this? If Windows saves last used path in registry do you know how to find it?

EDIT1:

With:

dialog.AutoUpgradeEnabled = true;

is working as expected...

EDIT2: same problem as here Any known problems with getting SaveFileDialog's InitialDirectory property working in Windows 7?

Body:
None of the other answers worked for me. See below

Use GetFolderPath for OpenFileDialog object's InitialDirectory.

using (this.openFile)
{
    this.openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
}

this.openFile is just a OpenFileDialog object added to form instead of creating a new object in code.


问:
Invalid Login attempt while accessing Netsuite using RESTlet?
I am trying to get data from Netsuite using RESTlet. For that, i am using the following details in PHP:

Consumer Key

Consumer Secret

Script Id

Deploy Id

Access Token Id

Access Token Secret

At first time of using these details, i got that error is Invalid login attempt.
I found why it is coming , because of the following any one or all of the wrong details.

Consumer Key

Consumer Secret

Access Token Id

Access Token Secret

After giving correct details it works fine and i stored all these details in DB. I didn't change anything. But after few days i am getting the same error.

I want to know whether the access token will expire after some days or why the error is coming.

答: I was testing on a sandbox and sb1 should be xxxxxx-SB1 on the URL and Realm should be xxxx_SB1</p>


问:
I am trying to create 4 buttons in HTML that calls the following functions such as Adding, Subtracting, Multiplying, dividing
I am new to JavaScript and I'm a bit confused about what I'm doing wrong. For this Assignment I need to create 4 buttons in HTML that calls the following functions such as adding, subtracting, multiplying and dividing. I am suppose to prompt the user to enter two numbers and then it will calculate it.

I figured out how to make one adding button but for some reason I am having trouble creating the other buttons for - * /. I am also not sure why it doesn't keep track of the calculations for the subtraction buttons and etc. I am kind of confused how to create multiple functions and buttons all in one program.

function add() {

  var num1, num2, num3;

  numAdd1 = parseInt(prompt("Enter First Number:"));
  numAdd2 = parseInt(prompt("Enter Second Number:"));
  numAdd3 = numAdd1 + numAdd2

  resultAdd = "Result is " + String(numAdd3)
  //document.write(numAdd3 + "
")

  document.getElementById("result").innerHTML = resultAdd;

}

function sub() {

  var sub1, sub2, sub3;

  sub1 = parseInt(prompt("Enter First Number:"));
  sub2 = parseInt(prompt("Enter Second Number:"));
  sub3 = sub1 - sub2

  result2 = "result is : " + String(numSub3)
  //document.write(Sub3 + "
")

  document.getElementById("result2").innerHTML = result2;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="add()">Press to Add</button>
<p id="result">Result:</p>

<button onclick="sub()">Press to Subtract</button>
<p id="result2">Result:</p>

<button onclick="Multiply()">Press to Multiply</button>
<p id="result">Result:</p>

<button onclick="Divide()">Press to Divide</button>
<p id="result2">Result:</p></code>```

答:
Welcome, and good luck with the assignment.  Nice start!

I would recommend using input elements for your numeric inputs, as I have shown in this partial example.  Also, be sure to shoot for consistency in your variable naming and general code layout.  The sooner you develop those habits the better.

And challenge yourself to add a few bells and whistles!

function run(operator) {
  const values = getValues();
  const result = calculate(values.left, values.right, operator);
  writeResult(result);
}

function calculate(left, right, operator) {

  if (operator === '+') {
    return left + right;
  }
  if (operator === '-') {
    return left - right;
  }
  /*
  add rest of operations...
  */
  throw Error('Invalid operator passed in');
}

function getValues() {
  return {
    left: +document.getElementById('left').value,
    right: +document.getElementById('right').value,
  }
}

function writeResult(result) {
  document.getElementById('result').innerText = result;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="left" />
<input type="number" id="right" />
<br/>
<button onclick="run('+')">Add</button>
<button onclick="run('-')">Subtract</button> ...more buttons
<div id="result"></div></code>```

Body:
I am new to JavaScript and I'm a bit confused about what I'm doing wrong. For this Assignment I need to create 4 buttons in HTML that calls the following functions such as adding, subtracting, multiplying and dividing. I am suppose to prompt the user to enter two numbers and then it will calculate it.

I figured out how to make one adding button but for some reason I am having trouble creating the other buttons for - * /. I am also not sure why it doesn't keep track of the calculations for the subtraction buttons and etc. I am kind of confused how to create multiple functions and buttons all in one program.

function add() {

  var num1, num2, num3;

  numAdd1 = parseInt(prompt("Enter First Number:"));
  numAdd2 = parseInt(prompt("Enter Second Number:"));
  numAdd3 = numAdd1 + numAdd2

  resultAdd = "Result is " + String(numAdd3)
  //document.write(numAdd3 + "
")

  document.getElementById("result").innerHTML = resultAdd;

}

function sub() {

  var sub1, sub2, sub3;

  sub1 = parseInt(prompt("Enter First Number:"));
  sub2 = parseInt(prompt("Enter Second Number:"));
  sub3 = sub1 - sub2

  result2 = "result is : " + String(numSub3)
  //document.write(Sub3 + "
")

  document.getElementById("result2").innerHTML = result2;

}

<button onclick="add()">Press to Add</button>

Result:

<button onclick="sub()">Press to Subtract</button>

Result:

<button onclick="Multiply()">Press to Multiply</button>

Result:

<button onclick="Divide()">Press to Divide</button>

Result:

Body:
Welcome, and good luck with the assignment.  Nice start!

I would recommend using input elements for your numeric inputs, as I have shown in this partial example.  Also, be sure to shoot for consistency in your variable naming and general code layout.  The sooner you develop those habits the better.

And challenge yourself to add a few bells and whistles!

function run(operator) {
  const values = getValues();
  const result = calculate(values.left, values.right, operator);
  writeResult(result);
}

function calculate(left, right, operator) {

  if (operator === '+') {
    return left + right;
  }
  if (operator === '-') {
    return left - right;
  }
  /*
  add rest of operations...
  */
  throw Error('Invalid operator passed in');
}

function getValues() {
  return {
    left: +document.getElementById('left').value,
    right: +document.getElementById('right').value,
  }
}

function writeResult(result) {
  document.getElementById('result').innerText = result;
}

<input type="number" id="left" />
<input type="number" id="right" />
<br/>
<button onclick="run('+')">Add</button>
<button onclick="run('-')">Subtract</button> ...more buttons
<div id="result"></div>


问:
React app using json server, unable to render data from server
I am trying to fetch some data with useEffect from json server but I am having the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'questionText'). I was able to display the data before replicating data base with json server. Any help would be appreciated. Thanks in advance.</p>
```<code>import {useState, useEffect} from 'react';

const QuestionSection = () => {
    const [questions, setQuestions] = useState([]);
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [showScore, setShowScore] = useState(false);
    const [score, setScore] = useState(0);

    useEffect(() => {
        const getQuestions = async () => {
            const questionsFromServer = await fetchQuestions()
            setQuestions(questionsFromServer)
        }

        getQuestions()
    }, [])
    //Fetch questions
    const fetchQuestions = async () => {
        const res = await fetch ('http://localhost:5000/questions');
        const data = await res.json();

        return data
    }

    const handleAnswerOptionClick = (correct) => {
        if (correct) {
            setScore(score + 1);

        }

        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            setShowScore(true);
        }
    };
  return (
    <questionSection>
    <div className='questionSection'>
            {showScore ? (
                <div className='score-section'>
                    You scored {score} out of {questions.length}
                </div>
            ) : (
                <>
                    <div className='question-section'>
                        <div className='question-count'>
                            <span>Question {currentQuestion + 1}</span>/{questions.length}
                        </div>
                        <div className='question-text'>{questions[currentQuestion].questionText}</div>
                    </div>
                    <div className='answer-section'>
                        {questions[currentQuestion].answerOptions.map((answerOption) => (
                            <button key = {answerOption.id} onClick={() => handleAnswerOptionClick(answerOption.correct)}>{answerOption.answerLetter} {answerOption.answerText}</button>
                        ))}
                    </div>
                </>
            )}
        </div>
    </questionSection>
  )
}

export default QuestionSection
</code>```

答:
Since fetching the questions is an asynchronous action, you have to handle the undefined situation in your code.
An easy fix is to add the ? before the questionText property:

```<code><div className='question-text'>{questions[currentQuestion]?.questionText}</div>
</code>```

The question mark checks if the currentQuestion exists in the questions array, if it does the questionText is displayed.

Body:
I am trying to fetch some data with useEffect from json server but I am having the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'questionText'). I was able to display the data before replicating data base with json server. Any help would be appreciated. Thanks in advance.

import {useState, useEffect} from 'react';

const QuestionSection = () => {
    const [questions, setQuestions] = useState([]);
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [showScore, setShowScore] = useState(false);
    const [score, setScore] = useState(0);

    useEffect(() => {
        const getQuestions = async () => {
            const questionsFromServer = await fetchQuestions()
            setQuestions(questionsFromServer)
        }

        getQuestions()
    }, [])
    //Fetch questions
    const fetchQuestions = async () => {
        const res = await fetch ('http://localhost:5000/questions');
        const data = await res.json();

        return data
    }

    const handleAnswerOptionClick = (correct) => {
        if (correct) {
            setScore(score + 1);

        }

        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            setShowScore(true);
        }
    };
  return (
    <questionSection>

            {showScore ? (

                    You scored {score} out of {questions.length}

            ) : (
                <>

                            Question {currentQuestion + 1}/{questions.length}

{questions[currentQuestion].questionText}

                        {questions[currentQuestion].answerOptions.map((answerOption) => (
                            <button key = {answerOption.id} onClick={() => handleAnswerOptionClick(answerOption.correct)}>{answerOption.answerLetter} {answerOption.answerText}</button>
                        ))}

                </>
            )}

    </questionSection>
  )
}

export default QuestionSection

Body:
Since fetching the questions is an asynchronous action, you have to handle the undefined situation in your code.
An easy fix is to add the ? before the questionText property:

<div className='question-text'>{questions[currentQuestion]?.questionText}</div>

The question mark checks if the currentQuestion exists in the questions array, if it does the questionText is displayed.


问:
trying to ban all but only attempting to ban the bot executing
I'm making a ban all function for proof of concept but whenever I execute it, the code only attempts to ban the bot that is running the command (and fails) and doesn't ban anyone one else, no error message either.
code:</p>
```<code>async def ban(ctx):
        await ctx.message.delete()
        print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} beginning test\n")
        print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} Banning has begun.\n")

        try:
            for member in ctx.guild.members:
                await member.ban()
                print(f"{colorama.Fore.CYAN}Smited {colorama.Fore.YELLOW}{member}.")
        except:
            print(f"{colorama.Fore.CYAN}Unable to ban {colorama.Fore.YELLOW}{member}.")
            pass
</code>```

答:
Place your try statement around the ban function rather than around the for loop

```<code>async def ban(ctx):
    await ctx.message.delete()
    print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} beginning test\n")
    print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} Banning has begun.\n")

    for member in ctx.guild.members:
        try:
            await member.ban()
            print(f"{colorama.Fore.CYAN}Smited {colorama.Fore.YELLOW}{member}.")
        except:
            print(f"{colorama.Fore.CYAN}Unable to ban {colorama.Fore.YELLOW}{member}.")
            continue
</code>```

Body:
I'm making a ban all function for proof of concept but whenever I execute it, the code only attempts to ban the bot that is running the command (and fails) and doesn't ban anyone one else, no error message either.
code:

async def ban(ctx):
        await ctx.message.delete()
        print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} beginning test\n")
        print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} Banning has begun.\n")

        try:
            for member in ctx.guild.members:
                await member.ban()
                print(f"{colorama.Fore.CYAN}Smited {colorama.Fore.YELLOW}{member}.")
        except:
            print(f"{colorama.Fore.CYAN}Unable to ban {colorama.Fore.YELLOW}{member}.")
            pass

Body:
Place your try statement around the ban function rather than around the for loop

async def ban(ctx):
    await ctx.message.delete()
    print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} beginning test\n")
    print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} Banning has begun.\n")

    for member in ctx.guild.members:
        try:
            await member.ban()
            print(f"{colorama.Fore.CYAN}Smited {colorama.Fore.YELLOW}{member}.")
        except:
            print(f"{colorama.Fore.CYAN}Unable to ban {colorama.Fore.YELLOW}{member}.")
            continue


问:
std::auto_ptr<T> Usage
I've read a reasonable amount in decent textbooks about the auto_ptr class.  While I understand what it is, and how it gets you around the problem of getting exceptions in places like constructors, I am having trouble figuring out when someone would actually use it.

An auto_ptr can only hold a single type (no array new[] initialization is supported).  It changes ownership when you pass it into functions or try and duplicate it (it's not a reference counting smart pointer).

What is a realistic usage scenario for this class give its limitations?  It seems like most of the textbook examples of its use are reaching because there isn't even a reason to be using a pointer over a stack variable in most of the cases...

Anyway, I'll stop my rant - but if you can provide a short example/description or a link to a good usage scenario for this I'd be grateful.  I just want to know where I should use it in practice in case I come across the situation - I like to practice what I learn so I remember it.

答: auto_ptr has been deprecated in the now finalized C++11 standard. Some of the replacements are already available through TR1 or the Boost libraries. Examples are shared_ptr and unique_ptr (scoped_ptr in boost).

Title: std::auto_ptr<T> Usage


问:
{ detail: 'Authentication credentials were not provided.' }
i am trying to call api ("https://wger.de/api/v2/day/") to get some data , it require me to provide token with header in order to authorize i am passing same  , but whenever i am trying to make call i am getting error "data: { detail: 'Authentication credentials were no provided}"</p>
```<code>app.get("/workout", async (req, res) => {
    try {
        const response = await axios({
            url: "https://wger.de/api/v2/day/",
            method: "get",
            headers: {
                "content-type": "application/json",
                Authorization: 'Bearer ' + token
              },
        });

        res.status(200).json(response.data);

    } catch (err) {
        console.log(err);
        res.status(500).json({ message: err });

    }
});
</code>```

答:
Where are you getting the token variable from? Is that something that exists in a larger scope or is that something you need to be passing to your get?

Taking a look at the api you provided - it looks like you need to pass your authenticaion another way and without the Bearer keyword

I would try to reformat it to fit the example and see if that works?
Like this:

Authentication: 'Token' + token

I found this under the Tools - https://wger.de/en/software/api

```<code># In the terminal, e.g. bash
curl -H "Authorization: Token 123456..." \
     -H "Accept: application/json; indent=4" \
     -X PATCH --data '{"key": value, ...}' \
     --dump-header -
     https://wger.de/api/v2/....
# In the python console
>>> import requests
>>> import json
>>> from pprint import pprint
>>>
>>> url = 'https://wger.de/api/v2/....'
>>> data = '{"key": "value"}'
>>> headers = {'Accept': 'application/json',
               'Authorization': 'Token 12345...'}
>>> r = requests.patch(url=url, data=data, headers=headers)
>>> r
>>> r.content
>>> pprint(json.loads(r.content))
</code>```

Body:
i am trying to call api ("https://wger.de/api/v2/day/") to get some data , it require me to provide token with header in order to authorize i am passing same  , but whenever i am trying to make call i am getting error "data: { detail: 'Authentication credentials were no provided}"

app.get("/workout", async (req, res) => {
    try {
        const response = await axios({
            url: "https://wger.de/api/v2/day/",
            method: "get",
            headers: {
                "content-type": "application/json",
                Authorization: 'Bearer ' + token
              },
        });

        res.status(200).json(response.data);

    } catch (err) {
        console.log(err);
        res.status(500).json({ message: err });

    }
});

Body:
Where are you getting the token variable from? Is that something that exists in a larger scope or is that something you need to be passing to your get?

Taking a look at the api you provided - it looks like you need to pass your authenticaion another way and without the Bearer keyword

I would try to reformat it to fit the example and see if that works?
Like this:

Authentication: 'Token' + token

I found this under the Tools - https://wger.de/en/software/api

# In the terminal, e.g. bash
curl -H "Authorization: Token 123456..." \
     -H "Accept: application/json; indent=4" \
     -X PATCH --data '{"key": value, ...}' \
     --dump-header -
     https://wger.de/api/v2/....
# In the python console
>>> import requests
>>> import json
>>> from pprint import pprint
>>>
>>> url = 'https://wger.de/api/v2/....'
>>> data = '{"key": "value"}'
>>> headers = {'Accept': 'application/json',
               'Authorization': 'Token 12345...'}
>>> r = requests.patch(url=url, data=data, headers=headers)
>>> r
>>> r.content
>>> pprint(json.loads(r.content))


问:
Get the variable value of assigned class
im learning to make an organizational chart using class

```<code>class employee:
    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

abcde = employee("Elon Musk", "CEO",1000000)
print(employee.self) --> error
</code>```

Basically what im trying to do is to get the "abcde" value, to use it on my other function..

is there anyway to get the name assigned to the object? in this case "abcde"

Recreating this post to clarify what im trying to do:

I simplified the complete code that i have here, but basically what im trying to do here is getting the assigned class name, in this case "abcde".

i understand that self.name will get me "elon musk:
self.title will get me "CEO"

but how do i get the "abcde"?

why do i need the abcde?
because i need to append the abcde to a list called

direct_report_list= []

to append the "abcde" inside this list, which i will use for this:

```<code>def __str__(self):

           otheremp_list = []

           print(self.title,” – “, self.name)

           print(“Direct Reports:”)

           for emp in self.direct_reports_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*

           print(“other employees:”)

           for emp in otheremp_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*
</code>```

i need the "abcde" value so i can add this value into my list, which i use for the "emp" in str

答:
Looks like you have just started learning classes. I will try to clarify a few aspects that i think may be causing this confusion.

Remember a self keyword for a class is relevant only inside the class to refer to its own objects, and that is why you were able to use self.title in the class

When you create an object abcde you already have the object named abcde; you do not need to refer to it as employee.self.

Hence if you simply want to pass that as an object just pass by what it is actually named i.e. just abcde. Below code may make it more clear!

```<code>class employee:
    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

def simplefunc(obj):
    print(obj.name)

abcde = employee("Elon Musk", "CEO",1000000)
#print(employee.self) --> Causes an Error

print(abcde)
simplefunc(abcde)
</code>```

Body:
im learning to make an organizational chart using class

class employee:
    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

abcde = employee("Elon Musk", "CEO",1000000)
print(employee.self) --> error

Basically what im trying to do is to get the "abcde" value, to use it on my other function..

is there anyway to get the name assigned to the object? in this case "abcde"

Recreating this post to clarify what im trying to do:

I simplified the complete code that i have here, but basically what im trying to do here is getting the assigned class name, in this case "abcde".

i understand that self.name will get me "elon musk:
self.title will get me "CEO"

but how do i get the "abcde"?

why do i need the abcde?
because i need to append the abcde to a list called

direct_report_list= []

to append the "abcde" inside this list, which i will use for this:

def __str__(self):

           otheremp_list = []

           print(self.title,” – “, self.name)

           print(“Direct Reports:”)

           for emp in self.direct_reports_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*

           print(“other employees:”)

           for emp in otheremp_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*

i need the "abcde" value so i can add this value into my list, which i use for the "emp" in str

Body:
Looks like you have just started learning classes. I will try to clarify a few aspects that i think may be causing this confusion.

Remember a self keyword for a class is relevant only inside the class to refer to its own objects, and that is why you were able to use self.title in the class

When you create an object abcde you already have the object named abcde; you do not need to refer to it as employee.self.

Hence if you simply want to pass that as an object just pass by what it is actually named i.e. just abcde. Below code may make it more clear!

class employee:
    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

def simplefunc(obj):
    print(obj.name)

abcde = employee("Elon Musk", "CEO",1000000)
#print(employee.self) --> Causes an Error

print(abcde)
simplefunc(abcde)


问:
(when adding jar) - Module "android" must not contain source root
I'm trying to add gdx-tools.jar to a libGDX project in IntelliJ. The result:

Module "android" must not contain source root ".../android/src". The
  root already belongs to module "android".

This is what I've tried:

project structure > libraries > new project library > java > select "gdx-tools.jar" >select module "desktop"

project structure > modules > select "desktop" > new > jars or directories > select "gdx-tools.jar" >

Ideas?

答:
open:

file > project structure > modules
you will see 2 models

"project name"

"project name"_android

just delete "project name"_android in the module, that solved the problem for me.


问:
Android how to draw line?

Possible Duplicate:

  How do you set a line's width when drawing in Android?

I've seen How to draw a line in android but how can I set line width? I tried to set Paint

```<code>    colorCenter = new Paint();
    colorCenter.setAntiAlias(true);
    colorCenter.setStrokeWidth(100);
    colorCenter.setColor(0xFF00FFFF);
</code>```

then in onDraw()

```<code>canvas.drawLine(0, 0, 40, 40, colorCenter);
</code>```

but it always 1px.

I also tried to find class LineShape and use it with ShapeDrawable, but there is no such class!

答: get the Canvas and use drawLine(startX, startY, stopX, stopY, paint)</p>

Title: Android how to draw line?

Body:
Possible Duplicate:

  How do you set a line's width when drawing in Android?

I've seen How to draw a line in android but how can I set line width? I tried to set Paint

    colorCenter = new Paint();
    colorCenter.setAntiAlias(true);
    colorCenter.setStrokeWidth(100);
    colorCenter.setColor(0xFF00FFFF);

then in onDraw()

canvas.drawLine(0, 0, 40, 40, colorCenter);

but it always 1px.

I also tried to find class LineShape and use it with ShapeDrawable, but there is no such class!


问:
How to make program wait for further input?
If I run the below program and enter an answer (e.g. "3 years") the program completes without waiting for any further input e.g.:

```<code>How long did the christians walk for the crusade? :3 years
Correct!
How many of the crusades were won by christians? :Incorrect.
Who started the crusades? :Incorrect.
Thank you for playing!
</code>```

How can I make it wait for answers to the other questions?

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Printf("How long did the christians walk for the crusade? :")
    scanner.Scan()
    input := scanner.Text()

    if input == "3 years" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("How many of the crusades were won by christians? :")

    if input == "1" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("Who started the crusades? :")

    if input == "the pope" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("Thank you for playing!")
    time.Sleep(2 * time.Hour)
}
```

答:
scanner.Scan()
input := scanner.Text()
```
<p>The above will accept a single line of input and store the result in the variable <code>input</code>.</p>
<p>So when your program runs it asks the first question and waits for an answer; lets say I answer with "1 day" then <code>input == "1 day"</code>. The value of <code>Input</code> is not changed after that point - you are comparing the first value the user enters against multiple answers i.e. <code>"1 day" == "3 years"</code> and <code>"1 day" == "the pope"</code>.</p>
<p>If you want to accept additional lines you will need to repeat the call e.g.</p>
<pre class="lang-golang prettyprint-override"><code>scanner.Scan()
input := scanner.Text()

if input == "3 years" {
    fmt.Println("Correct!")
} else {
    fmt.Println("Incorrect.")
}

fmt.Printf("How many of the crusades were won by christians? :")
scanner.Scan() // Get next answer from scanner
input = scanner.Text()

if input == "1" {
    fmt.Println("Correct!")
} else {
    fmt.Println("Incorrect.")
}
</code>```

Note that you can simplify this considerably by using a function:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    s := bufio.NewScanner(os.Stdin)

    askQuestion(s, "How long did the christians walk for the crusade? :", "3 years")
    askQuestion(s, "How many of the crusades were won by christians? :", "1")
    askQuestion(s, "Who started the crusades? :", "the pope")

    fmt.Printf("Thank you for playing!")
}

func askQuestion(s *bufio.Scanner, question string, answer string) {
    fmt.Print(question)
    if !s.Scan() {
        panic(fmt.Sprintf("scan failed: %s", s.Err()))
    }
    if s.Text() == answer {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }
}
```

Body:
If I run the below program and enter an answer (e.g. "3 years") the program completes without waiting for any further input e.g.:

How long did the christians walk for the crusade? :3 years
Correct!
How many of the crusades were won by christians? :Incorrect.
Who started the crusades? :Incorrect.
Thank you for playing!

How can I make it wait for answers to the other questions?

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Printf("How long did the christians walk for the crusade? :")
    scanner.Scan()
    input := scanner.Text()

    if input == "3 years" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("How many of the crusades were won by christians? :")

    if input == "1" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("Who started the crusades? :")

    if input == "the pope" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("Thank you for playing!")
    time.Sleep(2 * time.Hour)
}

Body:
scanner.Scan()
input := scanner.Text()

The above will accept a single line of input and store the result in the variable input.

So when your program runs it asks the first question and waits for an answer; lets say I answer with "1 day" then input == "1 day". The value of Input is not changed after that point - you are comparing the first value the user enters against multiple answers i.e. "1 day" == "3 years" and "1 day" == "the pope".

If you want to accept additional lines you will need to repeat the call e.g.

scanner.Scan()
input := scanner.Text()

if input == "3 years" {
    fmt.Println("Correct!")
} else {
    fmt.Println("Incorrect.")
}

fmt.Printf("How many of the crusades were won by christians? :")
scanner.Scan() // Get next answer from scanner
input = scanner.Text()

if input == "1" {
    fmt.Println("Correct!")
} else {
    fmt.Println("Incorrect.")
}

Note that you can simplify this considerably by using a function:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    s := bufio.NewScanner(os.Stdin)

    askQuestion(s, "How long did the christians walk for the crusade? :", "3 years")
    askQuestion(s, "How many of the crusades were won by christians? :", "1")
    askQuestion(s, "Who started the crusades? :", "the pope")

    fmt.Printf("Thank you for playing!")
}

func askQuestion(s *bufio.Scanner, question string, answer string) {
    fmt.Print(question)
    if !s.Scan() {
        panic(fmt.Sprintf("scan failed: %s", s.Err()))
    }
    if s.Text() == answer {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }
}


问:
Why do non-exhaustive guards cause irrefutable pattern match to fail?
I have this function in Haskell:

```<code>test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing
</code>```

This is what I got when I tried the function with different inputs:

```<code>ghci>test 3 4
Nothing
ghci>test 3 3
Just 3
</code>```

According to Real World Haskell, the first pattern is irrefutable.  But it seems like test 3 4 doesn't fails the first pattern, and matches the second.  I expected some kind of error -- maybe 'non-exhaustive guards'.  So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?

答:
The compiler should be warning you if you leave out the second clause, i.e. if your last match has a set of guards where the last one is not trivially true.

Generally, testing guards for completeness is obviously not possible, as it would be as hard as solving the halting problem.

Answer to Matt's comment:

Look at the example:

```<code>foo a b
   | a <= b = True
   | a >  b = False
</code>```

A human can see that one of both guards must be true. But the compiler does not know that either a <= b or a > b.

Now look for another example:

```<code>fermat a b c n
    | a^n + b^n /= c^n = ....
    | n < 0 = undefined
    | n < 3 = ....
</code>```

To prove that the set of guards is complete, the compiler had to prove Fermat's Last Theorem. It's impossible to do that in a compiler. Remember that the number and complexity of the guards is not limited. The compiler would have to be a general solver for mathematical problems, problems that are stated in Haskell itself.

More formally, in the easiest case:

```<code> f x | p x = y
</code>```

the compiler must prove that if p x is not bottom, then p x is True for all possible x. In other words, it must prove that either p x is bottom (does not halt) no matter what x is or evaluates to True.

Body:
I have this function in Haskell:

test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing

This is what I got when I tried the function with different inputs:

ghci>test 3 4
Nothing
ghci>test 3 3
Just 3

According to Real World Haskell, the first pattern is irrefutable.  But it seems like test 3 4 doesn't fails the first pattern, and matches the second.  I expected some kind of error -- maybe 'non-exhaustive guards'.  So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?

Body:
The compiler should be warning you if you leave out the second clause, i.e. if your last match has a set of guards where the last one is not trivially true.

Generally, testing guards for completeness is obviously not possible, as it would be as hard as solving the halting problem.

Answer to Matt's comment:

Look at the example:

foo a b
   | a <= b = True
   | a >  b = False

A human can see that one of both guards must be true. But the compiler does not know that either a <= b or a > b.

Now look for another example:

fermat a b c n
    | a^n + b^n /= c^n = ....
    | n < 0 = undefined
    | n < 3 = ....

To prove that the set of guards is complete, the compiler had to prove Fermat's Last Theorem. It's impossible to do that in a compiler. Remember that the number and complexity of the guards is not limited. The compiler would have to be a general solver for mathematical problems, problems that are stated in Haskell itself.

More formally, in the easiest case:

 f x | p x = y

the compiler must prove that if p x is not bottom, then p x is True for all possible x. In other words, it must prove that either p x is bottom (does not halt) no matter what x is or evaluates to True.


问:
Why is there no .NET Core options displayed in the console app for Visual Studio for Mac?
I created a new Console App in Visual Studio for Mac.  Right click the project => options => Build => General.

I expect to see .NET core versions here.  3.1, 5.0, 6.0 apparently are .NET core versions.  These look like standard .NET versions.  So is standard .NET now running on Mac? Last I heard .NET core was created for cross-operating system compatibility.

答:
yes you are right .Net Core was created for cross-operating system compatibility.
When you choose the project type in Visual Studio you can choose between two Console Applications, one with .Net Framework and the other one for .Net Core.</p>


问:
Is it possible to export to body of two different files from main.js?
I want to export components to multiple files from main.js, something like this:

main.js:

```<code>import Block1 from './Block1.svelte';
import Block2 from './Block2.svelte';

export const Block1  = new Block1({ target: document.body}); //to index.html
export const Block2  = new Block2({ target: document.body}); //to index2.html
</code>```

How to compile multiple .html files to public directory in svelt js?

答:
I found this repository:

https://github.com/Tom-Siegel/multi-page-svelte

Works well and is possible to add multiple pages as inputs

```<code>const inputs = [
  "main", //string defaults to input: src/[name].js and output: public/build/[name].js
  {
    input: "src/second.js",
    output: { file: "public/build/second.js", name: "second" },
    css: "public/build/second.css",
  }, //object for setting more specific values for input and output of roolup configuration
];
</code>```

Body:
I want to export components to multiple files from main.js, something like this:

main.js:

import Block1 from './Block1.svelte';
import Block2 from './Block2.svelte';

export const Block1  = new Block1({ target: document.body}); //to index.html
export const Block2  = new Block2({ target: document.body}); //to index2.html

How to compile multiple .html files to public directory in svelt js?

Body:
I found this repository:

https://github.com/Tom-Siegel/multi-page-svelte

Works well and is possible to add multiple pages as inputs

const inputs = [
  "main", //string defaults to input: src/[name].js and output: public/build/[name].js
  {
    input: "src/second.js",
    output: { file: "public/build/second.js", name: "second" },
    css: "public/build/second.css",
  }, //object for setting more specific values for input and output of roolup configuration
];


问:
How to stop catching signal(Ctrl + c) exception in debug mode
I'm implementing std::signal into my server application to shut it down safely.

```<code>void signal_handler(int signal)
{
    if (signal == SIGINT)
    {
        std::cout << "Hello.\n";
        exit(signal);
    }
}

void threadFunc()
{
    while (gLoop)
    {
        std::cout << "Hello..\n";
        std::this_thread::sleep_for(1s);
    }
}

int main()
{
    std::signal(SIGINT, signal_handler);
    std::thread thrd{ threadFunc };
    thrd.join();
}
</code>```

This is an example code

It works fine when I run it as release mode..

But it stops when I press Ctrl+c in debug mode and of course notify me that exception occurred.

I just want it to ignore the exception and see what I've done something wrong in the terminating process (memory leaks, violation exception etc.)

Is there anyway that I can do for it?

答:
I figured it out just a second after I post this!
I can do it by just disabling catch this exception next time setting in the exception box.

Body:
I'm implementing std::signal into my server application to shut it down safely.

void signal_handler(int signal)
{
    if (signal == SIGINT)
    {
        std::cout << "Hello.\n";
        exit(signal);
    }
}

void threadFunc()
{
    while (gLoop)
    {
        std::cout << "Hello..\n";
        std::this_thread::sleep_for(1s);
    }
}

int main()
{
    std::signal(SIGINT, signal_handler);
    std::thread thrd{ threadFunc };
    thrd.join();
}

This is an example code

It works fine when I run it as release mode..

But it stops when I press Ctrl+c in debug mode and of course notify me that exception occurred.

I just want it to ignore the exception and see what I've done something wrong in the terminating process (memory leaks, violation exception etc.)

Is there anyway that I can do for it?


问:
Real world comparisons of Glassfish and JBoss 5?
Does anyone have experiences with both in the real world?  How do they compare in terms of performance (memory usage, speed, etc)?  Stability?

Does JBoss Seam work well on Glassfish?

答: I will have to go with Glassfish on this. Deploying a diverse range of application built on different webservices, we had major compatibility issues, resulting in customizing the class loading & still faced many issues. Glassfish I never faced any such issues.</p>

ContentLicense: CC BY-SA 2.5