问:
jQuery mobile $(document).ready equivalent
in ajax navigation pages, the classic "document ready" form for performing initialization javascript simply doesn't fire.

What's the right way to execute some code in an ajax loaded page?

(I mean, not my ajax... it's the jquery mobile page navigation system which brings me to that page)

Ok, I did suspect something like that... thanks a lot =) But... it still doesn't work, here's my code:

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

```<code><head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mypage</title>

    <link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />
    <script type="text/javascript" src="jquery-1.5.min.js"></script>
    <script type="text/javascript" src="jquery.mobile-1.0a4.min.js"></script>
    <script type="text/javascript">
        $('div').live('pageshow',function(event, ui){
          alert('ciao');
        });
    </script>

</head>

<body>

    <div data-role="page">

        <div data-role="header" data-position="fixed">
            <h1>Shopping Cart</h1>
        </div>

        <div data-role="content"> asd

        </div>

    </div>

</body>
</code>```

Do I need to specify the div id?

答:
I spent some time on researching the same since JQM docs are not very detailed at this point. Solution below works fine for me:

```<code><script type="text/javascript">
$('div:jqmData(role="page")').live('pagebeforeshow',function(){
    // code to execute on each page change
});
</script>
</code>```

You have to implement your own checking flow in order to prevent multiple initialization since the code above will run on every page change

Body:
in ajax navigation pages, the classic "document ready" form for performing initialization javascript simply doesn't fire.

What's the right way to execute some code in an ajax loaded page?

(I mean, not my ajax... it's the jquery mobile page navigation system which brings me to that page)

Ok, I did suspect something like that... thanks a lot =) But... it still doesn't work, here's my code:

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

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

    <link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />

Shopping Cart

 asd

Do I need to specify the div id?

Body:
I spent some time on researching the same since JQM docs are not very detailed at this point. Solution below works fine for me:

<script type="text/javascript">
$('div:jqmData(role="page")').live('pagebeforeshow',function(){
    // code to execute on each page change
});
</script>

You have to implement your own checking flow in order to prevent multiple initialization since the code above will run on every page change


来源: stackexchange

问:
Transition to UITabBarController
I need help with bug fix. I'm use segue to transit between ViewControllers.

I have UITabBarController with one UIViewController. When I click on button in my vc I move to second vc. My second vc doesn't have TabBar. (use segue). In my second vc I have button and UIAlertController. When I click on button or alert I must transit to first vc with TabBar, but my TabBar doesn't displayed. How to fix this ? I don't need to use NavigationController.

```<code>let alert = UIAlertController(title: "Поздравляю", message: "Тренировка окончена", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: { action in self.performSegue(withIdentifier: "backSegue", sender: self) }))
        self.present(alert, animated: true, completion: nil)
</code>```

StoryBoard

答:
If you are presenting the second ViewController modally add this to your UIAlertController action:</p>

```<code>self.dismiss(animated: true, completion: nil)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Transition to UITabBarController

Body:
I need help with bug fix. I'm use segue to transit between ViewControllers.

I have UITabBarController with one UIViewController. When I click on button in my vc I move to second vc. My second vc doesn't have TabBar. (use segue). In my second vc I have button and UIAlertController. When I click on button or alert I must transit to first vc with TabBar, but my TabBar doesn't displayed. How to fix this ? I don't need to use NavigationController.

let alert = UIAlertController(title: "Поздравляю", message: "Тренировка окончена", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: { action in self.performSegue(withIdentifier: "backSegue", sender: self) }))
        self.present(alert, animated: true, completion: nil)

StoryBoard

Body:
If you are presenting the second ViewController modally add this to your UIAlertController action:

self.dismiss(animated: true, completion: nil)


问:
Mongo-go how to use arrayFilter to find elem in "array of objects inside array of objects"
Lets imagine a JSON like:

```<code>"user": {
  "id": "1234",
  ...some fields,
  "achievements": [
    {
      "scope": "life achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
    {
      "scope": "sport achievements",
      "list": [
        {"_id": 1, "title": "sport", "gotAt": "some date"},
        {"_id": 2, "title": "some other sport", "gotAt": "some date"}
      ]
    },
    {
      "scope": "academic achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
  ]
}
</code>```

I need to UPDATE for example the first life achievement (with id 1) using mongoDb and Golang driver Mongo-go for it

The problem is in the nesting level. I can get some array element by $ mongoDb operator, but here i need to identify every user achievement by the activity scope (life, sport, academic etc) and _id field of achievement. So I need to make a search inside an array of objects inside other array of objects.

Thats what ive done (it doesnt work anyway)

doc := coll.FindOneAndUpdate(
        context.Background(),
        bson.D{
            {"_id", "1234"},
            {"achievements.scope", "life achievements"},
            {"achievements.list._id", 1},
        },
        bson.D{
            {"$set", bson.D{
                {"achievements.$.list.$[elem].title", "some new test"},
            }},
        },
        options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
            Filters: append(make([]interface{}, 0), bson.D{
                {"elem", bson.D{
                    {"achievements.list._id", 1},
                }},
            }),
        }).SetReturnDocument(1),
    )
```

I expect this query to update only one element specified by "id" and "scope" fields. May be I use arrayFilters incorretly, or may be I set  param of FindOneAndUpdate function incorrectly. Now it doesnt throw any error nor updates the document. Please help me

答:
So, with help of @owlwalks, we have found the decision:

doc := coll.FindOneAndUpdate(
        context.Background(),
        bson.D{
            {"_id", "1234"},
            {"achievements.scope", "life achievements"},
        },
        bson.D{
            {"$set", bson.D{
                {"achievements.$.list.$[elem].title", "some new text"},
            }},
        },
        options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
            Filters: []interface{}{bson.D{
                    {"elem._id", 1},
                }},
        }).SetReturnDocument(1),
    )
```

Body:
Lets imagine a JSON like:

"user": {
  "id": "1234",
  ...some fields,
  "achievements": [
    {
      "scope": "life achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
    {
      "scope": "sport achievements",
      "list": [
        {"_id": 1, "title": "sport", "gotAt": "some date"},
        {"_id": 2, "title": "some other sport", "gotAt": "some date"}
      ]
    },
    {
      "scope": "academic achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
  ]
}

I need to UPDATE for example the first life achievement (with id 1) using mongoDb and Golang driver Mongo-go for it

The problem is in the nesting level. I can get some array element by $ mongoDb operator, but here i need to identify every user achievement by the activity scope (life, sport, academic etc) and _id field of achievement. So I need to make a search inside an array of objects inside other array of objects.

Thats what ive done (it doesnt work anyway)

doc := coll.FindOneAndUpdate(
        context.Background(),
        bson.D{
            {"_id", "1234"},
            {"achievements.scope", "life achievements"},
            {"achievements.list._id", 1},
        },
        bson.D{
            {"$set", bson.D{
                {"achievements.$.list.$[elem].title", "some new test"},
            }},
        },
        options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
            Filters: append(make([]interface{}, 0), bson.D{
                {"elem", bson.D{
                    {"achievements.list._id", 1},
                }},
            }),
        }).SetReturnDocument(1),
    )

I expect this query to update only one element specified by "id" and "scope" fields. May be I use arrayFilters incorretly, or may be I set  param of FindOneAndUpdate function incorrectly. Now it doesnt throw any error nor updates the document. Please help me


问:
How to connect multiple queries
I created this table with data from the database.
table: https://imgur.com/06xnebJ

I need all the rows with month May to be in 1 row
like this:

May 2019 |  | 3 | 3| 2|
etc.

My DB looks like this:

https://imgur.com/nmwco9y

https://imgur.com/QbdGlzo

So far I got this code

```<code>$tipsportsql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '0' AND komentator1 = '$firstname $lastname' OR projekt = '0' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

$slaviasql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '1' AND komentator1 = '$firstname $lastname' OR projekt = '1' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

$betsql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '2' AND komentator1 = '$firstname $lastname' OR projekt = '2' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");
</code>```

and this

```<code><tbody>
        <?php while ($tip = mysqli_fetch_assoc($tipsportsql)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>

            </td>
            <td>

            </td>
            <td>
                <?=$tip['project']?>
            </td>
        </tr>

        <?php } while ($tip = mysqli_fetch_assoc($slaviasql)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>

            </td>
            <td>

            </td>
            <td>

            </td>
            <td>
                <?=$tip['project']?>
            </td>
        </tr>
        <?php }while ($tip = mysqli_fetch_assoc($betsql)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>

            </td>
            <td>
            <?=$tip['project']?>
            </td>
            <td>

            </td>
            <td>

            </td>
        </tr>
        <?php }?>
    </tbody>
</code>```

I am thankful for any help.

答:
I believe you want a query like this:

```<code>SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
       SUM(projekt = 0) AS project_1,
       SUM(projekt = 1) AS project_2,
       SUM(projekt = 2) AS project_3
FROM zapasy
WHERE CONCAT(?, ?) IN (komentator1, komentator2)
GROUP BY Monthyear;
</code>```

Note in particular the parameter placeholders.  You need to learn how to use parameters so your queries are not vulnerable to unexpected syntax errors and SQL injection attacks.

Title: How to connect multiple queries

Body:
I created this table with data from the database.
table: https://imgur.com/06xnebJ

I need all the rows with month May to be in 1 row
like this:

May 2019 |  | 3 | 3| 2|
etc.

My DB looks like this:

https://imgur.com/nmwco9y

https://imgur.com/QbdGlzo

So far I got this code

$tipsportsql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '0' AND komentator1 = '$firstname $lastname' OR projekt = '0' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

$slaviasql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '1' AND komentator1 = '$firstname $lastname' OR projekt = '1' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

$betsql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '2' AND komentator1 = '$firstname $lastname' OR projekt = '2' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

and this

        <?php while ($tip = mysqli_fetch_assoc($tipsportsql)) {?>

                <?=$tip['Monthyear'] ?>

                <?=$tip['project']?>

        <?php } while ($tip = mysqli_fetch_assoc($slaviasql)) {?>

                <?=$tip['Monthyear'] ?>

                <?=$tip['project']?>

        <?php }while ($tip = mysqli_fetch_assoc($betsql)) {?>

                <?=$tip['Monthyear'] ?>

            <?=$tip['project']?>

        <?php }?>

I am thankful for any help.

Body:
I believe you want a query like this:

SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
       SUM(projekt = 0) AS project_1,
       SUM(projekt = 1) AS project_2,
       SUM(projekt = 2) AS project_3
FROM zapasy
WHERE CONCAT(?, ?) IN (komentator1, komentator2)
GROUP BY Monthyear;

Note in particular the parameter placeholders.  You need to learn how to use parameters so your queries are not vulnerable to unexpected syntax errors and SQL injection attacks.


问:
How efficiently we can get the required output from the list in java?
```<code>CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70
</code>```

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

```<code>Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50
</code>```

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

```<code>for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours
</code>```

Circuit class is having pojo objects with getter setters of this three objects.

```<code> public class Circuit {

        String circuitID;
        int hours;
        String department;
}
</code>```

答:
First write a custom comparator to check for highest hours and evaluate duplicate hours situation to take the one with Electricity department:

```<code>Comparator<Circuit> cmp = new Comparator<Circuit>() {
    @Override
    public int compare(Circuit o1, Circuit o2) {

        int compare = Integer.compare(o1.getHours(), o2.getHours());

        if(compare==0) {  // equal hours so check for department

            // the element with 'Electricity' value must seem to be have max value
            if(o1.getDepartment().equals("Electricity")) {
                compare = 1;
            }
            if(o2.getDepartment().equals("Electricity")) {
                compare = -1;
            }
        }

        return compare;
    }
};
</code>```

Then group by circuitId attribute with Collectors.groupingBy(Circuit::getCircuitId,  and find max hours with the help of custom comparator above Collectors.maxBy(cmp):

```<code>Map<String, Optional<Circuit>> resultMap = circuitList.stream().collect(
                Collectors.groupingBy(Circuit::getCircuitId, Collectors.maxBy(cmp)));
Collection<Optional<Circuit>> result = resultMap.values();
result.forEach(x -> System.out.println(x.get().getCircuitId() + "  " + x.get().getDepartment() + "\t" + x.get().getHours()));
</code>```

Body:
CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours

Circuit class is having pojo objects with getter setters of this three objects.

 public class Circuit {

        String circuitID;
        int hours;
        String department;
}

Body:
First write a custom comparator to check for highest hours and evaluate duplicate hours situation to take the one with Electricity department:

Comparator<Circuit> cmp = new Comparator<Circuit>() {
    @Override
    public int compare(Circuit o1, Circuit o2) {

        int compare = Integer.compare(o1.getHours(), o2.getHours());

        if(compare==0) {  // equal hours so check for department

            // the element with 'Electricity' value must seem to be have max value
            if(o1.getDepartment().equals("Electricity")) {
                compare = 1;
            }
            if(o2.getDepartment().equals("Electricity")) {
                compare = -1;
            }
        }

        return compare;
    }
};

Then group by circuitId attribute with Collectors.groupingBy(Circuit::getCircuitId,  and find max hours with the help of custom comparator above Collectors.maxBy(cmp):

Map<String, Optional<Circuit>> resultMap = circuitList.stream().collect(
                Collectors.groupingBy(Circuit::getCircuitId, Collectors.maxBy(cmp)));
Collection<Optional<Circuit>> result = resultMap.values();
result.forEach(x -> System.out.println(x.get().getCircuitId() + "  " + x.get().getDepartment() + "\t" + x.get().getHours()));


问:
How to append prefix to all url names when using include function - django
I want to include some django app's urls, in two different parent routes. The problem is, if I try to do this, then I will not be able to use reverse function properly for that app's urls.

This is where I'm stuck. The following url configurations will result in creation of two different url sets, e.g:

```<code>/api/v4/auth/{login, register, ...}
/api/auth/{login, register, ...}
</code>```

app A (urls.py)

from auth import views

urlpatterns = [
    url(r'^login/', views.login, name='login'),
    url(r'^register/', views.register, name='register'),
    ...
]
```

<p>main app (urls.py)</p>

<pre class="lang-py prettyprint-override"><code>from auth import urls as auth_urls

urlpatterns = [
    url(r'^api/v4/auth/', include(auth_urls)),
    url(r'^api/auth/', include(auth_urls)),
    ...
]
</code>```

Now, if I try to use reverse function like below:

def get_login_url():
    return reverse('login')
```

I would probably get one of the possible outputs which I don't know how to control!

I don't know if django supports appending some kind of prefix to names of the urls that are being included or is there any tricks to hack around it or not!

答:
You can use namespaces

```<code>from auth import urls as auth_urls

urlpatterns = [
    url(r'^api/v4/auth/', include(auth_urls, namespace='auth1'))),
    url(r'^api/auth/', include(auth_urls, namespace='auth2'))),
    ...
]
</code>```

This way, you will be able to reverse alling auth1:login

Body:
I want to include some django app's urls, in two different parent routes. The problem is, if I try to do this, then I will not be able to use reverse function properly for that app's urls.

This is where I'm stuck. The following url configurations will result in creation of two different url sets, e.g:

/api/v4/auth/{login, register, ...}
/api/auth/{login, register, ...}

app A (urls.py)

from auth import views

urlpatterns = [
    url(r'^login/', views.login, name='login'),
    url(r'^register/', views.register, name='register'),
    ...
]

main app (urls.py)

from auth import urls as auth_urls

urlpatterns = [
    url(r'^api/v4/auth/', include(auth_urls)),
    url(r'^api/auth/', include(auth_urls)),
    ...
]

Now, if I try to use reverse function like below:

def get_login_url():
    return reverse('login')

I would probably get one of the possible outputs which I don't know how to control!

I don't know if django supports appending some kind of prefix to names of the urls that are being included or is there any tricks to hack around it or not!

Body:
You can use namespaces

from auth import urls as auth_urls

urlpatterns = [
    url(r'^api/v4/auth/', include(auth_urls, namespace='auth1'))),
    url(r'^api/auth/', include(auth_urls, namespace='auth2'))),
    ...
]

This way, you will be able to reverse alling auth1:login


问:
Dictionary size reduces upon increasing one element
I ran this:

```<code>import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664
</code>```

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

答:
You are actually not doing anything wrong. getsizeof doesn't get the size of the elements inside the dictionary but the rough estimate of the dictionary. The alternative way for this problem would be json.dumps() from the json library. Though it doesn't give you the actual size of the object, it is consistent with the changes you make to the object.

Here's an example

```<code>import sys
import json

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(json.dumps(diii)) # <----

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(json.dumps(diii)) # <----
</code>```

json.dumps() changes the dictionary into a json string, then diii can be evaluated as a string.
Read more about python's json library here

Body:
I ran this:

import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

Body:
You are actually not doing anything wrong. getsizeof doesn't get the size of the elements inside the dictionary but the rough estimate of the dictionary. The alternative way for this problem would be json.dumps() from the json library. Though it doesn't give you the actual size of the object, it is consistent with the changes you make to the object.

Here's an example

import sys
import json

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(json.dumps(diii)) # <----

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(json.dumps(diii)) # <----

json.dumps() changes the dictionary into a json string, then diii can be evaluated as a string.
Read more about python's json library here


问:
Any utility which can print out map quickly
I am wondering any utility to print out map quickly for debugging purpose.</p>

答:
How about this:

```<code>Map<String, String> map = new HashMap<String, String>();
for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(map.get(key));
}
</code>```

or simply:

```<code>System.out.println(map.toString());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How about this:

Map<String, String> map = new HashMap<String, String>();
for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(map.get(key));
}

or simply:

System.out.println(map.toString());


问:
Lambda loses captured value
I cannot understand why the captured value is lost. I understand that it is connected with an out of scope or copying of an object of LambdaWrapper. But what exactly happens? If LambdaWrapper(100) leaves the scope in Add and reference to __value loses, then why there is no same to LambdaWrapper(300).

```<code>#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class LambdaWrapper {
public:
    LambdaWrapper(double new_value): __value (new_value) {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};

class LambdaContainer {
public:
    void Add(double value) {
        LambdaWrapper w(value); //out of scope
        parts.push_back(w);
    }

    void Add(LambdaWrapper w) // passed as value
    {
        parts.push_back(w);
    }

    void call() const {
        for (const auto& part : parts)
                part.call();
    }
private:
    vector<LambdaWrapper> parts;
};

int main() {
    LambdaContainer c;
    c.Add(100);

    LambdaWrapper w(200);
    c.Add(w);

    c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too

    cout << "==============" << endl;
    c.call();

    return 0;
}
</code>```

The output:

```<code>constructed with 100
constructed with 200
constructed with 300
==============
6.95168e-308 <<< WHY?
200
300
</code>```

答:
By all means pay attention to @Peter's comment.

If you really want a solution, define the copy c'tor of LambdaWrapper yourself so that it would capture the this of the source object.

```<code>class LambdaWrapper
{
public:
    LambdaWrapper(double new_value): __value (new_value)
    {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    LambdaWrapper(const LambdaWrapper &obj) {
        __value = obj.__value;
        __func = [this](){cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};
</code>```

Title: Lambda loses captured value

Body:
I cannot understand why the captured value is lost. I understand that it is connected with an out of scope or copying of an object of LambdaWrapper. But what exactly happens? If LambdaWrapper(100) leaves the scope in Add and reference to __value loses, then why there is no same to LambdaWrapper(300).

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class LambdaWrapper {
public:
    LambdaWrapper(double new_value): __value (new_value) {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};

class LambdaContainer {
public:
    void Add(double value) {
        LambdaWrapper w(value); //out of scope
        parts.push_back(w);
    }

    void Add(LambdaWrapper w) // passed as value
    {
        parts.push_back(w);
    }

    void call() const {
        for (const auto& part : parts)
                part.call();
    }
private:
    vector<LambdaWrapper> parts;
};

int main() {
    LambdaContainer c;
    c.Add(100);

    LambdaWrapper w(200);
    c.Add(w);

    c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too

    cout << "==============" << endl;
    c.call();

    return 0;
}

The output:

constructed with 100
constructed with 200
constructed with 300
==============
6.95168e-308 <<< WHY?
200
300

Body:
By all means pay attention to @Peter's comment.

If you really want a solution, define the copy c'tor of LambdaWrapper yourself so that it would capture the this of the source object.

class LambdaWrapper
{
public:
    LambdaWrapper(double new_value): __value (new_value)
    {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    LambdaWrapper(const LambdaWrapper &obj) {
        __value = obj.__value;
        __func = [this](){cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};


问:
How can I do the equivalent of "SHOW TABLES" in T-SQL?
I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In MySQL I would use SHOW TABLES LIKE "Datasheet%", but in T-SQL this throws an error (it tries to look for a SHOW stored procedure and fails).

Is this possible, and if so, how?

答:
One who doesn't know the TABLE NAME will not able to get the result as per the above answers.

TRY THIS

```<code>SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='dbo';
</code>```

OwnerDisplayName: Andrew Crowe

LastEditorDisplayName: Joel Coehoorn

Body:
One who doesn't know the TABLE NAME will not able to get the result as per the above answers.

TRY THIS

SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='dbo';


问:
Is there any way to use dynamic upstream in Nginx for both HTTP and TCP
We are looking for an option to configure upstream servers dynamically with Restapi or any other available option without stopping nginx server. </p>

答: the solution i can offer is with nginx perl module which by default it is not compiled along with nginx ( you should install nginx perl module seperately ). you can write perl code to request backends through rest api and return it to nginx here you can find more info. </p>


问:
How to fix this error : "../node_modules/react-native/scripts/third-party/glog-0.3.5/test-driver'. Couldn't follow symbolic link
I've faced this error while generating signed apk from android studio.

```<code> Could not list contents of '../node_modules/react-native/scripts/third-party/glog-0.3.5/test-driver'. Couldn't follow symbolic link.
</code>```

I tried :

unlinking test-driver -> No such file found

removing glog-0.3.5 folder

removing .bin folder in node_modules

but still i can't generate apk because of the above error.

答:
I believe this page has solutions.

https://github.com/facebook/react-native/issues/14464

Thanks to @itinance and @tapz for the solutions.

Just for your ease, here is what I did.

Step 1)

```<code>unlink node_modules/react-native/third-party/glog-0.3.4/test-driver
</code>```

Step 2)
Manually located third-party/glog-0.3.4 in the project root folder, deleted the “blog-0.3.4” folder.

Step 3)
cd back to android folder and

```<code>./gradlew assembleRelease
</code>```

This time, the release build was successfully compiled.

Body:
I've faced this error while generating signed apk from android studio.

 Could not list contents of '../node_modules/react-native/scripts/third-party/glog-0.3.5/test-driver'. Couldn't follow symbolic link.

I tried :

unlinking test-driver -> No such file found

removing glog-0.3.5 folder

removing .bin folder in node_modules

but still i can't generate apk because of the above error.

Body:
I believe this page has solutions.

https://github.com/facebook/react-native/issues/14464

Thanks to @itinance and @tapz for the solutions.

Just for your ease, here is what I did.

Step 1)

unlink node_modules/react-native/third-party/glog-0.3.4/test-driver

Step 2)
Manually located third-party/glog-0.3.4 in the project root folder, deleted the “blog-0.3.4” folder.

Step 3)
cd back to android folder and

./gradlew assembleRelease

This time, the release build was successfully compiled.


问:
How can I compare two string format times?
I have a collection called "project" which is having a field expected time and actual time both are in string format

```<code>{
    "_id" : ObjectId("5ce7455d77af2d1143f84d49"),
    "project_name" : "p1",
    "expected" : "0:11:30",
    "actual" : "7:30:00",
}
</code>```

How can I compare two string format times using mongodb?
I want to find if actual time is more than expected

答:
You can convert time to any date you want using $dateFromString operator and then can easily use $lte $gte to perform simple match operations.

```<code>db.collection.find({
  "$expr": {
    "$gt": [
      { "$dateFromString": {
        "dateString": {
          "$concat": ["2018-09-19", "T", "$actual"]
        }
      }},
      { "$dateFromString": {
        "dateString": {
          "$concat": ["2018-09-19", "T", "$expected"]
        }
      }}
    ]
  }
})
</code>```

Body:
I have a collection called "project" which is having a field expected time and actual time both are in string format

{
    "_id" : ObjectId("5ce7455d77af2d1143f84d49"),
    "project_name" : "p1",
    "expected" : "0:11:30",
    "actual" : "7:30:00",
}

How can I compare two string format times using mongodb?
I want to find if actual time is more than expected

Body:
You can convert time to any date you want using $dateFromString operator and then can easily use $lte $gte to perform simple match operations.

db.collection.find({
  "$expr": {
    "$gt": [
      { "$dateFromString": {
        "dateString": {
          "$concat": ["2018-09-19", "T", "$actual"]
        }
      }},
      { "$dateFromString": {
        "dateString": {
          "$concat": ["2018-09-19", "T", "$expected"]
        }
      }}
    ]
  }
})


问:
Win 10 computer does not recognize ESP8266, no blue LED
Flashed five ESP8266 ESP-12e by using NodeMCU firmware. Then inserted each into the USB and no blue LED on the board came on. Only flashes momentarily when inserted then turns off. After this the "device manager" said we did have a COM9 port. Now COM9 is not there in the device manager. I have the drivers for CH341SER and CP2102 installed.

Arduino IDE has "port" but grayed out.

ESPlorer says "could not find any serial port".

NodeMCU says "Error:Serial port not exist".

Any possible solutions or should I throw the computer into a river?

答: It looks like bad USB cable. Try another one.</p>


问:
If any EditText in a Table is empty
In the layout I have a table and two buttons, one button dynamically add another row in the table and the other button is submitted button which stores the values of edittexts inside rows in the table. I want to show a message and cancel submission unless all the edit texts in that table are filled.so it is form validation of a table with the uncertain number of rows with edit texts.
So how to show an error message if any of the edit text inside a table layout is empty. </p>

答:
use the following code

```<code> public boolean isEmpty(ViewGroup viewGroup){

            for(int i=0;i<viewGroup.getChildCount();i++){
                View view = viewGroup.getChildAt(i);
                if(view instanceof ViewGroup){
                    boolean isEmpty= isEmpty((ViewGroup) view);

                    if(isEmpty){
                        return true;
                    }
                }else if(view instanceof EditText){
                    EditText editText= (EditText) view;
                    String input = editText.getText().toString();

                    if("".equals(input)){
                        return true;
                    }
                }
            }

         return false;
    }
</code>```

so basically u can pass table view instance(which is a viewgroup) or any other viewgroup instance and the method will handle looping through its children to check if any edittext have an empty field

Title: If any EditText in a Table is empty

Body:
use the following code

 public boolean isEmpty(ViewGroup viewGroup){

            for(int i=0;i<viewGroup.getChildCount();i++){
                View view = viewGroup.getChildAt(i);
                if(view instanceof ViewGroup){
                    boolean isEmpty= isEmpty((ViewGroup) view);

                    if(isEmpty){
                        return true;
                    }
                }else if(view instanceof EditText){
                    EditText editText= (EditText) view;
                    String input = editText.getText().toString();

                    if("".equals(input)){
                        return true;
                    }
                }
            }

         return false;
    }

so basically u can pass table view instance(which is a viewgroup) or any other viewgroup instance and the method will handle looping through its children to check if any edittext have an empty field


问:
mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
I've started working with django, and here is the error on 'runserver' after setting up 'DATABASES' in settings.py

```<code>mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
</code>```

My settings.py portion of code:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'my_site',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'root',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }

}
</code>```

I've created 'my_site' database and privileges are set in the right way (root has all privileges).
I've done this operations with 'phpmyadmin'.

What goes wrong?

答: FYI if your using XAMPP, go directly into localhost/phpmyad>Privileges to modify this </p>

Body:
I've started working with django, and here is the error on 'runserver' after setting up 'DATABASES' in settings.py

mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")

My settings.py portion of code:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'my_site',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'root',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }

}

I've created 'my_site' database and privileges are set in the right way (root has all privileges).
I've done this operations with 'phpmyadmin'.

What goes wrong?


问:
c#.net function
```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}
</code>```

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

答:
You are defining a method inside another method, and that is not allowed in C#.

Change it to this:

```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        public static int AddNumbers(int number1, int number2)
        {
           int result = AddNumbers(10, 5);
           Console.WriteLine(result);
        }
    }
}
</code>```

Then if you want to call AddNumbers from Main, add the following line inside Main

```<code>AddNumbers( 10, 5);
</code>```

Also note that you are not using the parameters inside AddNumbers for anything. The method should probably look like this:

```<code>public int AddNumbers(int number1, int number2)
{
  int result = number1 + number2;
  Console.WriteLine(result);
}
</code>```

In it's current form it's calling itself recursively also, and will go into an endless loop.

So basically, there are tons of problems with your code. You should probably try to get an entry level book on C# to brush up on your C# skills.

Title: c#.net function

Body:
namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

Body:
You are defining a method inside another method, and that is not allowed in C#.

Change it to this:

namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        public static int AddNumbers(int number1, int number2)
        {
           int result = AddNumbers(10, 5);
           Console.WriteLine(result);
        }
    }
}

Then if you want to call AddNumbers from Main, add the following line inside Main

AddNumbers( 10, 5);

Also note that you are not using the parameters inside AddNumbers for anything. The method should probably look like this:

public int AddNumbers(int number1, int number2)
{
  int result = number1 + number2;
  Console.WriteLine(result);
}

In it's current form it's calling itself recursively also, and will go into an endless loop.

So basically, there are tons of problems with your code. You should probably try to get an entry level book on C# to brush up on your C# skills.


问:
Is it possible to row-reverse in a 2 columns Flatlist?
I create a 2 columns FLatlist in react-native-android

```<code>1    |    2
------------
3    |    4
</code>```

I want this

```<code>2    |    1
4    |    3
</code>```

I try these:

```<code><View style={{flex:1,flexDirection:'row-reverse'}}>
        <FlatList
            style={{flex:1,flexDirection:'row-reverse'}}
</code>```

and in render item I use flexDirection:'row-reverse' too

but no success!

答:
You can use flexDirection: 'row-reverse' inside columnWrapperStyle :

```<code><FlatList
  numColumns={2}
  columnWrapperStyle={{ flexDirection: 'row-reverse' }}
  data={data}
  renderItem={yourRenderFunction}
/>
</code>```

Body:
I create a 2 columns FLatlist in react-native-android

1    |    2
------------
3    |    4

I want this

2    |    1
4    |    3

I try these:

<View style={{flex:1,flexDirection:'row-reverse'}}>
        <FlatList
            style={{flex:1,flexDirection:'row-reverse'}}

and in render item I use flexDirection:'row-reverse' too

but no success!

Body:
You can use flexDirection: 'row-reverse' inside columnWrapperStyle :

<FlatList
  numColumns={2}
  columnWrapperStyle={{ flexDirection: 'row-reverse' }}
  data={data}
  renderItem={yourRenderFunction}
/>


问:
How do I dynamically append html snippets into the web page?
I have the following markup:

```<code><div id="maincontainer">
  <div id="mainMenu">

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

     <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

  </div>
  <div id="legalDocument"></div>
</div>
</code>```

, where the
 element is repeated multiple (9) times.

What is the best way to append such blocks dynamically, through for(){} cycle for example? The innerHtml property is not recommended from what I've heard. and using a special recursive function that I made doesn't seem to be the right way either.

What should I do? I'd like to extend my Web pages with templates kinda like how Javascript classes behave.

答:
I'd use HTML templates -- that's what they're for:

```<code><html>
    <head>
        <template id="giver-template">
            <div class="giver">
                <hr class = "giver-hr">
                <select class ="giver-subject"></select>
                <select class ="giver-status"></select>
                <label class = giver-isClient>
                    <input type = "radio">
                    <span>lorem ipsum</span>
                </label>
            </div>
        </template>
    </head>
    <body>
        <!-- document body -->
    </body>
</html>
</code>```

The contents of a template, a DocumentFragment, are available through accessing the content property on the template element itself; these contents, being a DocumentFragment, are in a convenient form, parsed and ready, and will not incur extra overhead the way innerHtml or insertAdjacentHTML would imply because of need to parse the markup and produce DOM objects for insertion into the document.

As you can observe, template elements are contained in the document head section, meaning they are not themselves rendered or are part of your document body otherwise -- their utility lies in being able to clone them and use their "instantiated" copies.

You can trivially use the template defined above for your use-case:

```<code>const new_giver_element = document.getElementById("giver-template").content.cloneNode(true);
</code>```

Meaning that new_giver_element now refers to a new, unattached DOM node (a DocumentFragment) (which you can further modify if you so wish) ready for insertion into a document through appendChild or other methods.

Body:
I have the following markup:

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

, where the
 element is repeated multiple (9) times.

What is the best way to append such blocks dynamically, through for(){} cycle for example? The innerHtml property is not recommended from what I've heard. and using a special recursive function that I made doesn't seem to be the right way either.

What should I do? I'd like to extend my Web pages with templates kinda like how Javascript classes behave.

Body:
I'd use HTML templates -- that's what they're for:

<html>
    <head>
        <template id="giver-template">
            <div class="giver">
                <hr class = "giver-hr">
                <select class ="giver-subject"></select>
                <select class ="giver-status"></select>
                <label class = giver-isClient>
                    <input type = "radio">
                    <span>lorem ipsum</span>
                </label>
            </div>
        </template>
    </head>
    <body>
        <!-- document body -->
    </body>
</html>

The contents of a template, a DocumentFragment, are available through accessing the content property on the template element itself; these contents, being a DocumentFragment, are in a convenient form, parsed and ready, and will not incur extra overhead the way innerHtml or insertAdjacentHTML would imply because of need to parse the markup and produce DOM objects for insertion into the document.

As you can observe, template elements are contained in the document head section, meaning they are not themselves rendered or are part of your document body otherwise -- their utility lies in being able to clone them and use their "instantiated" copies.

You can trivially use the template defined above for your use-case:

const new_giver_element = document.getElementById("giver-template").content.cloneNode(true);

Meaning that new_giver_element now refers to a new, unattached DOM node (a DocumentFragment) (which you can further modify if you so wish) ready for insertion into a document through appendChild or other methods.


问:
fping using IP list in python3
I am new to python and I am trying to scan multiple IPs with fping. I have large number of server to monitor for statistics and I could write the following code that works for 2 hosts:

```
    import subprocess
    import binascii

    out = ''
    err = ''

    host1 = '172.2.2.5'
    host2 = '172.1.5.8'
    hosts = '/tmp/ip.list'

    ping = subprocess.Popen(['fping', '-C', '10', '-b', '50', '-p', '25', host1, host2], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    try:
        [out, err] = ping.communicate(timeout=15)

        print('STDOUT')
        print(out.decode('utf-8').strip())

        print('STDERR (Statistics)')
        print(err.decode('utf-8').strip())

    except subprocess.TimeoutExpired:
        print('STDERR (expired timeout)')
```

However, I am unable to replace the two hosts with list of host files, though I tried in multiple ways.

I would very much appreciate any help this regard or any improvements in the program itself.

TIA.

答:
I found a simple fix:</p>

```

with open('ip_list.csv', 'r') as fh:
    all_ips = fh.read().splitlines()

cmd = ['fping', '-C', '10', '-b', '50', '-p', '25']
cmd.extend(all_ips)

ping = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

```

Title: fping using IP list in python3

Body:
I am new to python and I am trying to scan multiple IPs with fping. I have large number of server to monitor for statistics and I could write the following code that works for 2 hosts:

    import subprocess
    import binascii

    out = ''
    err = ''

    host1 = '172.2.2.5'
    host2 = '172.1.5.8'
    hosts = '/tmp/ip.list'

    ping = subprocess.Popen(['fping', '-C', '10', '-b', '50', '-p', '25', host1, host2], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    try:
        [out, err] = ping.communicate(timeout=15)

        print('STDOUT')
        print(out.decode('utf-8').strip())

        print('STDERR (Statistics)')
        print(err.decode('utf-8').strip())

    except subprocess.TimeoutExpired:
        print('STDERR (expired timeout)')

However, I am unable to replace the two hosts with list of host files, though I tried in multiple ways.

I would very much appreciate any help this regard or any improvements in the program itself.

TIA.

Body:
I found a simple fix:

with open('ip_list.csv', 'r') as fh:
    all_ips = fh.read().splitlines()

cmd = ['fping', '-C', '10', '-b', '50', '-p', '25']
cmd.extend(all_ips)

ping = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)


问:
How do I scale the height of a div the same way that a div with an image does?
I have 2 divs that are floated next to each other. In one of the divs I have an image that scales (both it´s height and width) when I decrease the size of the browser window. In the other div I have some other content, but this is only being scaled in width when I decrease the size of the browser window. I want both of the divs to have the same height at all times, even when they are being scaled. Is this possible?

If you want a live preview, please check out this link:
http://jjberg.com/cipher/index.html

I know part of the problem is that I´ve actually set a height of 500px to the cipherSide div. This is because so far I haven´t been able to make the height of this div closer to the height of the pinupSide div in any other way.

I tried to copy the declarations from the pinupSide and pinUpGirl to the cipherSide and verticalAlign divs, but to no avail. This only pushed the content in the cipherSide div all the way to the top.

 Dirty Diana

Dirty Diana wants to send dirty love messages to her husband, but she does not want Big Brother to know about it. Try out the tool I made for her!

      <textarea rows="10" placeholder="Insert the text you want to cipher or decipher here!" required></textarea>
      <button id="cipherIT">Cipher It!</button>
      <button id="deCipher">Decipher!</button>

```

<pre class="lang-css prettyprint-override"><code>.container {
  max-width: 992px;
  height: 100%;
  margin: 0 auto;
  background: blue;
}
.pinupSide {
  background: green;
  width: 50%;
  height: 100%;
  float: left;
}
.pinUpGirl {
  max-width: 100%;
  max-height: 100%;
  background: black;
}
.cipherSide {
  position: relative;
  background: red;
  width: 50%;
  height: 500px;
  float: left;
}
.verticalAlign {
  position: absolute;
  top: 25%;
  height: 50%;
  width: 100%;
  background: yellow;
}
</code>```

I want both of the divs to have the same height at all times, no matter how I´m scaling the width of the browser window.

答:
Considering you code I assume you want the two elements to have the same height but also the same width at all time. I also assume you want the image to be as big as possible inside the left element without being distorted. Is that right?

If you can use CSS Grid, you can achieve that layout with a grid made up of two columns of each 1fr, which represent one fraction of the available space. See the following code:

The  element has its width set to 100% so that it is as big as possible inside its parent element, and its parent element has the font-size set to 0 to remove an unwanted space below the image.

body {
  margin: 0;
  background-color: #3ff4fe;
}

.container {
  max-width: 992px;
  margin: auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.image {
  background-color: black;
  font-size: 0;
}
.image img {
  width: 100%;
}

.text {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="image">
    <img src="http://jjberg.com/cipher/images/pin_up_edited_x2.png" alt="Pin up girl">
  </div>
  <div class="text">
    Some text
  </div>
</div></code>```

Does this help?

Body:
I have 2 divs that are floated next to each other. In one of the divs I have an image that scales (both it´s height and width) when I decrease the size of the browser window. In the other div I have some other content, but this is only being scaled in width when I decrease the size of the browser window. I want both of the divs to have the same height at all times, even when they are being scaled. Is this possible?

If you want a live preview, please check out this link:
http://jjberg.com/cipher/index.html

I know part of the problem is that I´ve actually set a height of 500px to the cipherSide div. This is because so far I haven´t been able to make the height of this div closer to the height of the pinupSide div in any other way.

I tried to copy the declarations from the pinupSide and pinUpGirl to the cipherSide and verticalAlign divs, but to no avail. This only pushed the content in the cipherSide div all the way to the top.

 Dirty Diana

Dirty Diana wants to send dirty love messages to her husband, but she does not want Big Brother to know about it. Try out the tool I made for her!

      <textarea rows="10" placeholder="Insert the text you want to cipher or decipher here!" required></textarea>
      <button id="cipherIT">Cipher It!</button>
      <button id="deCipher">Decipher!</button>

.container {
  max-width: 992px;
  height: 100%;
  margin: 0 auto;
  background: blue;
}
.pinupSide {
  background: green;
  width: 50%;
  height: 100%;
  float: left;
}
.pinUpGirl {
  max-width: 100%;
  max-height: 100%;
  background: black;
}
.cipherSide {
  position: relative;
  background: red;
  width: 50%;
  height: 500px;
  float: left;
}
.verticalAlign {
  position: absolute;
  top: 25%;
  height: 50%;
  width: 100%;
  background: yellow;
}

I want both of the divs to have the same height at all times, no matter how I´m scaling the width of the browser window.

Body:
Considering you code I assume you want the two elements to have the same height but also the same width at all time. I also assume you want the image to be as big as possible inside the left element without being distorted. Is that right?

If you can use CSS Grid, you can achieve that layout with a grid made up of two columns of each 1fr, which represent one fraction of the available space. See the following code:

The <img> element has its width set to 100% so that it is as big as possible inside its parent element, and its parent element has the font-size set to 0 to remove an unwanted space below the image.

body {
  margin: 0;
  background-color: #3ff4fe;
}

.container {
  max-width: 992px;
  margin: auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.image {
  background-color: black;
  font-size: 0;
}
.image img {
  width: 100%;
}

.text {
  background-color: red;
}

<div class="container">
  <div class="image">
    <img src="http://jjberg.com/cipher/images/pin_up_edited_x2.png" alt="Pin up girl">
  </div>
  <div class="text">
    Some text
  </div>
</div>

Does this help?


问:
How to shift Array.count result by -1 using Swift?
I have an array with 7 objects inside it, and am using the Array.count to get the number of objects inside the array.

I'm then using Int.random(in: 0 ... arrayMax) to get a random object from the array. Yet, because there are 7 objects in the array, and the .count will return 7, I'll every once in a while get an error, because 7 is obviously 6.

I've tried to solve this by going like this:

```<code>let nTMax = Array.count
let nTSelection = Int.random(in: 0 ... nTMax)
print (nTMax, nTSelection)
let nTSelectionProtect = nTSelection -1
</code>```

but the nTSelectionProtect refuses to be accepted. I was hoping to do a safety calculation so that 7 will always be 6, but I'm not sure how to do it.

How would I do it?

答:
It's more safe to use

```<code>    let nTSelection = Int.random(in: 0..<nTMax)
</code>```

This

```<code>    let nTSelectionProtect = nTSelection -1
</code>```

will crash if the random returned is zero, this nTSelection -1 will be -1

You can also fetch a random element with

```<code>print(array.randomElement())
</code>```

Body:
I have an array with 7 objects inside it, and am using the Array.count to get the number of objects inside the array.

I'm then using Int.random(in: 0 ... arrayMax) to get a random object from the array. Yet, because there are 7 objects in the array, and the .count will return 7, I'll every once in a while get an error, because 7 is obviously 6.

I've tried to solve this by going like this:

let nTMax = Array.count
let nTSelection = Int.random(in: 0 ... nTMax)
print (nTMax, nTSelection)
let nTSelectionProtect = nTSelection -1

but the nTSelectionProtect refuses to be accepted. I was hoping to do a safety calculation so that 7 will always be 6, but I'm not sure how to do it.

How would I do it?

Body:
It's more safe to use

    let nTSelection = Int.random(in: 0..<nTMax)

This

    let nTSelectionProtect = nTSelection -1

will crash if the random returned is zero, this nTSelection -1 will be -1

You can also fetch a random element with

print(array.randomElement())


答: I guess, the .toString() method of implementing class (HashMap or TreeMap for ex.) will do what you want.</p>

Title: Any utility which can print out map quickly

Body: I am wondering any utility to print out map quickly for debugging purpose.


问:
Reusing variables in Rust
I have the following code:

```<code>let display_value = entry.path().display();
files_and_dirs.push(DiskEntry {
    path: display_value.to_string(),
    is_dir: is_dir(display_value.to_string()),
    name: display_value.to_string()
});
</code>```

If I write it thus:

```<code>let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name,
    is_dir: is_dir(dir_name),
    name: dir_name
});
</code>```

I get the following error:

move occurs because dir_name has type std::string::String, which
  does not implement the Copy trait

I understand in Rust values are moved around when assigning. I want to declare one variable and use it multiple times in the second block of code. How do I do this?

答:
Your DiskEntry and is_dir are presumably defined like this:

```<code>struct DiskEntry {
    path: String,
    is_dir: bool,
    name: String,
}

fn is_dir(path: String) -> bool {
    // ...
}
</code>```

Each time there is a variable of type String, the variable needs to have its own copy of the string in memory.

As the error suggests, you could fix it by cloning:

```<code>let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name.clone(),
    is_dir: is_dir(dir_name.clone()),
    name: dir_name
});
</code>```

But you should avoid cloning data unnecessarily because it's inefficient. The clone that is very easy to remove is in is_dir - it should be pretty obvious that this method doesn't need to permanently take ownership of its input. It can very easily borrow it instead:

```<code>fn is_dir(path: &str) -> bool {
    // ...
}
</code>```

And you would call it like this, so that the String is borrowed as a &str:

```<code>is_dir(&dir_name),
</code>```

The other case is probably trickier. In order to avoid cloning, you will need to make the DiskEntry struct borrow the strings. It would look like this:

```<code>struct DiskEntry<'a> {
    path: &'a str,
    is_dir: bool,
    name: &'a str,
}

let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: &dir_name,
    is_dir: is_dir(&dir_name),
    name: &dir_name
});
</code>```

However, this will limit what you can do with the DiskEntry; in particular, it cannot outlive the dir_name variable.  It's hard to know what other problems this could cause you, without knowing the wider context of your code, but it is likely to have broader impact on other data structures.

Given that you appear to be just learning Rust, if you are not yet comfortable with borrowing and lifetimes it might be easiest just to accept this one extra clone, until you have a better understanding and can make that judgement for yourself.

See also:

What are the differences between Rust's String and str?

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

Title: Reusing variables in Rust

Body:
I have the following code:

let display_value = entry.path().display();
files_and_dirs.push(DiskEntry {
    path: display_value.to_string(),
    is_dir: is_dir(display_value.to_string()),
    name: display_value.to_string()
});

If I write it thus:

let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name,
    is_dir: is_dir(dir_name),
    name: dir_name
});

I get the following error:

move occurs because dir_name has type std::string::String, which
  does not implement the Copy trait

I understand in Rust values are moved around when assigning. I want to declare one variable and use it multiple times in the second block of code. How do I do this?

Body:
Your DiskEntry and is_dir are presumably defined like this:

struct DiskEntry {
    path: String,
    is_dir: bool,
    name: String,
}

fn is_dir(path: String) -> bool {
    // ...
}

Each time there is a variable of type String, the variable needs to have its own copy of the string in memory.

As the error suggests, you could fix it by cloning:

let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: dir_name.clone(),
    is_dir: is_dir(dir_name.clone()),
    name: dir_name
});

But you should avoid cloning data unnecessarily because it's inefficient. The clone that is very easy to remove is in is_dir - it should be pretty obvious that this method doesn't need to permanently take ownership of its input. It can very easily borrow it instead:

fn is_dir(path: &str) -> bool {
    // ...
}

And you would call it like this, so that the String is borrowed as a &str:

is_dir(&dir_name),

The other case is probably trickier. In order to avoid cloning, you will need to make the DiskEntry struct borrow the strings. It would look like this:

struct DiskEntry<'a> {
    path: &'a str,
    is_dir: bool,
    name: &'a str,
}

let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
    path: &dir_name,
    is_dir: is_dir(&dir_name),
    name: &dir_name
});

However, this will limit what you can do with the DiskEntry; in particular, it cannot outlive the dir_name variable.  It's hard to know what other problems this could cause you, without knowing the wider context of your code, but it is likely to have broader impact on other data structures.

Given that you appear to be just learning Rust, if you are not yet comfortable with borrowing and lifetimes it might be easiest just to accept this one extra clone, until you have a better understanding and can make that judgement for yourself.

See also:

What are the differences between Rust's String and str?

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?


问:
A grammar for Access SQL
Does a grammar (like in EBNF or similar format) exist for MS Access SQL syntax? Like how TSQL syntax is documented with EBNF: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-2017.  </p>

<p>I have only been able to find find tutorials with examples, but not a full grammar. </p>

答:
You can find the full Access SQL reference here on MS Docs.

Note that some statements are exclusive to the SQL server compatible syntax (anything with the DECIMAL type and CHECK constraints), and this isn't properly described in the reference.

It isn't as extensive and well-written as the T-SQL stuff, but it's closest to what you're asking.

Title: A grammar for Access SQL

Body:
Does a grammar (like in EBNF or similar format) exist for MS Access SQL syntax? Like how TSQL syntax is documented with EBNF: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-2017.

I have only been able to find find tutorials with examples, but not a full grammar.


问:
Fetching data from DB and not getting correct value in input fields
I have fetch the data from the database.  I have a 7 checkbox and 2 tag text in the front of the checkboxes. I have written the logic for the checkbox that check the those checkbox which is in the database but in the text fields data is serving wrong i know the problem that $j is going wrong. Can you tell me what check should i write to get correct value of the text from checkbox according to the checkbox. I have Given the pic it will easy to understand.

PICTURE(see in the array according to weekname, i am not able to get the values of the texbox)->HERE IS THE PICTURE

Now lets see the Code:

```<code> <?php
            $details=new User();

            $row=$details->Display('date',$ids);
            $weeknames=array(1=>'Monday',2=>'Tuesday',3=>'Wednesday',4=>'Thursday',5=>'Friday',6=>'Saturday',7=>'Sunday');

            for($i=0;$i<count($row); $i++)
          {
           $arr[]= $row[$i]['name'];
           $start[]= $row[$i]['starttime'];
           $end[]= $row[$i]['endtime'];
           $id[]=$row[$i]['id'];
          }
          print_r($row);
         $j=0;
            foreach($weeknames as $key=>$value)
            {
                // echo $j;
                ?>
              <br/>  <input type="checkbox"  id="<?php echo $key; ?>" name="mycheck" value="<?php echo $value ?>"  <?php if(in_array($value,$arr)) { ?> checked="checked" <?php }?> /><?php echo $value ?> Start<input type="text"  userid="<?php  echo $ids; ?>" id="start<?php echo $key ?>" value="<?php  if(in_array($value,$arr)) { echo $start[$j];  } ?>"  />End<input type="text" id="end<?php echo $key ?>" value="<?php  if(in_array($value,$arr)) { echo $end[$j]; $j++;  }  ?>" /> <br />
                <?php
            }
            ?>
</code>```

答:
The below code should do what you are attempting to do but when making it I noticed a few things you should be aware of.

You use mycheck as the name for all checkboxes, you will want them to be unique if you need to know which is which and if not why set it at all.

Secondly userid is not a valid HTML attribute, if you wish to have it available use data-userid the data- then a name is a valid attribute.

```<code>$data = [
    ["id"=>1, "name"=>"Monday", "starttime"=>"12:12 PM", "endtime"=> "12:34 PM", "userid"=> ""],
    ["id"=>2, "name"=>"Tuesday", "starttime"=>"4:20 AM", "endtime"=>"11:00 AM", "userid"=> ""],
    ["id"=>3, "name"=>"Wednesday", "starttime"=>"2:22 AM", "endtime"=> "6:00 AM", "userid"=> ""],
    ["id"=>4, "name"=>"Sunday", "starttime"=>"3:12 PM", "endtime"=> "7:22 PM", "userid"=> ""]
];

$days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];

for($x = 0; $x < count($days); $x++){

    $day = $days[$x];
    $row = getRow($day, $data);

    if($row != null)
    {
        echo "<input type='checkbox'  id='{$day}' name='this-should-be-unique-{$x}' checked='checked'/> {$day} Start <input type='text' value='{$row['starttime']}'/> End <input type='text' value='{$row['endtime']}'/><br/> ";
    }
    else
    {
        echo "<input type='checkbox'  id='{$day}' name='this-should-be-unique-{$x}' /> {$day} Start <input type='text' value=''/> End <input type='text' value=''/><br/> ";
    }
}

function getRow($day, $data){
    for ($x = 0; $x < count($data); $x++){
        if($data[$x]["name"] == $day){
            return $data[$x];
        }
    }
    return null;
}
</code>```

Body:
I have fetch the data from the database.  I have a 7 checkbox and 2 tag text in the front of the checkboxes. I have written the logic for the checkbox that check the those checkbox which is in the database but in the text fields data is serving wrong i know the problem that $j is going wrong. Can you tell me what check should i write to get correct value of the text from checkbox according to the checkbox. I have Given the pic it will easy to understand.

PICTURE(see in the array according to weekname, i am not able to get the values of the texbox)->HERE IS THE PICTURE

Now lets see the Code:

 <?php
            $details=new User();

            $row=$details->Display('date',$ids);
            $weeknames=array(1=>'Monday',2=>'Tuesday',3=>'Wednesday',4=>'Thursday',5=>'Friday',6=>'Saturday',7=>'Sunday');

            for($i=0;$i<count($row); $i++)
          {
           $arr[]= $row[$i]['name'];
           $start[]= $row[$i]['starttime'];
           $end[]= $row[$i]['endtime'];
           $id[]=$row[$i]['id'];
          }
          print_r($row);
         $j=0;
            foreach($weeknames as $key=>$value)
            {
                // echo $j;
                ?>

  <input type="checkbox"  id="<?php echo $key; ?>" name="mycheck" value="<?php echo $value ?>"  <?php if(in_array($value,$arr)) { ?> checked="checked" <?php }?> /><?php echo $value ?> Start<input type="text"  userid="<?php  echo $ids; ?>" id="start<?php echo $key ?>" value="<?php  if(in_array($value,$arr)) { echo $start[$j];  } ?>"  />End<input type="text" id="end<?php echo $key ?>" value="<?php  if(in_array($value,$arr)) { echo $end[$j]; $j++;  }  ?>" />

                <?php
            }
            ?>

Body:
The below code should do what you are attempting to do but when making it I noticed a few things you should be aware of.

You use mycheck as the name for all checkboxes, you will want them to be unique if you need to know which is which and if not why set it at all.

Secondly userid is not a valid HTML attribute, if you wish to have it available use data-userid the data- then a name is a valid attribute.

$data = [
    ["id"=>1, "name"=>"Monday", "starttime"=>"12:12 PM", "endtime"=> "12:34 PM", "userid"=> ""],
    ["id"=>2, "name"=>"Tuesday", "starttime"=>"4:20 AM", "endtime"=>"11:00 AM", "userid"=> ""],
    ["id"=>3, "name"=>"Wednesday", "starttime"=>"2:22 AM", "endtime"=> "6:00 AM", "userid"=> ""],
    ["id"=>4, "name"=>"Sunday", "starttime"=>"3:12 PM", "endtime"=> "7:22 PM", "userid"=> ""]
];

$days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];

for($x = 0; $x < count($days); $x++){

    $day = $days[$x];
    $row = getRow($day, $data);

    if($row != null)
    {
        echo "<input type='checkbox'  id='{$day}' name='this-should-be-unique-{$x}' checked='checked'/> {$day} Start <input type='text' value='{$row['starttime']}'/> End <input type='text' value='{$row['endtime']}'/><br/> ";
    }
    else
    {
        echo "<input type='checkbox'  id='{$day}' name='this-should-be-unique-{$x}' /> {$day} Start <input type='text' value=''/> End <input type='text' value=''/><br/> ";
    }
}

function getRow($day, $data){
    for ($x = 0; $x < count($data); $x++){
        if($data[$x]["name"] == $day){
            return $data[$x];
        }
    }
    return null;
}


问:
Calling a function that was passed through its props
I am currently new to react-bootstrap and have a question i can not solve.

I want to set my parents state by passing it as a prop to its child. Whe ncalling the function it seems to be executed, but the state is not set.. I have no clue why that is.

```<code>class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state={
            component : ""
        }

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

    returnDashboard=()=>{
        console.log("i am executed")
        this.setState({component : <Dashboard />})
    }

    render(){
        return (
            <Child returnDashboard={this.returnDashboard}/>
        );
    }
};

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

    render(){
         return(
                <button onClick={()={this.props.returnSettings()}}>foo</button>
            );
    }
}
</code>```

when pressing the button the console logs "i am executed" and this: ƒ () { [native code] }. Can someone help me with that?

答:
you note have a returnSettings props in child component,
do click event like this

onClick = {()=>this.props.returnDashboard}

Body:
I am currently new to react-bootstrap and have a question i can not solve.

I want to set my parents state by passing it as a prop to its child. Whe ncalling the function it seems to be executed, but the state is not set.. I have no clue why that is.

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state={
            component : ""
        }

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

    returnDashboard=()=>{
        console.log("i am executed")
        this.setState({component : <Dashboard />})
    }

    render(){
        return (
            <Child returnDashboard={this.returnDashboard}/>
        );
    }
};

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

    render(){
         return(
                <button onClick={()={this.props.returnSettings()}}>foo</button>
            );
    }
}

when pressing the button the console logs "i am executed" and this: ƒ () { [native code] }. Can someone help me with that?


问:
Importing a known function from an already-compiled binary, using GHC's API or Hint
I have a module Target, with a function Target.accessMe inside it. I compile this module in some way, then get rid of the source code.

Now, what series of arcane incantations must I do to make a different program dynamically import Target.accessMe? This program knows accessMe's type in advance. Also, consider the fact that the source code of Target is not available.

The plugins package manages to accomplish this, but seems to have serious issues with working on Windows. I've checked out plugins's source, but am having trouble understanding it.

I've tried using Hint, but can only find out how to evaluate code that I have the source for.

Thanks for any help!

答:
The answer to this question has been given to me elsewhere. The GHC API is capable of doing this. Here are two functions, one of which compiles Target.hs, while the other accesses Target.accessMe (and doesn't require the source code of the Target module to be there anymore).

```<code>import GHC
import DynFlags

compile :: String -> IO SuccessFlag
compile name = defaultRunGhc $ do
  dynflags <- getSessionDynFlags
  let dynflags' = dynflags -- You can change various options here.
  setSessionDynFlags dynflags'

  -- (name) can be "Target.hs", "Target", etc.
  target <- guessTarget name Nothing
  addTarget target
  load LoadAllTargets -- Runs something like "ghc --make".
</code>```

That's a function that compiles a given module and returns whether compilation succeeded or not. It uses a defaultRunGhc helper function that is defined as:

```<code>import GHC.Paths (libdir)

defaultRunGhc :: Ghc a -> IO a
defaultRunGhc = defaultErrorHandler defaultDynFlags . runGhc (Just libdir)
</code>```

And now a function for fetching a value from the compiled module. The module's source code need not be present at this point.

```<code>import Unsafe.Coerce (unsafeCoerce)

fetch :: String -> String -> IO Int -- Assumes we are fetching an Int value.
fetch name value = defaultRunGhc $ do
  -- Again, you can change various options in dynflags here, as above.
  dynflags <- getSessionDynFlags
  let m = mkModule (thisPackage dynflags) (mkModuleName name)
  setContext [] [(m, Nothing)] -- Use setContext [] [m] for GHC<7.

  fetched <- compileExpr (name ++ "." ++ value) -- Fetching "Target.accessMe".
  return (unsafeCoerce fetched :: Int)
</code>```

And that's it!

ContentLicense: CC BY-SA 2.5

Body:
The answer to this question has been given to me elsewhere. The GHC API is capable of doing this. Here are two functions, one of which compiles Target.hs, while the other accesses Target.accessMe (and doesn't require the source code of the Target module to be there anymore).

import GHC
import DynFlags

compile :: String -> IO SuccessFlag
compile name = defaultRunGhc $ do
  dynflags <- getSessionDynFlags
  let dynflags' = dynflags -- You can change various options here.
  setSessionDynFlags dynflags'

  -- (name) can be "Target.hs", "Target", etc.
  target <- guessTarget name Nothing
  addTarget target
  load LoadAllTargets -- Runs something like "ghc --make".

That's a function that compiles a given module and returns whether compilation succeeded or not. It uses a defaultRunGhc helper function that is defined as:

import GHC.Paths (libdir)

defaultRunGhc :: Ghc a -> IO a
defaultRunGhc = defaultErrorHandler defaultDynFlags . runGhc (Just libdir)

And now a function for fetching a value from the compiled module. The module's source code need not be present at this point.

import Unsafe.Coerce (unsafeCoerce)

fetch :: String -> String -> IO Int -- Assumes we are fetching an Int value.
fetch name value = defaultRunGhc $ do
  -- Again, you can change various options in dynflags here, as above.
  dynflags <- getSessionDynFlags
  let m = mkModule (thisPackage dynflags) (mkModuleName name)
  setContext [] [(m, Nothing)] -- Use setContext [] [m] for GHC<7.

  fetched <- compileExpr (name ++ "." ++ value) -- Fetching "Target.accessMe".
  return (unsafeCoerce fetched :: Int)

And that's it!


问:
How to create a Firestore safe Document ID based on a string
After some discussion on my question about base64 not being safe for Firestore IDs here I would like to know how one can encode a string to a Firestore "safe" Document ID.

Here is the problem:

I am login in users via a custom authentication service.

That service provides a username that can contain / that are not safe for the firestore document ids as declared here

I asked about the base64 in another question and that is not safe as it contains /

So what could be a safe way to encode that string without loosing the entropy of the username that the external service provides. That means that there could be a username such as dimi/test1 and another as dimitest1 so just stripping out characters is not an option.

Also since that service has available an open API and my service exposes the document ID's via URLs I would like not to expose the other service usernames via my apps URLS.

Any suggestions?

答: I used Base58 and that was the most safe I could research for</p>


问:
How to fix problem with Roboto font load in Google Chrome?
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

```<code>GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND
</code>```

I tried to import directy in the CSS and in the HTML this:

```<code>@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}
</code>```

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
        </style>
        <!-- JQuery Mobile -->
        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>
        <!-- Project CSS -->
        <link rel="stylesheet" href="./css/style.css"></link>
        <!-- NativeDroid2 CSS -->
        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>
    </head>
    <body>
        <div data-role="main" class="ui-content">
            <form method="post">
                <div class="img-container">
                    <img src="img/logo_gemott.png" alt="No es pot carregar la imatge" height="110" width="350">
                </div>

                <div>
                    <h2>Registre</h2>
                    <hr>
                    <label for="mail"><b>Correu electrònic</b></label>
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    <label for="psw"><b>Contrasenya</b></label>
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>
                    <div class="center-text">
                        <p>Al registrar-te, acceptes els <a href=#>termes de privacitat</a></p>
                        <p>Ja estàs <a href="login.html">registrat?</a></p>
                    </div>
                </div>

                <a href="javascript:registry()" class="ui-btn ui-btn-raised clr-primary">Registrar-me</a>

                <div class="img-container" id="uab-logo">
                    <img src="img/UAB.jpg" alt="No es pot carrerar la imatge" height="150" witdh="150">
                </div>
            </form>
        </div>
        <!-- JQuery -->
        <script type="text/javascript" src="jquery/jquery-2.2.4.js"></script>
        <!-- Project Js -->
        <script type="text/javascript" src="js/app.js"></script>
        <!-- JQuery Mobile -->
        <script type="text/javascript" src="jquery/jquery.mobile-1.4.5.min.js"></script>
        <!-- NativeDroid2 Js -->
        <script type="text/javascript" src="bower_components/Waves/dist/waves.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/nd2settings.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/js/nativedroid2.js"></script>
    </body>
</html>
</code>```

答:
You just need to define the font-family: 'Roboto', sans-serif; in CSSor body tag.

<!DOCTYPE html>

        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>

        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>

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

        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>

            <form method="post">

Registre

                    Correu electrònic
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    Contrasenya
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>

Al registrar-te, acceptes els termes de privacitat

Ja estàs registrat?

                Registrar-me

            </form>

```
</div>
</div>
</p>

```body {
      font-family: 'Roboto', sans-serif;
}
```

I have tried. It's working!

Body:
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND

I tried to import directy in the CSS and in the HTML this:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

<!DOCTYPE html>

        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>

        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>

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

        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>

            <form method="post">

Registre

                    Correu electrònic
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    Contrasenya
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>

Al registrar-te, acceptes els termes de privacitat

Ja estàs registrat?

                Registrar-me

            </form>

Body:
You just need to define the font-family: 'Roboto', sans-serif; in CSSor body tag.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');

             body {
  font-family: 'Roboto', sans-serif;
       }

        </style>
        <!-- JQuery Mobile -->
        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>
        <!-- Project CSS -->
        <link rel="stylesheet" href="./css/style.css"></link>
        <!-- NativeDroid2 CSS -->
        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>
    </head>
    <body>
        <div data-role="main" class="ui-content">
            <form method="post">
                <div class="img-container">
                    <img src="img/logo_gemott.png" alt="No es pot carregar la imatge" height="110" width="350">
                </div>

                <div>
                    <h2>Registre</h2>
                    <hr>
                    <label for="mail"><b>Correu electrònic</b></label>
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    <label for="psw"><b>Contrasenya</b></label>
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>
                    <div class="center-text">
                        <p>Al registrar-te, acceptes els <a href=#>termes de privacitat</a></p>
                        <p>Ja estàs <a href="login.html">registrat?</a></p>
                    </div>
                </div>

                <a href="javascript:registry()" class="ui-btn ui-btn-raised clr-primary">Registrar-me</a>

                <div class="img-container" id="uab-logo">
                    <img src="img/UAB.jpg" alt="No es pot carrerar la imatge" height="150" witdh="150">
                </div>
            </form>
        </div>
        <!-- JQuery -->
        <script type="text/javascript" src="jquery/jquery-2.2.4.js"></script>
        <!-- Project Js -->
        <script type="text/javascript" src="js/app.js"></script>
        <!-- JQuery Mobile -->
        <script type="text/javascript" src="jquery/jquery.mobile-1.4.5.min.js"></script>
        <!-- NativeDroid2 Js -->
        <script type="text/javascript" src="bower_components/Waves/dist/waves.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/nd2settings.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/js/nativedroid2.js"></script>
    </body>
</html>

body {
      font-family: 'Roboto', sans-serif;
}

I have tried. It's working!


问:
Get Information from Microsoft Academic Graph API
I am trying to use the Microsoft Academic Graph API with Python, to get information about the Author's Affiliations. However, the information provided in

https://learn.microsoft.com/en-us/azure/cognitive-services/academic-knowledge/graphsearchmethod

is not clear to me.

I have also read Microsoft Academic Graph Search - retrieving all papers from a journal within a time-frame?

I am trying with something like this:

```<code>import requests

url = "https://westus.api.cognitive.microsoft.com/academic/v1.0/graph/search"

querystring = {"mode":"json%0A"}

payload = "{}"

response = requests.request("POST", url, data=payload, params=querystring)

print(response.text)
</code>```

What should I put in "payload" to retrieve the affiliation of, for example, the Author "John Doe" ?

答:
It seems you are using the wrong endpoint.
As for anything experimental the documentation seems out of date.
I have had success calling https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate
These endpoints can be seen in the cognitive labs documentation.

I am yet to figure out how to retrieve academic profiles, as the query below yields no results, whereas academic.microsoft.com has loads.

https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr=Composite(AA.AuN='Harry L. Anderson')&model=latest&count=10&attributes=Id,Ti,AA.AuN,E,AA.AuId

Hope this may help anyone stumbling upon this.

Update :

Here is a working query for the same author :
https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?model=latest&count=100&expr=Composite(AA.AuN=='harry l anderson')&attributes=Id,Ti,AA.AuN,E,AA.AuId

Notice the author name has to be in lowercase.

Body:
I am trying to use the Microsoft Academic Graph API with Python, to get information about the Author's Affiliations. However, the information provided in

https://learn.microsoft.com/en-us/azure/cognitive-services/academic-knowledge/graphsearchmethod

is not clear to me.

I have also read Microsoft Academic Graph Search - retrieving all papers from a journal within a time-frame?

I am trying with something like this:

import requests

url = "https://westus.api.cognitive.microsoft.com/academic/v1.0/graph/search"

querystring = {"mode":"json%0A"}

payload = "{}"

response = requests.request("POST", url, data=payload, params=querystring)

print(response.text)

What should I put in "payload" to retrieve the affiliation of, for example, the Author "John Doe" ?


问:
Growing Tables with aggregations
I'm looking at creating a table that could potentially be loaded with 100s of rows. I was hoping to use the growing option that the tables provide. I have a few questions.

If I have a aggregation which is a total for all the rows in that column, will it be the total of all rows or only of those that have been loaded. Or can this be set with a variable etc.

similar to above the select all feature to tick all the rows, will this select every row even the ones not included, or will it just select the loaded rows. Again is this just a variable that I can set.

This is a first time really using any of the UI5 table elements, and the sap said this which I didn't really understand:

"Show Aggregations
Show aggregations (such as totals) on the table footer (sap.m.Column, aggregation: footer).
Do not show aggregations in “growing” mode. It is not clear, if an aggregation will only aggregate the items loaded into the front end, or all items."

答:
For the growing tables, by default all actions and aggregations will only be processed for the data already loaded. Your citation from SAP means that it is not clear to the end user if the aggregated data refers to the visible data or to all data.

If you want to implement something like "Select all" or "Delete All", it would be better to implement this in the backend. From the guidelines of sap.m.List:

In multiple selection mode, users can (de)select all items using the shortcut CTRL+A. This only affects items that have already been loaded to the front-end server. All other items are not (de)selected before they are loaded (for example, items added via lazy loading with growingScrollToLoad). This conflicts with the guideline that all items the user can reach by scrolling must be (de)selected.

To process all items, listen to the selectionChange event and to its flag selectAll. This indicates whether CTRL+A was triggered. As soon as an action is triggered, process the items accordingly. Depending on the number of items, consider processing them in the back end.

Title: Growing Tables with aggregations