问:
What happens to a process in an EC2 instance when I get a 'Broken Pipe' error on ssh?
I am using some EC2 instances to run some large jobs I can not run locally. The issue I am seeing is that after a while (X hours since the process started) my connection on my shell gives me a broken pipe error

```<code>ubuntu@ip-10-122-xxx-xxx:~/stratto/ode$ Write failed: Broken pipe
</code>```

The instance is still there because I can reconnect with no problems, but how can I reconnect and get back at seeing the logs of the process as before the 'Broken Pipe'

Any tip much appreciated,
Thanks!

答: You can use "screen". Detach from it and ping to google.com. So there ssh session will be active through out the installation.

Body:
I am using some EC2 instances to run some large jobs I can not run locally. The issue I am seeing is that after a while (X hours since the process started) my connection on my shell gives me a broken pipe error

ubuntu@ip-10-122-xxx-xxx:~/stratto/ode$ Write failed: Broken pipe

The instance is still there because I can reconnect with no problems, but how can I reconnect and get back at seeing the logs of the process as before the 'Broken Pipe'

Any tip much appreciated,
Thanks!


来源: stackexchange

问:
Airflow - xcom_pull in the bigquery operator
I try to use xcomm_pull to insert a data_key_param calculated by the python_operator and pass it to the bigquery_operator. The python operator return the output as string e.g. "2020-05-31".

I got an error when running the BigqueryOperator: "Dependencies Blocking Task From Getting Scheduled" - Could not cast literal "{xcom_pull(task_ids[\'set_date_key_param\'])[0] }"

The sql attribute value returned from the Airflow GUI after task execution:

SELECT DATE_KEY, count(*) as COUNT

FROM my-project.my_datasets.source_table

WHERE DATE_KEY = {{ task_instance.xcom_pull(task_ids='set_date_key_param') }}

GROUP BY DATE_KEY

Code below (I have already treid to use '{{' and '}}' to enclose the task_instance.xcom...):

```<code>def set_date_key_param():

    # a business logic here
    return "2020-05-31" # example results

# task 1

set_date_key_param = PythonOperator(
    task_id='set_date_key_param',
    provide_context=True,
    python_callable=set_date_key_param,
    dag=dag
)

# taks 2

load_data_to_bq_table = BigQueryOperator(
    task_id='load_data_to_bq_table',
    sql="""SELECT DATE_KEY, count(*) as COUNT
    FROM `{project}.{dataset}.source_table`
    WHERE DATE_KEY = {{{{ task_instance.xcom_pull(task_ids='set_date_key_param') }}}}
    GROUP BY DATE_KEY""".format(
        project=PROJECT_ID,
        env=ENV
),
use_legacy_sql=False,
destination_dataset_table="{project}.{dataset}.target_table".format(
    project=PROJECT_ID,
    dataset=BQ_TARGET_DATASET,
),
write_disposition="WRITE_TRUNCATE",
create_disposition="CREATE_NEVER",
trigger_rule='all_success',
dag=dag
</code>```

)

set_date_key_param >> load_data_to_bq_table

答:
I think the string formatting and jinja template is conflicting each other.

In your use case where leveraging xcom, I think it makes sense to use jinja template.

```<code>load_data_to_bq_table = BigQueryOperator(
    task_id='load_data_to_bq_table',
    sql="""SELECT DATE_KEY, count(*) as COUNT
        FROM `{{ params.project }}.{{ params.dataset }}.source_table`
        WHERE DATE_KEY = \"{{ task_instance.xcom_pull(task_ids='set_date_key_param') }}\"
        GROUP BY DATE_KEY""",
    params={
        'project': PROJECT_ID,
        'env': ENV   # env or dataset??, match this name to the params key in sql
    }
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to use xcomm_pull to insert a data_key_param calculated by the python_operator and pass it to the bigquery_operator. The python operator return the output as string e.g. "2020-05-31".

I got an error when running the BigqueryOperator: "Dependencies Blocking Task From Getting Scheduled" - Could not cast literal "{xcom_pull(task_ids[\'set_date_key_param\'])[0] }"

The sql attribute value returned from the Airflow GUI after task execution:

SELECT DATE_KEY, count(*) as COUNT

FROM my-project.my_datasets.source_table

WHERE DATE_KEY = {{ task_instance.xcom_pull(task_ids='set_date_key_param') }}

GROUP BY DATE_KEY

Code below (I have already treid to use '{{' and '}}' to enclose the task_instance.xcom...):

def set_date_key_param():

    # a business logic here
    return "2020-05-31" # example results

# task 1

set_date_key_param = PythonOperator(
    task_id='set_date_key_param',
    provide_context=True,
    python_callable=set_date_key_param,
    dag=dag
)

# taks 2

load_data_to_bq_table = BigQueryOperator(
    task_id='load_data_to_bq_table',
    sql="""SELECT DATE_KEY, count(*) as COUNT
    FROM `{project}.{dataset}.source_table`
    WHERE DATE_KEY = {{{{ task_instance.xcom_pull(task_ids='set_date_key_param') }}}}
    GROUP BY DATE_KEY""".format(
        project=PROJECT_ID,
        env=ENV
),
use_legacy_sql=False,
destination_dataset_table="{project}.{dataset}.target_table".format(
    project=PROJECT_ID,
    dataset=BQ_TARGET_DATASET,
),
write_disposition="WRITE_TRUNCATE",
create_disposition="CREATE_NEVER",
trigger_rule='all_success',
dag=dag

)

set_date_key_param >> load_data_to_bq_table

Body:
I think the string formatting and jinja template is conflicting each other.

In your use case where leveraging xcom, I think it makes sense to use jinja template.

load_data_to_bq_table = BigQueryOperator(
    task_id='load_data_to_bq_table',
    sql="""SELECT DATE_KEY, count(*) as COUNT
        FROM `{{ params.project }}.{{ params.dataset }}.source_table`
        WHERE DATE_KEY = \"{{ task_instance.xcom_pull(task_ids='set_date_key_param') }}\"
        GROUP BY DATE_KEY""",
    params={
        'project': PROJECT_ID,
        'env': ENV   # env or dataset??, match this name to the params key in sql
    }
)


Title: How to restructure in a specific way a pandas dataframe?

Body:
I have the following df:

              Year           b      c     Monthly Flow (2018)    First thing  Second thing Third thing
1             2018   -0.041619  43.91               -0.041619           2000          1000           6
2             2018    0.011913  43.91               -0.041619           4000          120            8
3             2018   -0.048801  43.91               -0.041619           2000          1000           6
4             2018    0.002857  43.91               -0.041619           2000          1000           6

And I would like restructure it in order to achieve this output:

              Year           b      c     Monthly Flow (2018)    Process name    Value
1             2018   -0.041619  43.91               -0.041619     First thing     2000
1             2018    0.011913  43.91               -0.041619    Second thing     1000
1             2018   -0.048801  43.91               -0.041619     Third thing        6
2             2018   -0.041619  43.91               -0.041619     First thing     4000
2             2018    0.011913  43.91               -0.041619    Second thing      120
2             2018   -0.048801  43.91               -0.041619     Third thing        8
...

I tried to  pivot but I can't get this output.

Body:
You can use df.melt:

df.melt(id_vars=['Year','b','c','Monthly Flow (2018)'], var_name='Process name',value_name='Value')

Output:

    Year     b     c  Monthly_Flow_(2018)  Process name  Value
0   2018 -0.04 43.91                -0.04   First_thing   2000
1   2018  0.01 43.91                -0.04   First_thing   4000
2   2018 -0.05 43.91                -0.04   First_thing   2000
3   2018  0.00 43.91                -0.04   First_thing   2000
4   2018 -0.04 43.91                -0.04  Second_thing   1000
5   2018  0.01 43.91                -0.04  Second_thing    120
6   2018 -0.05 43.91                -0.04  Second_thing   1000
7   2018  0.00 43.91                -0.04  Second_thing   1000
8   2018 -0.04 43.91                -0.04   Third_thing      6
9   2018  0.01 43.91                -0.04   Third_thing      8
10  2018 -0.05 43.91                -0.04   Third_thing      6
11  2018  0.00 43.91                -0.04   Third_thing      6


问:
Time complexity question, i think it is impossible with current data
The question is :

. Let A be an array of integers in the range {1, ..., n}. Give an O(n)
  algorithm that gets rid of duplicate numbers, and sorts the elements
  of A in decreasing order of frequency, starting with the element that
  appears the most. For example, if A = [5, 1, 3, 1, 7, 7, 1, 3, 1, 3],
  then the output should be [1, 3, 7, 5].

the thing is, if we want to know how many time each number from 1 to n, appears we need to run of A which his length is m (m = A.length, because its unknow to us).

with bucket-sort , while m = O(n), its possible.

i think there is a problem in the question, because if m = θ(n), or even m = Ω(n).

so basically i think that without classify what m is, its impossible to achive O(n).

if someone know a way to solve this problem i would be glad.
thanks

答:
I agree with you that the problem as stated isn’t possible - O(n) time is not sufficient to even read all the elements of the array, which means you can’t necessarily find all the distinct elements in the given time bound.

However, if you assume the array has size O(n), then as you’ve noted this can be done with a counting sort.

You may want to contact whoever gave you this problem to point out that detail. :-)

Hope this helps!


问:
JavaScript: Find Matches AND Differences in two Arrays of Objects
Okay, so this is a tough one. I think.

I have two arrays of objects that contain some information about pods. I'm looking to provide a side by side comparison of environments to show where pods contain the exact same image; the trick is that I also need to catch the pods where the images aren't matching. The results are going to be rendered on a table which will look something like this (at least as a first iteration):

```<code>|---------------------|------------------|------------------|
|      Pod Name       | Image from Env1  |  Image from Env2 |
|---------------------|------------------|------------------|
|          foo        |     foo:1.0.0    |     foo:1.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          foo        |   foobar:1.0.0   |                  |   <---- No match for image tag; image name different from the pod name as the pods may contain multiple images
|---------------------|------------------|------------------|
|          foo        |                  |    foobar:2.0.0  |   <---- As above
|---------------------|------------------|------------------|
|          bar        |     bar:2.0.0    |     bar:2.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          baz        |     baz:1.0.0    |                  |   <----
|---------------------|------------------|------------------|         Note the 'no match'; so own row for now
|          baz        |                  |     baz:2.0.0    |   <----
|---------------------|------------------|------------------|
</code>```

I will later use CSS to highlight the matches vs. differences.

The things that I'm struggling with most are:

Pods may have more than 1 image. 1 of those images may match between environments, but the other may not. When there is more than one image the tags inside that pod differ (see foo pod in table above)

How to check the objects match between environments whilst still capturing the ones that don't match. Using nested loops cause a whole bunch of issues with duplicates and false negatives

I'm unsure on the best way to store the output. Likely something like: [{ "Pod Name": "foo", "Image_Env_1": foo:1.0.0", "Image_Env_2": foo:1.0.0"}... and leaving blank strings (like the blank cell in the table) for a value in the non-matching cases. But this may clash with the other image in the foo pod that has different image tags.

So Env1 array looks something like this snippet:

[
    {
        "Image": {
            "S": "foo:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:1.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    },
    {
        "Image": {
            "S": "qux:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    }
]```
</div>
</div>
</p>

<p><code>Env2</code> array:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
    {
        "Image": {
            "S": "foo:2.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:3.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    }
]</code>```

答:
This is pretty tough! But I think the process can be broken down into two main stages:

Finding the matches and differences.

Converting that information into something useful.

The first step can be further broken down into manipulating the original data and then processing it.

What I like to do when dealing with categories, like Pod Name, is to create Map objects that contain Set objects. In this case, it would probably look something like this:

// Let's assume Env1 is loaded already.
const podNameMap1 = new Map();
Env1.forEach( (value, index) => {
    // Here 'value' is element in Env1

    const podName = value['Pod Name'].S;
    const podValue = podNameMap.get(podName);
    // returns undefined if it does not exist

    if (!podValue) {
        podNameMap.set(podName, new Set(value['Image'].S) );
        // If there is no podValue, set podName to a new Set with the images in it.
    } else {
        // Here there is a podValue, and we can add a new member to the Set.
        podValue.add(value['Images'].S);
        // podValue is a Set object which means the map value needs to be set one time.
    }
});
```

<p>At the end of that <code>podNameMap1</code> has all the pods and all of their images. The next step is to do the same thing to <code>Env2</code>, at which point there are two maps of various pod names and images.</p>

<p>After that, the comparison can be made, which is more complicated than creating the maps:</p>

<pre class="lang-js prettyprint-override"><code>// Let's assume podNameMap1 and podNameMap2 are both loaded.
// I don't know if it's possible for pods to be mismatched,
// I'm going to assume they are cannot be.

// Images in both
const inBothEnvsMap = new Map();
// Images in env1 but not env2
const inEnv1Map = new Map();
// Images in env2 but not env1
const inEnv2Map = new Map();

podNameMap1.forEach( (imageSet1, podName) => {
    // Here, imageSet1 and podName are self explanitory
    const imageSet2 = podNameMap1.get(podName); // assuming this is always the case

    // Computing the set intersections n stuff
    const inEnv1 = new Set();
    const inEnv2 = new Set();
    const inBothEnvs = new Set();

    // Note: I wish JS had built in set operations because there's probably
    // a better way to do this but alas...
    imageSet1.forEach( image => {
        if (imageSet2.has(image))
            inBothEnvs.add(image);
        else // in imageSet1 only
            inEnv1.add(image);
    });
    // now inEnv1 AND inBothEnvs are complete

    imageSet2.forEach( image => {
        if (!imageSet1.has(image))
            inEnv2.add(image);
    });

    // now this pod is done
    inBothEnvsMap.set(podName, inBothEnvs);
    inEnv1Map.set(podName, inEnv1);
    inEnv2Map.set(podname, inEnv2);
});
</code>```

At this point, this is the "finding the matches and differences" step.

Moving on to the next step "converting that information into something useful" is the part that's less specific to simple set operations so I can't really give sound advice on that.

Body:
Okay, so this is a tough one. I think.

I have two arrays of objects that contain some information about pods. I'm looking to provide a side by side comparison of environments to show where pods contain the exact same image; the trick is that I also need to catch the pods where the images aren't matching. The results are going to be rendered on a table which will look something like this (at least as a first iteration):

|---------------------|------------------|------------------|
|      Pod Name       | Image from Env1  |  Image from Env2 |
|---------------------|------------------|------------------|
|          foo        |     foo:1.0.0    |     foo:1.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          foo        |   foobar:1.0.0   |                  |   <---- No match for image tag; image name different from the pod name as the pods may contain multiple images
|---------------------|------------------|------------------|
|          foo        |                  |    foobar:2.0.0  |   <---- As above
|---------------------|------------------|------------------|
|          bar        |     bar:2.0.0    |     bar:2.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          baz        |     baz:1.0.0    |                  |   <----
|---------------------|------------------|------------------|         Note the 'no match'; so own row for now
|          baz        |                  |     baz:2.0.0    |   <----
|---------------------|------------------|------------------|

I will later use CSS to highlight the matches vs. differences.

The things that I'm struggling with most are:

Pods may have more than 1 image. 1 of those images may match between environments, but the other may not. When there is more than one image the tags inside that pod differ (see foo pod in table above)

How to check the objects match between environments whilst still capturing the ones that don't match. Using nested loops cause a whole bunch of issues with duplicates and false negatives

I'm unsure on the best way to store the output. Likely something like: [{ "Pod Name": "foo", "Image_Env_1": foo:1.0.0", "Image_Env_2": foo:1.0.0"}... and leaving blank strings (like the blank cell in the table) for a value in the non-matching cases. But this may clash with the other image in the foo pod that has different image tags.

So Env1 array looks something like this snippet:

[
    {
        "Image": {
            "S": "foo:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:1.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    },
    {
        "Image": {
            "S": "qux:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    }
]

Env2 array:

[
    {
        "Image": {
            "S": "foo:2.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:3.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    }
]

Body:
This is pretty tough! But I think the process can be broken down into two main stages:

Finding the matches and differences.

Converting that information into something useful.

The first step can be further broken down into manipulating the original data and then processing it.

What I like to do when dealing with categories, like Pod Name, is to create Map objects that contain Set objects. In this case, it would probably look something like this:

// Let's assume Env1 is loaded already.
const podNameMap1 = new Map();
Env1.forEach( (value, index) => {
    // Here 'value' is element in Env1

    const podName = value['Pod Name'].S;
    const podValue = podNameMap.get(podName);
    // returns undefined if it does not exist

    if (!podValue) {
        podNameMap.set(podName, new Set(value['Image'].S) );
        // If there is no podValue, set podName to a new Set with the images in it.
    } else {
        // Here there is a podValue, and we can add a new member to the Set.
        podValue.add(value['Images'].S);
        // podValue is a Set object which means the map value needs to be set one time.
    }
});

At the end of that podNameMap1 has all the pods and all of their images. The next step is to do the same thing to Env2, at which point there are two maps of various pod names and images.

After that, the comparison can be made, which is more complicated than creating the maps:

// Let's assume podNameMap1 and podNameMap2 are both loaded.
// I don't know if it's possible for pods to be mismatched,
// I'm going to assume they are cannot be.

// Images in both
const inBothEnvsMap = new Map();
// Images in env1 but not env2
const inEnv1Map = new Map();
// Images in env2 but not env1
const inEnv2Map = new Map();

podNameMap1.forEach( (imageSet1, podName) => {
    // Here, imageSet1 and podName are self explanitory
    const imageSet2 = podNameMap1.get(podName); // assuming this is always the case

    // Computing the set intersections n stuff
    const inEnv1 = new Set();
    const inEnv2 = new Set();
    const inBothEnvs = new Set();

    // Note: I wish JS had built in set operations because there's probably
    // a better way to do this but alas...
    imageSet1.forEach( image => {
        if (imageSet2.has(image))
            inBothEnvs.add(image);
        else // in imageSet1 only
            inEnv1.add(image);
    });
    // now inEnv1 AND inBothEnvs are complete

    imageSet2.forEach( image => {
        if (!imageSet1.has(image))
            inEnv2.add(image);
    });

    // now this pod is done
    inBothEnvsMap.set(podName, inBothEnvs);
    inEnv1Map.set(podName, inEnv1);
    inEnv2Map.set(podname, inEnv2);
});

At this point, this is the "finding the matches and differences" step.

Moving on to the next step "converting that information into something useful" is the part that's less specific to simple set operations so I can't really give sound advice on that.


问:
How to catch deferred.reject using supertest and chai?
I'm using supertest, chai and mocha to test my Web API application. I have the following code:

```<code>it('should return 500', function(done) {
    this.timeout(30000);
    request(server)
        .get('/some/path')
        .expect(500)
        .end(function(err, res) {
            done();
        });
});
</code>```

It should fail. The code which runs in the get request is:

```<code>        // Inside method getData
        try {
            // Get data
            // throws error
        } catch (e) {
            // catches error and displays it
            deferred.reject(e);
            return deferred.promise;
        }

    // Other code not in getData method
    dbOps.params.getData(collection, parameter, query).then(
         function (arr) {
            response.send(arr);
         }, function (err) {
            logger.error(err.message);
            response.status(500).send(err.message);
         }
    );
</code>```

It basically does deferred.reject(e); and sends the error as the response of the API. I would like to catch the deferred.reject(e); part and in the same time continue the chain of .except(500).end(...). Something like:

```<code>catch_deferred(request(server).get('/some/path'))
        .expect(500)
        .end(function(err, res) {
            expect(err).to.equal(null);
            expect(res.body).to.be.an('object').that.is.empty;
            done();
</code>```

Is there some way to do it? I can't use the try-catch block because its not an exception. Also I can't chai's expect().to.throw() because there is not exception being thrown.

答:
Disclaimer: I never use deferred.reject().

Possible solution: use sinon.

You can use spy, if you want the real deferred.reject() to run and you just want to monitor it. Monitor means: to know whether the method get called, with what argument, and also the return value. Example:

// Preparation: (Disclaimer: I never use Deferred.reject())
const spyDeferredReject = sinon.spy(Deferred, 'reject');
// Do stuff..
// Expectation phase: check whether deferred reject get called.
expect(spyDeferredReject.calledOnce).to.equal(true);
// Check whether deferred reject called with correct argument.
expect(spyDeferredReject.args[0][0]).to.be.an('error');
```

You can use stub, if you want to monitor it and make sure the real method not get called.

Hope this helps.

Body:
I'm using supertest, chai and mocha to test my Web API application. I have the following code:

it('should return 500', function(done) {
    this.timeout(30000);
    request(server)
        .get('/some/path')
        .expect(500)
        .end(function(err, res) {
            done();
        });
});

It should fail. The code which runs in the get request is:

        // Inside method getData
        try {
            // Get data
            // throws error
        } catch (e) {
            // catches error and displays it
            deferred.reject(e);
            return deferred.promise;
        }

    // Other code not in getData method
    dbOps.params.getData(collection, parameter, query).then(
         function (arr) {
            response.send(arr);
         }, function (err) {
            logger.error(err.message);
            response.status(500).send(err.message);
         }
    );

It basically does deferred.reject(e); and sends the error as the response of the API. I would like to catch the deferred.reject(e); part and in the same time continue the chain of .except(500).end(...). Something like:

catch_deferred(request(server).get('/some/path'))
        .expect(500)
        .end(function(err, res) {
            expect(err).to.equal(null);
            expect(res.body).to.be.an('object').that.is.empty;
            done();

Is there some way to do it? I can't use the try-catch block because its not an exception. Also I can't chai's expect().to.throw() because there is not exception being thrown.

Body:
Disclaimer: I never use deferred.reject().

Possible solution: use sinon.

You can use spy, if you want the real deferred.reject() to run and you just want to monitor it. Monitor means: to know whether the method get called, with what argument, and also the return value. Example:

// Preparation: (Disclaimer: I never use Deferred.reject())
const spyDeferredReject = sinon.spy(Deferred, 'reject');
// Do stuff..
// Expectation phase: check whether deferred reject get called.
expect(spyDeferredReject.calledOnce).to.equal(true);
// Check whether deferred reject called with correct argument.
expect(spyDeferredReject.args[0][0]).to.be.an('error');

You can use stub, if you want to monitor it and make sure the real method not get called.

Hope this helps.


问:
Recursive depth function on an array
I have an array of objects like this input, and I want to nest some objects inside another objects (based if their parentId is the parents' forumId),

I got the function working but up to 1 depth, how can I get it working for n depth? Any idea or optimizations are appreciated!

EDIT: After pointing out, the input isn't necessarily ordered.

const input = [
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 2,
    parentId: 1,
    forumName: "Announcements",
    forumDescription: "Announcements & Projects posted here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 3,
    parentId: 1,
    forumName: "General",
    forumDescription: "General forum, talk whatever you want here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 4,
    parentId: 3,
    forumName: "Introduction",
    forumDescription: "A warming introduction for newcomers here",
    forumLocked: false,
    forumDisplay: true,
  },
];

function processInput(forumInput) {
  const topLevelForums = forumInput.filter(function (forum) {
    return forum.parentId === null;
  });

  let output = topLevelForums;

  forumInput.forEach(function (forum) {
    if (forum.parentId !== null) {
      const forumParentId = forum.parentId;
      output.forEach(function (parentForum, idx) {
        if (parentForum.forumId === forumParentId) {
          if (!output[idx].hasOwnProperty("subForums")) {
            output[idx].subForums = [];
          }
          parentForum.subForums.push(forum);
        }
      });
    }
  });

  return output;
}
```

<p>This is the <strong>expected output</strong>:</p>

```[
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
    subForums: [
      {
        forumId: 2,
        parentId: 1,
        forumName: "Announcements",
        forumDescription: "Announcements & Projects posted here",
        forumLocked: false,
        forumDisplay: true,
      },
      {
        forumId: 3,
        parentId: 1,
        forumName: "General",
        forumDescription: "General forum, talk whatever you want here",
        forumLocked: false,
        forumDisplay: true,
        subForums: [
          {
            forumId: 4,
            parentId: 3,
            forumName: "Introduction",
            forumDescription: "A warming introduction for newcomers here",
            forumLocked: false,
            forumDisplay: true,
          },
        ],
      },
    ],
  },
]
```

<p>This is the <strong>current output</strong>:</p>

```[
  {
    forumDescription: "",
    forumDisplay: true,
    forumId: 1,
    forumLocked: false,
    forumName: "Main",
    parentId: null,
    subForums: [
      {
        forumDescription: "Announcements & Projects posted here",
        forumDisplay: true,
        forumId: 2,
        forumLocked: false,
        forumName: "Announcements",
        parentId: 1,
      },
      {
        forumDescription: "General forum, talk whatever you want here",
        forumDisplay: true,
        forumId: 3,
        forumLocked: false,
        forumName: "General",
        parentId: 1,
      },
    ],
  },
]
```

答:
A wonderful opportunity to learn about mutual recursion. The input can be in any order -

function makeIndex (items, indexer)
{ const append = (r, k, v) =>
    r.set(k, (r.get(k) || []).concat([ v ]))

  return items.reduce
    ( (r, i) => append(r, indexer(i), i)
    , new Map
    )
}

function makeTree (index, root = null)
{ const many = (all = []) =>
    all.map(one)

  const one = (forum = {}) =>
    ( { ...forum
      , subforums: many(index.get(forum.forumId))
      }
    )

  return many(index.get(root))
}

const input =
  [{forumId:1,parentId:null,forumName:"Main",forumDescription:"",forumLocked:false,forumDisplay:true},{forumId:2,parentId:1,forumName:"Announcements",forumDescription:"Announcements & Projects posted here",forumLocked:false,forumDisplay:true},{forumId:3,parentId:1,forumName:"General",forumDescription:"General forum, talk whatever you want here",forumLocked:false,forumDisplay:true},{forumId:4,parentId:3,forumName:"Introduction",forumDescription:"A warming introduction for newcomers here",forumLocked:false,forumDisplay:true}]

const result =
  makeTree(makeIndex(input, forum => forum.parentId))

console.log(JSON.stringify(result, null, 2))```
</div>
</div>
</p>

```[
  {
    "forumId": 1,
    "parentId": null,
    "forumName": "Main",
    "forumDescription": "",
    "forumLocked": false,
    "forumDisplay": true,
    "subforums": [
      {
        "forumId": 2,
        "parentId": 1,
        "forumName": "Announcements",
        "forumDescription": "Announcements & Projects posted here",
        "forumLocked": false,
        "forumDisplay": true,
        "subforums": []
      },
      {
        "forumId": 3,
        "parentId": 1,
        "forumName": "General",
        "forumDescription": "General forum, talk whatever you want here",
        "forumLocked": false,
        "forumDisplay": true,
        "subforums": [
          {
            "forumId": 4,
            "parentId": 3,
            "forumName": "Introduction",
            "forumDescription": "A warming introduction for newcomers here",
            "forumLocked": false,
            "forumDisplay": true,
            "subforums": []
          }
        ]
      }
    ]
  }
]
```

<hr>

<p><strong>make it modular</strong></p>

<p>Above <code>makeIndex</code> is written in a way that it can index any array of datum, but <code>makeTree</code> makes assumptions like <code>...forum</code>, <code>subforums</code>, and <code>forum.forumId</code>. When we think about our code in modules, we are forced to draw lines of separation and consequently our programs become untangled.</p>

<p>Below, <code>input</code> is defined in <code>main</code> and so we keep all knowledge about <code>input</code> here -</p>

<pre class="lang-js prettyprint-override"><code>// main.js
import { tree } from './tree'

const input =
  [{forumId:1,parentId:null,forumName:"Main",forumDescription:"",forumLocked:false,forumDisplay:true},{forumId:2,parentId:1,forumName:"Announcements",forumDescription:"Announcements & Projects posted here",forumLocked:false,forumDisplay:true},{forumId:3,parentId:1,forumName:"General",forumDescription:"General forum, talk whatever you want here",forumLocked:false,forumDisplay:true},{forumId:4,parentId:3,forumName:"Introduction",forumDescription:"A warming introduction for newcomers here",forumLocked:false,forumDisplay:true}]

const result =
  tree
    ( input                    // <- array of nodes
    , forum => forum.parentId  // <- foreign key
    , (forum, subforums) =>    // <- node reconstructor function
        ({ ...forum, subforums: subforums(forum.forumId) }) // <- primary key
    )

console.log(JSON.stringify(result, null, 2))
</code>```

When I make a tree, I don't want to have to think about making an index first. In our original program, how was I supposed to know a tree needed an index? Let's let the tree module worry about that -

// tree.js
import { index } from './index'

const empty =
  {}

function tree (all, indexer, maker, root = null)
{ const cache =
    index(all, indexer)

  const many = (all = []) =>
    all.map(x => one(x))
                             // zero knowledge of forum object shape
  const one = (single) =>
    maker(single, next => many(cache.get(next)))

  return many(cache.get(root))
}

export { empty, tree } // <-- public interface
```

<p>We could have written the <code>index</code> function directly in the <code>tree</code> module but the behavior we want is not specific to trees. Writing a separate <code>index</code> module makes more sense -</p>

<pre class="lang-js prettyprint-override"><code>// index.js
const empty = _ =>
  new Map

const update = (r, k, t) =>
  r.set(k, t(r.get(k)))

const append = (r, k, v) =>
  update(r, k, (all = []) => [...all, v])

const index = (all = [], indexer) =>
  all.reduce
      ( (r, v) => append(r, indexer(v), v) // zero knowledge of v shape
      , empty()
      )

export { empty, index, append } // <-- public interface
</code>```

Writing modules helps you think about your code in meaningful parts and promotes a high degree of code reusability.

Title: Recursive depth function on an array

Body:
I have an array of objects like this input, and I want to nest some objects inside another objects (based if their parentId is the parents' forumId),

I got the function working but up to 1 depth, how can I get it working for n depth? Any idea or optimizations are appreciated!

EDIT: After pointing out, the input isn't necessarily ordered.

const input = [
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 2,
    parentId: 1,
    forumName: "Announcements",
    forumDescription: "Announcements & Projects posted here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 3,
    parentId: 1,
    forumName: "General",
    forumDescription: "General forum, talk whatever you want here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 4,
    parentId: 3,
    forumName: "Introduction",
    forumDescription: "A warming introduction for newcomers here",
    forumLocked: false,
    forumDisplay: true,
  },
];

function processInput(forumInput) {
  const topLevelForums = forumInput.filter(function (forum) {
    return forum.parentId === null;
  });

  let output = topLevelForums;

  forumInput.forEach(function (forum) {
    if (forum.parentId !== null) {
      const forumParentId = forum.parentId;
      output.forEach(function (parentForum, idx) {
        if (parentForum.forumId === forumParentId) {
          if (!output[idx].hasOwnProperty("subForums")) {
            output[idx].subForums = [];
          }
          parentForum.subForums.push(forum);
        }
      });
    }
  });

  return output;
}

This is the expected output:

[
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
    subForums: [
      {
        forumId: 2,
        parentId: 1,
        forumName: "Announcements",
        forumDescription: "Announcements & Projects posted here",
        forumLocked: false,
        forumDisplay: true,
      },
      {
        forumId: 3,
        parentId: 1,
        forumName: "General",
        forumDescription: "General forum, talk whatever you want here",
        forumLocked: false,
        forumDisplay: true,
        subForums: [
          {
            forumId: 4,
            parentId: 3,
            forumName: "Introduction",
            forumDescription: "A warming introduction for newcomers here",
            forumLocked: false,
            forumDisplay: true,
          },
        ],
      },
    ],
  },
]

This is the current output:

[
  {
    forumDescription: "",
    forumDisplay: true,
    forumId: 1,
    forumLocked: false,
    forumName: "Main",
    parentId: null,
    subForums: [
      {
        forumDescription: "Announcements & Projects posted here",
        forumDisplay: true,
        forumId: 2,
        forumLocked: false,
        forumName: "Announcements",
        parentId: 1,
      },
      {
        forumDescription: "General forum, talk whatever you want here",
        forumDisplay: true,
        forumId: 3,
        forumLocked: false,
        forumName: "General",
        parentId: 1,
      },
    ],
  },
]

Body:
A wonderful opportunity to learn about mutual recursion. The input can be in any order -

function makeIndex (items, indexer)
{ const append = (r, k, v) =>
    r.set(k, (r.get(k) || []).concat([ v ]))

  return items.reduce
    ( (r, i) => append(r, indexer(i), i)
    , new Map
    )
}

function makeTree (index, root = null)
{ const many = (all = []) =>
    all.map(one)

  const one = (forum = {}) =>
    ( { ...forum
      , subforums: many(index.get(forum.forumId))
      }
    )

  return many(index.get(root))
}

const input =
  [{forumId:1,parentId:null,forumName:"Main",forumDescription:"",forumLocked:false,forumDisplay:true},{forumId:2,parentId:1,forumName:"Announcements",forumDescription:"Announcements & Projects posted here",forumLocked:false,forumDisplay:true},{forumId:3,parentId:1,forumName:"General",forumDescription:"General forum, talk whatever you want here",forumLocked:false,forumDisplay:true},{forumId:4,parentId:3,forumName:"Introduction",forumDescription:"A warming introduction for newcomers here",forumLocked:false,forumDisplay:true}]

const result =
  makeTree(makeIndex(input, forum => forum.parentId))

console.log(JSON.stringify(result, null, 2))

[
  {
    "forumId": 1,
    "parentId": null,
    "forumName": "Main",
    "forumDescription": "",
    "forumLocked": false,
    "forumDisplay": true,
    "subforums": [
      {
        "forumId": 2,
        "parentId": 1,
        "forumName": "Announcements",
        "forumDescription": "Announcements & Projects posted here",
        "forumLocked": false,
        "forumDisplay": true,
        "subforums": []
      },
      {
        "forumId": 3,
        "parentId": 1,
        "forumName": "General",
        "forumDescription": "General forum, talk whatever you want here",
        "forumLocked": false,
        "forumDisplay": true,
        "subforums": [
          {
            "forumId": 4,
            "parentId": 3,
            "forumName": "Introduction",
            "forumDescription": "A warming introduction for newcomers here",
            "forumLocked": false,
            "forumDisplay": true,
            "subforums": []
          }
        ]
      }
    ]
  }
]

make it modular

Above makeIndex is written in a way that it can index any array of datum, but makeTree makes assumptions like ...forum, subforums, and forum.forumId. When we think about our code in modules, we are forced to draw lines of separation and consequently our programs become untangled.

Below, input is defined in main and so we keep all knowledge about input here -

// main.js
import { tree } from './tree'

const input =
  [{forumId:1,parentId:null,forumName:"Main",forumDescription:"",forumLocked:false,forumDisplay:true},{forumId:2,parentId:1,forumName:"Announcements",forumDescription:"Announcements & Projects posted here",forumLocked:false,forumDisplay:true},{forumId:3,parentId:1,forumName:"General",forumDescription:"General forum, talk whatever you want here",forumLocked:false,forumDisplay:true},{forumId:4,parentId:3,forumName:"Introduction",forumDescription:"A warming introduction for newcomers here",forumLocked:false,forumDisplay:true}]

const result =
  tree
    ( input                    // <- array of nodes
    , forum => forum.parentId  // <- foreign key
    , (forum, subforums) =>    // <- node reconstructor function
        ({ ...forum, subforums: subforums(forum.forumId) }) // <- primary key
    )

console.log(JSON.stringify(result, null, 2))

When I make a tree, I don't want to have to think about making an index first. In our original program, how was I supposed to know a tree needed an index? Let's let the tree module worry about that -

// tree.js
import { index } from './index'

const empty =
  {}

function tree (all, indexer, maker, root = null)
{ const cache =
    index(all, indexer)

  const many = (all = []) =>
    all.map(x => one(x))
                             // zero knowledge of forum object shape
  const one = (single) =>
    maker(single, next => many(cache.get(next)))

  return many(cache.get(root))
}

export { empty, tree } // <-- public interface

We could have written the index function directly in the tree module but the behavior we want is not specific to trees. Writing a separate index module makes more sense -

// index.js
const empty = _ =>
  new Map

const update = (r, k, t) =>
  r.set(k, t(r.get(k)))

const append = (r, k, v) =>
  update(r, k, (all = []) => [...all, v])

const index = (all = [], indexer) =>
  all.reduce
      ( (r, v) => append(r, indexer(v), v) // zero knowledge of v shape
      , empty()
      )

export { empty, index, append } // <-- public interface

Writing modules helps you think about your code in meaningful parts and promotes a high degree of code reusability.


问:
Access one item from a dict and store it into a variable
I am trying to get all the "uuid"'s from an API, and the issue is that it is stored into a dict (I think). Her is how it looks on the API:

```<code>{"guild": {
        "_id": "5eba1c5f8ea8c960a61f38ed",
        "name": "Creators Club",
        "name_lower": "creators club",
        "coins": 0,
        "coinsEver": 0,
        "created": 1589255263630,
        "members":
            [{  "uuid": "db03ceff87ad4909bababc0e2622aaf8",
                "rank": "Guild Master",
                "joined": 1589255263630,
                "expHistory": {
                "2020-06-01": 280,
                "2020-05-31": 4701,
                "2020-05-30": 0,
                "2020-05-29": 518,
                "2020-05-28": 1055,
                "2020-05-27": 136665,
                "2020-05-26": 34806}}]
        }
    }
</code>```

Now I am interested in the "uuid" part there, and take note: There is multiple players, it can be 1 to 100 players, and I am going to need every UUID.

Now I have done this in my python to get the UUID's displayed on the website:
try:

```<code>f = requests.get(
            "https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
        guildName = f["guild"]["name"]
        guildMembers = f["guild"]["members"]
        members = client.getPlayer(uuid=guildMembers) #this converts UUID to player names
        #I need to store all uuid's in variables and put them at "guildMembers"
</code>```

And that gives me all the "UUID codes", and I will be using client.getPlayer(uuid=---) to convert the UUID into the Player Names. I have to loop through each "UUID" into that code client.getPlayer(uuid=---) . But first of I need to save the UUID'S in variables, I have been doing members.uuid to access the UUID on my HTML file, but I don't know how you do the .uuid part in python

If you need anything else, just comment :)

答:
List comprehension is a powerful concept:

```<code>members = [client.getPlayer(member['uuid']) for member in guildMembers]
</code>```

Edit:
If you want to insert the names back into your data (in guildMembers),
use a dictionary comprehension with {uuid: member_name,} format:

```<code>members = {member['uuid']: client.getPlayer(uuid=member['uuid']) for member in guildMembers}
</code>```

Than you can update guildMembers with your results:

```<code>for member in guildMembers:
    guildMembers[member]['name'] = members[member['uuid']]
</code>```

Body:
I am trying to get all the "uuid"'s from an API, and the issue is that it is stored into a dict (I think). Her is how it looks on the API:

{"guild": {
        "_id": "5eba1c5f8ea8c960a61f38ed",
        "name": "Creators Club",
        "name_lower": "creators club",
        "coins": 0,
        "coinsEver": 0,
        "created": 1589255263630,
        "members":
            [{  "uuid": "db03ceff87ad4909bababc0e2622aaf8",
                "rank": "Guild Master",
                "joined": 1589255263630,
                "expHistory": {
                "2020-06-01": 280,
                "2020-05-31": 4701,
                "2020-05-30": 0,
                "2020-05-29": 518,
                "2020-05-28": 1055,
                "2020-05-27": 136665,
                "2020-05-26": 34806}}]
        }
    }

Now I am interested in the "uuid" part there, and take note: There is multiple players, it can be 1 to 100 players, and I am going to need every UUID.

Now I have done this in my python to get the UUID's displayed on the website:
try:

f = requests.get(
            "https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
        guildName = f["guild"]["name"]
        guildMembers = f["guild"]["members"]
        members = client.getPlayer(uuid=guildMembers) #this converts UUID to player names
        #I need to store all uuid's in variables and put them at "guildMembers"

And that gives me all the "UUID codes", and I will be using client.getPlayer(uuid=---) to convert the UUID into the Player Names. I have to loop through each "UUID" into that code client.getPlayer(uuid=---) . But first of I need to save the UUID'S in variables, I have been doing members.uuid to access the UUID on my HTML file, but I don't know how you do the .uuid part in python

If you need anything else, just comment :)

Body:
List comprehension is a powerful concept:

members = [client.getPlayer(member['uuid']) for member in guildMembers]

Edit:
If you want to insert the names back into your data (in guildMembers),
use a dictionary comprehension with {uuid: member_name,} format:

members = {member['uuid']: client.getPlayer(uuid=member['uuid']) for member in guildMembers}

Than you can update guildMembers with your results:

for member in guildMembers:
    guildMembers[member]['name'] = members[member['uuid']]


问:
Higher-order type constructors and functors in Ocaml
Can the following polymorphic functions

```<code>let id x = x;;
let compose f g x = f (g x);;
let rec fix f = f (fix f);;     (*laziness aside*)
</code>```

be written for types/type constructors or modules/functors? I tried

```<code>type 'x id = Id of 'x;;
type 'f 'g 'x compose = Compose of ('f ('g 'x));;
type 'f fix = Fix of ('f (Fix 'f));;
</code>```

for types but it doesn't work.

Here's a Haskell version for types:

```<code>data Id x = Id x
data Compose f g x = Compose (f (g x))
data Fix f = Fix (f (Fix f))

-- examples:
l = Compose [Just 'a'] :: Compose [] Maybe Char

type Natural = Fix Maybe   -- natural numbers are fixpoint of Maybe
n = Fix (Just (Fix (Just (Fix Nothing)))) :: Natural   -- n is 2

-- up to isomorphism composition of identity and f is f:
iso :: Compose Id f x -> f x
iso (Compose (Id a)) = a
</code>```

答:
Well... I'm not an expert of higher-order-types nor Haskell programming.
But this seems to be ok for F# (which is OCaml), could you work with these:

```<code>type 'x id = Id of 'x;;
type 'f fix = Fix of ('f fix -> 'f);;
type ('f,'g,'x) compose = Compose of ('f ->'g -> 'x);;
</code>```

The last one I wrapped to tuple as I didn't come up with anything better...

ContentLicense: CC BY-SA 2.5

Body:
Can the following polymorphic functions

let id x = x;;
let compose f g x = f (g x);;
let rec fix f = f (fix f);;     (*laziness aside*)

be written for types/type constructors or modules/functors? I tried

type 'x id = Id of 'x;;
type 'f 'g 'x compose = Compose of ('f ('g 'x));;
type 'f fix = Fix of ('f (Fix 'f));;

for types but it doesn't work.

Here's a Haskell version for types:

data Id x = Id x
data Compose f g x = Compose (f (g x))
data Fix f = Fix (f (Fix f))

-- examples:
l = Compose [Just 'a'] :: Compose [] Maybe Char

type Natural = Fix Maybe   -- natural numbers are fixpoint of Maybe
n = Fix (Just (Fix (Just (Fix Nothing)))) :: Natural   -- n is 2

-- up to isomorphism composition of identity and f is f:
iso :: Compose Id f x -> f x
iso (Compose (Id a)) = a

Body:
Well... I'm not an expert of higher-order-types nor Haskell programming.
But this seems to be ok for F# (which is OCaml), could you work with these:

type 'x id = Id of 'x;;
type 'f fix = Fix of ('f fix -> 'f);;
type ('f,'g,'x) compose = Compose of ('f ->'g -> 'x);;

The last one I wrapped to tuple as I didn't come up with anything better...

ContentLicense: CC BY-SA 3.0


问:
How to find out Target framework name and version from exe?
I have some exe files which has been created using either .net framework 4.5 or .net core 2.1 or .net core 3.1.

I want to get framework name and version information from this DLL using only c# application.

I have written below piece of code which is beneficial and works great with DLL files but not with exe.

```<code>var dllInformation = Assembly.LoadFrom(@"D:\\MyProgram.dll");
Console.WriteLine(dllInformation.FullName);
Console.WriteLine(dllInformation.ImageRuntimeVersion);
Console.WriteLine(((TargetFrameworkAttribute)dllInformation.GetCustomAttributes(typeof(TargetFrameworkAttribute)).First()).FrameworkName);
</code>```

I have also gone through these links but I didn't found them useful for exe files:

information from exe file

Determine .NET Framework version for dll

Please let me know if any suggestions available.

答:
The following program should display the version of the assembly. The program
 loads two assemblies during runtime using Assembly.LoadFrom method. 1) is a .NET Fx assembly and 2) is a .NET Core assembly. It loads both and displays the framework version without issues. This project is in github. If you are using the github project, you need to have .NET Core 3.1 installled.

```<code>using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;

namespace net007
{
    class Program
    {
        static void Main(string[] args)
        {
            //A .net framwwork dll in the same output fodler
            //as the current executable
            var fxAssembly = Assembly.LoadFrom("fx.console.app.exe");

            //A .net core dll in the same output fodler
            //as the current executable
            var netCoreAssembly = Assembly.LoadFrom("core.console.app.dll");

            ShowFrameworkVersion(fxAssembly); //.NETFramework,Version=v4.7.2
            ShowFrameworkVersion(netCoreAssembly);//.NETCoreApp,Version = v3.1
        }

        static void ShowFrameworkVersion(Assembly assembly)
        {
            var attributes = assembly.CustomAttributes;
            foreach (var attribute in attributes)
            {
                if (attribute.AttributeType == typeof(TargetFrameworkAttribute))
                {
                    var arg = attribute.ConstructorArguments.FirstOrDefault();
                    if (arg == null)
                        throw new NullReferenceException("Unable to read framework version");
                    Console.WriteLine(arg.Value);
                }
            }
        }
    }
}
</code>```

Body:
I have some exe files which has been created using either .net framework 4.5 or .net core 2.1 or .net core 3.1.

I want to get framework name and version information from this DLL using only c# application.

I have written below piece of code which is beneficial and works great with DLL files but not with exe.

var dllInformation = Assembly.LoadFrom(@"D:\\MyProgram.dll");
Console.WriteLine(dllInformation.FullName);
Console.WriteLine(dllInformation.ImageRuntimeVersion);
Console.WriteLine(((TargetFrameworkAttribute)dllInformation.GetCustomAttributes(typeof(TargetFrameworkAttribute)).First()).FrameworkName);

I have also gone through these links but I didn't found them useful for exe files:

information from exe file

Determine .NET Framework version for dll

Please let me know if any suggestions available.

Body:
The following program should display the version of the assembly. The program
 loads two assemblies during runtime using Assembly.LoadFrom method. 1) is a .NET Fx assembly and 2) is a .NET Core assembly. It loads both and displays the framework version without issues. This project is in github. If you are using the github project, you need to have .NET Core 3.1 installled.

using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;

namespace net007
{
    class Program
    {
        static void Main(string[] args)
        {
            //A .net framwwork dll in the same output fodler
            //as the current executable
            var fxAssembly = Assembly.LoadFrom("fx.console.app.exe");

            //A .net core dll in the same output fodler
            //as the current executable
            var netCoreAssembly = Assembly.LoadFrom("core.console.app.dll");

            ShowFrameworkVersion(fxAssembly); //.NETFramework,Version=v4.7.2
            ShowFrameworkVersion(netCoreAssembly);//.NETCoreApp,Version = v3.1
        }

        static void ShowFrameworkVersion(Assembly assembly)
        {
            var attributes = assembly.CustomAttributes;
            foreach (var attribute in attributes)
            {
                if (attribute.AttributeType == typeof(TargetFrameworkAttribute))
                {
                    var arg = attribute.ConstructorArguments.FirstOrDefault();
                    if (arg == null)
                        throw new NullReferenceException("Unable to read framework version");
                    Console.WriteLine(arg.Value);
                }
            }
        }
    }
}


问:
How to link path to font-awesome installation
I am pretty new to angular and the like. I am trying to link the font-awesome stylesheet, and I was to reference the path to the css folder of the font-awesome installation. I have used npm to install font-awesome, and when I reference font-awesome, I don't want to link to a website, I want to use the path that it is installed to.

The problem comes when I try to make the path more universal. If I have font-awesome installed to the repo that I am using, and I want anyone who uses the app to be able to see these icons, how can I write the path so that I don't put my own directories before the repo in the path?

For example, If the folder I am trying to link is at path C:/Users/Me/path/to/folder/font-awesome/css, how can I write this path so that anyone who uses the app can use the same path that will find the same folder in their system?

答:
1.keep complete font-awesome folder in assets folder.

go to angular.json

in styles array give path of /fontawesome/css/all.min.css


问:
Controller method is not invoked using IP but localhost
I am invoking a Controller method from javascript Ajax call. When I use localhost (fine only for dev) in below code, it invokes the Controller method but if I use IP address (IP is needed when code is hosted in other some other Linux box) in place of localhost, method is not invoked.

This code works as I can see call in the network tab in browser:

```<code>var tmpUrl = "https://localhost:<port>/method1?param1=" + value1 + "&param2="+value2;
$('#serviceBinding').load(tmpUrl);
</code>```

But when I use IP address in place of localhost, there is no invocation of controller method.

```<code>var tmpUrl = "https://xx.xxx.xxx.xx:<port>/method1?param1=" + value1 + "&param2="+value2;
$('#serviceBinding').load(tmpUrl);
</code>```

Below is the method in spring Controller.

```<code>@GetMapping("/method1")
@CrossOrigin(origins = "*", allowedHeaders = "*")
    public String method1(...
</code>```

I do not see any error related to CORS in the browser but I see below error in the inspect section of browser

```<code>GET <full URL> net::ERR_TIMED_OUT
</code>```

答:
I think you are not able to reach IP address, you don't have a HTTPS certificate for your IP address or you have an incorrect port.

Try to ping your IP address into CLI using ping or tracert commands to check if you can reach that ip address.

Also, are you able to open the full url in your browser?

Body:
I am invoking a Controller method from javascript Ajax call. When I use localhost (fine only for dev) in below code, it invokes the Controller method but if I use IP address (IP is needed when code is hosted in other some other Linux box) in place of localhost, method is not invoked.

This code works as I can see call in the network tab in browser:

var tmpUrl = "https://localhost:<port>/method1?param1=" + value1 + "&param2="+value2;
$('#serviceBinding').load(tmpUrl);

But when I use IP address in place of localhost, there is no invocation of controller method.

var tmpUrl = "https://xx.xxx.xxx.xx:<port>/method1?param1=" + value1 + "&param2="+value2;
$('#serviceBinding').load(tmpUrl);

Below is the method in spring Controller.

@GetMapping("/method1")
@CrossOrigin(origins = "*", allowedHeaders = "*")
    public String method1(...

I do not see any error related to CORS in the browser but I see below error in the inspect section of browser

GET <full URL> net::ERR_TIMED_OUT


问:
Databinding error: Only one layout element and one data element are allowed.
I'm getting following error when using databinding and include tag inside:

```<code>Error:Execution failed for task ':app:dataBindingProcessLayoutsBetaDebug'.>data binding error msg:Only one layout element and one data element are allowed. [path to file] has 3file:[path to file]****\ data binding error ****
</code>```

This is my layout file:

```<code>[...]

        <LinearLayout
            android:id="@+id/activity_description_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:orientation="vertical">

            <include
                android:id="@+id/activity_description_header_bottom"
                layout="@layout/activity_description_header_bottom" />

            <include
                android:id="@+id/activity_description_contact_info"
                layout="@layout/activity_description_contact_info" />

            <include
                android:id="@+id/activity_description_other_info_box"
                layout="@layout/activity_description_other_info_box" />

            <include
                android:id="@+id/activity_description_bottom_buttons"
                layout="@layout/activity_description_bottom_buttons" />
        </LinearLayout>
[...]
</layout>
</code>```

And in each of the included layouts i have something like this:

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android">
[...]
</layout>
</code>```

From this reply: Android Data Binding using include tag i suppose that my code is correct, why databinder thinks that I use more than single tag in the file?

答:
ViewBinding only one layout element is allowed.

DataBinding only one layout element and one data element are allowed.

build.gradle (:mobile)

```<code>android {
    //...

    buildFeatures{
        viewBinding = true
    }
}
</code>```

Do not use android:layout_width or android:layout_height as attributes of the <layout/> tag because otherwise dataBinding already counts it as a view and then in the scope of layot we could not put another view.

test.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <View
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- ... -->

    </View>

</layout>
</code>```

GL

Body:
I'm getting following error when using databinding and include tag inside:

Error:Execution failed for task ':app:dataBindingProcessLayoutsBetaDebug'.>data binding error msg:Only one layout element and one data element are allowed. [path to file] has 3file:[path to file]****\ data binding error ****

This is my layout file:

[...]

        <LinearLayout
            android:id="@+id/activity_description_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:orientation="vertical">

            <include
                android:id="@+id/activity_description_header_bottom"
                layout="@layout/activity_description_header_bottom" />

            <include
                android:id="@+id/activity_description_contact_info"
                layout="@layout/activity_description_contact_info" />

            <include
                android:id="@+id/activity_description_other_info_box"
                layout="@layout/activity_description_other_info_box" />

            <include
                android:id="@+id/activity_description_bottom_buttons"
                layout="@layout/activity_description_bottom_buttons" />
        </LinearLayout>
[...]
</layout>

And in each of the included layouts i have something like this:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
[...]
</layout>

From this reply: Android Data Binding using include tag i suppose that my code is correct, why databinder thinks that I use more than single tag in the file?

Body:
ViewBinding only one layout element is allowed.

DataBinding only one layout element and one data element are allowed.

build.gradle (:mobile)

android {
    //...

    buildFeatures{
        viewBinding = true
    }
}

Do not use android:layout_width or android:layout_height as attributes of the <layout/> tag because otherwise dataBinding already counts it as a view and then in the scope of layot we could not put another view.

test.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <View
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- ... -->

    </View>

</layout>

GL


问:
SQL - INSERT and catch the id auto-increment value
What is the best way to get the auto-id value in the same SQL with a SELECT?

A forum said adding this "; has Return Scope_Identity()"

in the end of the SQL works in ASP.

Is there a corresponding way in PHP?

答:
It depends on your database server. Using MySQL, call mysql_insert_id() immediately after your insert query. Using PostgreSQL, first query "select nextval(seq)" on the sequence and include the key in your insert query.

Querying for "select max(id) + 1 from tbl" could fail if another request inserts a record simultaneously.

LastEditorDisplayName: Milan Babuškov

OwnerDisplayName: Matthew


问:
C# web service against Oracle database source which is sometimes unavailable
We have an existing big application which contains a lot of data.  We'd like to use it as a datasource for various internally written C# web applications, so we don't have more redundant data.

The data we are looking at doesn't change too much, so caching would work fine most of the time.  So we are writing a C# Web Service against the data to be reused in various internally written applications.

However roughly once per month, the Oracle database source is unavailable.

What is the best way to handle this in the web service so that those other applications that rely on that data aren't disrupted also?

答:
The solution was to use a secondary Cache which doesn't expires.

The secondary cache is updated with the latest values if the first (shorter) cache is  successfully updated from the database.  If the database querying fails and the first cache has expired, then the first cache is updated by the second cache.  So there is always a secondary cache.


问:
Webpack-dev-server HMR not working for Angular app
In my Angular app, I am trying to use webpack-dev-server. I have my webpack config as follows:

```<code>//"use strict";

var webpack = require("webpack");

const AngularCompilerPlugin = require("@ngtools/webpack").AngularCompilerPlugin;

const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const resolve = require('path').resolve;

module.exports = function(env) {
  var environment = "'development'";
  console.log("Env: " + environment);

  return {
    stats: "errors-only",
    devtool: "source-map",
    mode: (environment == "'production'") ? "production" : "development",

    entry: {
      "polyfills": "./polyfills.ts",
      "vendor": "./vendor.ts",
      "main": "./main.ts",
      "styles": "./styles.ts"
    },

    resolve: {
      modules: [
        "node_modules",
        path.resolve(process.cwd(), "src")
      ],
      extensions: [".ts", ".js"]
    },
    context: path.join(process.cwd(), "./src"),

    output: {
      globalObject: 'this',
      path: path.join(process.cwd(), "dist"),
      publicPath: '/',
      filename: "[name].bundle.js",
      chunkFilename: "[name].chunk.js"
    },
    target: 'web',
    devServer: {
      disableHostCheck: true,
      host: require("os").hostname().toLowerCase(),
      publicPath: "/",
      port: 3000,
      watchContentBase: true,
      watchOptions: {
        poll: true
      },
      inline: true,
      hot: true,
      historyApiFallback:  {
        index: "/index.html"
      },
      https: true,
      proxy: {
        "/api": {
          //target: "https://" + require("os").hostname().toLowerCase() + "/"
          target:'https://URL.edu/',
          secure: false,
          changeOrigin:true,
          logLevel:"debug"
        },
        "/legacy/api": {
          //target: "https://" + require("os").hostname().toLowerCase() + "/"
          target:'https://URL.edu/',
          secure: false,
          changeOrigin:true,
          logLevel:"debug"
        },
        "/auth": {
          //target: "https://" + require("os").hostname().toLowerCase() + "/"
          target:'https://URL.edu/',
          secure: false,
          changeOrigin:true,
          logLevel:"debug"
        }
      },
      contentBase: "/src/",
     // contentBase:path.resolve(__dirname, 'build'),
      stats: {
        colors: true,
        hash: false,
        version: false,
        timings: false,
        assets: true,
        chunks: false,
        modules: false,
        reasons: true,
        children: false,
        warnings: true,
        publicPath: false
      }
    },

    module: {
      rules: [
        {
          test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
          loader: '@ngtools/webpack'
        },
        {
          test: /\.html$/,
          loader: "html-loader"
        },
        {
          test: /\.less$/,
          loader: "raw-loader!less-loader"
        },
        {
          test: /\.scss$/,
          use: ["raw-loader", "sass-loader"]
        },
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"]
         // use: [ "css-loader"]
        },
        {
          test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=application/font-woff"
        },
        {
          test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=application/font-woff"
        },
        {
          test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=application/octet-stream"
        },
        {
          test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader"
        },
        {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=image/svg+xml"
        }
      ]
    },

    plugins: [
      new webpack.ProgressPlugin(),

      new webpack.ContextReplacementPlugin(
        /angular(\\|\/)core(\\|\/)@angular/,
        path.join(process.cwd(), "src")
      ),

      new HtmlWebpackPlugin({
        filename: "index.html",
        template: "index.html"
      }),
      new webpack.HotModuleReplacementPlugin(),

      new CopyWebpackPlugin([
        {
          from: "favicon.ico",
          to: "favicon.ico"
        },
        {
          from: "assets",
          to: "assets"
        },
        {
          from: "data",
          to: "data"
        }
      ]),

      new AngularCompilerPlugin({
        tsConfigPath: "./tsconfig.json",
        entryModule: "./src/app/app.module.ts#AppModule",
        sourceMap: true
      }),

      new webpack.DefinePlugin({
        "ENV": environment,
        "process.env": {
          "ENV": environment,
          "NODE_ENV": environment
        },
        "CONTENT_PATH": "'/ccr2/'",
        "VERSION": JSON.stringify(require("../package.json").version),
        "USE_HASH": true
      }),

      new webpack.ProvidePlugin({
        d3: "d3"
      })
    ]
  };
}
</code>```

However when I make a code change, I see that it causes the browser to reload the page rather than a HMR.

Can anyone spot something I have missed or any ideas on how to make it work?

I can add package.json if someone wanted to see it.

答:
I had to add the following to the main.ts :

```<code>///<reference types="webpack-env" />
if (module.hot) {
  module.hot.accept();
}
</code>```

Also, something which was helpful was to use the option to 'Preserve Logs' on chrome console.

Body:
In my Angular app, I am trying to use webpack-dev-server. I have my webpack config as follows:

//"use strict";

var webpack = require("webpack");

const AngularCompilerPlugin = require("@ngtools/webpack").AngularCompilerPlugin;

const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const resolve = require('path').resolve;

module.exports = function(env) {
  var environment = "'development'";
  console.log("Env: " + environment);

  return {
    stats: "errors-only",
    devtool: "source-map",
    mode: (environment == "'production'") ? "production" : "development",

    entry: {
      "polyfills": "./polyfills.ts",
      "vendor": "./vendor.ts",
      "main": "./main.ts",
      "styles": "./styles.ts"
    },

    resolve: {
      modules: [
        "node_modules",
        path.resolve(process.cwd(), "src")
      ],
      extensions: [".ts", ".js"]
    },
    context: path.join(process.cwd(), "./src"),

    output: {
      globalObject: 'this',
      path: path.join(process.cwd(), "dist"),
      publicPath: '/',
      filename: "[name].bundle.js",
      chunkFilename: "[name].chunk.js"
    },
    target: 'web',
    devServer: {
      disableHostCheck: true,
      host: require("os").hostname().toLowerCase(),
      publicPath: "/",
      port: 3000,
      watchContentBase: true,
      watchOptions: {
        poll: true
      },
      inline: true,
      hot: true,
      historyApiFallback:  {
        index: "/index.html"
      },
      https: true,
      proxy: {
        "/api": {
          //target: "https://" + require("os").hostname().toLowerCase() + "/"
          target:'https://URL.edu/',
          secure: false,
          changeOrigin:true,
          logLevel:"debug"
        },
        "/legacy/api": {
          //target: "https://" + require("os").hostname().toLowerCase() + "/"
          target:'https://URL.edu/',
          secure: false,
          changeOrigin:true,
          logLevel:"debug"
        },
        "/auth": {
          //target: "https://" + require("os").hostname().toLowerCase() + "/"
          target:'https://URL.edu/',
          secure: false,
          changeOrigin:true,
          logLevel:"debug"
        }
      },
      contentBase: "/src/",
     // contentBase:path.resolve(__dirname, 'build'),
      stats: {
        colors: true,
        hash: false,
        version: false,
        timings: false,
        assets: true,
        chunks: false,
        modules: false,
        reasons: true,
        children: false,
        warnings: true,
        publicPath: false
      }
    },

    module: {
      rules: [
        {
          test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
          loader: '@ngtools/webpack'
        },
        {
          test: /\.html$/,
          loader: "html-loader"
        },
        {
          test: /\.less$/,
          loader: "raw-loader!less-loader"
        },
        {
          test: /\.scss$/,
          use: ["raw-loader", "sass-loader"]
        },
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"]
         // use: [ "css-loader"]
        },
        {
          test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=application/font-woff"
        },
        {
          test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=application/font-woff"
        },
        {
          test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=application/octet-stream"
        },
        {
          test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader"
        },
        {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url-loader?limit=10000&mimetype=image/svg+xml"
        }
      ]
    },

    plugins: [
      new webpack.ProgressPlugin(),

      new webpack.ContextReplacementPlugin(
        /angular(\\|\/)core(\\|\/)@angular/,
        path.join(process.cwd(), "src")
      ),

      new HtmlWebpackPlugin({
        filename: "index.html",
        template: "index.html"
      }),
      new webpack.HotModuleReplacementPlugin(),

      new CopyWebpackPlugin([
        {
          from: "favicon.ico",
          to: "favicon.ico"
        },
        {
          from: "assets",
          to: "assets"
        },
        {
          from: "data",
          to: "data"
        }
      ]),

      new AngularCompilerPlugin({
        tsConfigPath: "./tsconfig.json",
        entryModule: "./src/app/app.module.ts#AppModule",
        sourceMap: true
      }),

      new webpack.DefinePlugin({
        "ENV": environment,
        "process.env": {
          "ENV": environment,
          "NODE_ENV": environment
        },
        "CONTENT_PATH": "'/ccr2/'",
        "VERSION": JSON.stringify(require("../package.json").version),
        "USE_HASH": true
      }),

      new webpack.ProvidePlugin({
        d3: "d3"
      })
    ]
  };
}

However when I make a code change, I see that it causes the browser to reload the page rather than a HMR.

Can anyone spot something I have missed or any ideas on how to make it work?

I can add package.json if someone wanted to see it.

Body:
I had to add the following to the main.ts :

///<reference types="webpack-env" />
if (module.hot) {
  module.hot.accept();
}

Also, something which was helpful was to use the option to 'Preserve Logs' on chrome console.


问:
How to create layout background with 2 different colors in Flutter?
I am trying to make a layout as seen in the image in Flutter, but I don't get how to create a background with two colors and an overlapping button.
I don't know if there is a widget able to do this or need some code...
Any suggest or help will be great! (this was my very first post ever, sorry if there is something wrong about it!!)
Thanks.

答:
One possible approach is to use a Stack.  Set the background color to your grey (i think, color blind), add the white piece as an image positioned at the bottom.  Lastly add your button, again positioned at the bottom.

On closer inspection of your image, I now see that what I thought was an image at the bottom was actuall just a color.  All you need are two Container s and a button in a Stack.  The first Container should fill the whole space, the second Container should have a height setting (be responsive here for multiple device sizes) and lastly add your RaisedButton.


问:
Difference between Singleton and SRP(Single Responsibility Principle)
Difference between Singleton and SRP(Single Responsibility Principle)
Can you explain the difference in plain language with examples?

答:
If an object is a person,  singleton means that there is only one person of a given type in the world. You cannot find there are another person of the same type in the world.

Single Responsibility Principle (SRP) means that a person only focus on and can only do one thing. So even if you are the only the person of a given type in the world (i.e. singleton) , if you can do many things that are not related to each other , you are not SRP enough.

So you can see they are different concepts which do not related to each other. Singleton is about the quantity of certain kind of object. SRP is about what things can an object do.


问:
R exams define a question with a numerical answer with more than one possible correct answers
How can we create a numerical exercise with more than one possible correct answer in the exams package?

How does the exshuffle option works? We are trying to shuffle the solutions inside the cloze questions, but in Moodle they never appear shuffled.

答:
The exams package has no single num question that could have multiple answers. It is doable in exams2moodle(), though, in the following way: You make a cloze question consisting of a verbatim item. And for this you provide the explicit :NUMERICAL: code that treats multiple values as fully correct. The strategy is essentially the same as for partially correct answers, except that there are several fully correct answers, see: how to create a num question for Moodle with R/exams with partially correct answers

Outside of Moodle you could consider alternative ways of asking the question, e.g., via mchoice or via cloze with several num items. For example, if you ask for the prime numbers between 80 and 100, then 83, 89, 97 are correct answers. Either you could provide an mchoice list of, say, five numbers and ask: Which of these are prime numbers? Or you could ask three num items within a cloze: Which is the smallest/medium/largest prime number between 80 and 100?

As for the exshuffle: This only pertains to the answer options within schoice or mchoice questions (either standalone or as sub-questions in a cloze exercise). If you need more details, please consider asking another question.


答:
Assuming that guild is the main dictionary in which a key called members exists with a list of "sub dictionaries", you can try

```<code>uuid = list()
for x in guild['members']:
    uuid.append(x['uuid'])
</code>```

uuid now has all the uuids

Title: Access one item from a dict and store it into a variable

Body:
Assuming that guild is the main dictionary in which a key called members exists with a list of "sub dictionaries", you can try

uuid = list()
for x in guild['members']:
    uuid.append(x['uuid'])

uuid now has all the uuids


问:
How can I detect the element(s) at an arbitrary mouse position (x,y)?

Possible Duplicate:

Get element at specified position - JavaScript

How can I detect the elements at an arbitrary mouse position (x,y)?

I am using mouseenter/mouseleave to highlight hovered items. Unfortunately neither of these fire when the mouse moves implicitly and this leads to the wrong item being highlighted. An example of moving the mouse implicitly would be scrolling the page with arrow keys or track pad.

You can see a working demo with comments here: http://jsfiddle.net/bkG2K/6/

My idea for a workaround is to check the mouse's position every so often, or just after scrolling if possible, and update the hover state based on the current mouse co-ordinates. But I'm not sure how I can find DOM elements given an X,Y.

Ideas? If you have a better solution to the root problem, feel free!

答:
I don't know if internal implementations differ, but for what you are trying to achieve the intended method would be .hover(...) which takes two callbacks to execute in each state-change.

Alternatively, you could setInterval() and simulate .mousemove() event at the cursor's position (Though you should do a broswer check and only use it in the problematic browser since this is kind of a hack, and as few as possible people should be exposed to it)


问:
Error on async job
I'm trying to create an async task that will not block the request. The user make the request, the task will start, and the controller will render "Job is running...", this is for avoid the request being blocked waiting the task to complete.
Once the task is finish, it will execute the onComplete and do something with the result of that task (for example call a service that will send a mail to an user)

```<code>| Error 2014-09-16 17:38:56,721 [Actor Thread 3] ERROR gpars.LoggingPoolFactory  - Async execution error: null
</code>```

The code is the following:

```<code>package testasync

import static grails.async.Promises.*

class TestController {

  def index() {
    //Create the job
    def job1 = task {
        println 'Waiting 10 seconds'
        Thread.sleep(10000)
        return 'Im done'
    }
    //On error
    job1.onError { Throwable err ->
        println "An error occured ${err.message}"
    }
    //On success
    job1.onComplete { result ->
        println "Promise returned $result"
    }
    render 'Job is running...'
  }
</code>```

Complete stacktrace:

```<code>| Error 2014-09-17 10:35:24,522 [Actor Thread 3] ERROR gpars.LoggingPoolFactory  -  Async execution error: null
Message: null
   Line | Method
 ->>   72 | doCall    in org.grails.async.factory.gpars.GparsPromise$_onError_closure2
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  |     62 | run       in groovyx.gpars.dataflow.DataCallback$1
  |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
  |    615 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
  ^    745 | run . . . in java.lang.Thread
</code>```

答:
In my case, just returning a promise worked.

MyService.groovy

```<code>import static grails.async.Promises.*
def getAsync(){
    Promise p = task {
    //Long running task
            println 'John doe started digging a hole here.'
            Thread.sleep(2000)
            println 'John doe working......'
            return 'Kudos John Doe!'
        }
        p.onError { Throwable err ->
            println "Poor John"+err
        }
        p.onComplete { result ->
            println "Congrats." +result
        }

        println 'John Doe is doing something here.'
        return p
}
</code>```

Title: Error on async job

Body:
I'm trying to create an async task that will not block the request. The user make the request, the task will start, and the controller will render "Job is running...", this is for avoid the request being blocked waiting the task to complete.
Once the task is finish, it will execute the onComplete and do something with the result of that task (for example call a service that will send a mail to an user)

| Error 2014-09-16 17:38:56,721 [Actor Thread 3] ERROR gpars.LoggingPoolFactory  - Async execution error: null

The code is the following:

package testasync

import static grails.async.Promises.*

class TestController {

  def index() {
    //Create the job
    def job1 = task {
        println 'Waiting 10 seconds'
        Thread.sleep(10000)
        return 'Im done'
    }
    //On error
    job1.onError { Throwable err ->
        println "An error occured ${err.message}"
    }
    //On success
    job1.onComplete { result ->
        println "Promise returned $result"
    }
    render 'Job is running...'
  }

Complete stacktrace:

| Error 2014-09-17 10:35:24,522 [Actor Thread 3] ERROR gpars.LoggingPoolFactory  -  Async execution error: null
Message: null
   Line | Method
 ->>   72 | doCall    in org.grails.async.factory.gpars.GparsPromise$_onError_closure2
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  |     62 | run       in groovyx.gpars.dataflow.DataCallback$1
  |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
  |    615 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
  ^    745 | run . . . in java.lang.Thread

Body:
In my case, just returning a promise worked.

MyService.groovy

import static grails.async.Promises.*
def getAsync(){
    Promise p = task {
    //Long running task
            println 'John doe started digging a hole here.'
            Thread.sleep(2000)
            println 'John doe working......'
            return 'Kudos John Doe!'
        }
        p.onError { Throwable err ->
            println "Poor John"+err
        }
        p.onComplete { result ->
            println "Congrats." +result
        }

        println 'John Doe is doing something here.'
        return p
}


问:
Python3: trying to compare values in csv with threshold
```<code>import csv
with open('C:/Users/adria/Desktop/breastCancerDataReducedDimensions.csv', mode = 'r') as file:
    reader = csv.reader(file)

    for row in reader:
        next(reader)
        if row[2] >= 13:
            print(row[2])
</code>```

I am trying to compare the values in this particular row to a threshold value, but i am getting an operand error saying that I cannot compare a string to an integer. I believe the header in the first row is causing my issue but I'm unsure how to fix it.

答: if int(row[2]) >= 13: should do it, since the cell in the csv is prob interpreted as string

Body:
import csv
with open('C:/Users/adria/Desktop/breastCancerDataReducedDimensions.csv', mode = 'r') as file:
    reader = csv.reader(file)

    for row in reader:
        next(reader)
        if row[2] >= 13:
            print(row[2])

I am trying to compare the values in this particular row to a threshold value, but i am getting an operand error saying that I cannot compare a string to an integer. I believe the header in the first row is causing my issue but I'm unsure how to fix it.


问:
Express Throws TypeError: Cannot read property 'app' of undefined
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:

```<code>TypeError: Cannot read property 'app' of undefined
    at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
    at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
  <rejected> TypeError: Cannot read property 'app' of undefined
      at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
      at process._tickCallback (internal/process/next_tick.js:68:7) }
</code>```

All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:

```<code>    const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet'),
        app = express();
    app.use(helmet());
    app.use(cors());
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.set('trust proxy', true);

    //map router files to respective urls
    //these are stored in a directory and set above, these contain all of the handlers for each of my routes
    app.use('/user', user);

    //set port and listen on it
    app.listen(5000, () => console.log("Server running on port 5000"));
</code>```

If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.

EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.

答:
//Worked fine for me. removed ur local import. This runs fine.</p>

```<code>const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser')
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
</code>```

Body:
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:

TypeError: Cannot read property 'app' of undefined
    at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
    at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
  <rejected> TypeError: Cannot read property 'app' of undefined
      at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
      at process._tickCallback (internal/process/next_tick.js:68:7) }

All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:

    const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet'),
        app = express();
    app.use(helmet());
    app.use(cors());
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.set('trust proxy', true);

    //map router files to respective urls
    //these are stored in a directory and set above, these contain all of the handlers for each of my routes
    app.use('/user', user);

    //set port and listen on it
    app.listen(5000, () => console.log("Server running on port 5000"));

If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.

EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.

Body:
//Worked fine for me. removed ur local import. This runs fine.

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser')
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));


问:
how to print the dynamic array books * arr
how to print the dynamic array books * arr and do i have to add something more

how to print the dynamic array books * arr

how to print the dynamic array books * arr

```<code>  typedef struct Book
    {
        char name[32];
        char genre[32];
        char author[32];
        int numOfPages;
        int price;
    }books;

struct Library
{
    char name[32];
    books* arr;
        int numOfBooks;
    };

    int main()
    {

    struct Book book1;

    strcpy(book1.name,"Learn C.");
    strcpy(book1.genre,"Fantastic");
    strcpy(book1.author,"Dont know who");
    kniga1.numOfPages=666;
    kniga1.price=100;

    books* arr=(books*)malloc(sizeof(books));

    struct Library library1;
    strcpy(library1.name,"Biblioteka1");
    library1.numOfBooks=1;
</code>```

答:
regarding your question: *how to print the dynamic array books * ar*...

assuming you have created such an array (which the posted code has not done.

```<code>for( size_t i = 0; i < library1.numOfBooks; i++ )
{
    printf( "%s  ", library1.arr[i]->name );
    printf( "%s  ", library1.arr[i]->genre );
    printf( "%s  ", library1.arr[i]->author );
    printf( "%d  ", library1.arr[i]->numOfPages );
    printf( "%d\n", library1.arr[i]->price );
}
</code>```

Body:
how to print the dynamic array books * arr and do i have to add something more

how to print the dynamic array books * arr

how to print the dynamic array books * arr

  typedef struct Book
    {
        char name[32];
        char genre[32];
        char author[32];
        int numOfPages;
        int price;
    }books;

struct Library
{
    char name[32];
    books* arr;
        int numOfBooks;
    };

    int main()
    {

    struct Book book1;

    strcpy(book1.name,"Learn C.");
    strcpy(book1.genre,"Fantastic");
    strcpy(book1.author,"Dont know who");
    kniga1.numOfPages=666;
    kniga1.price=100;

    books* arr=(books*)malloc(sizeof(books));

    struct Library library1;
    strcpy(library1.name,"Biblioteka1");
    library1.numOfBooks=1;

Body:
regarding your question: *how to print the dynamic array books * ar*...

assuming you have created such an array (which the posted code has not done.

for( size_t i = 0; i < library1.numOfBooks; i++ )
{
    printf( "%s  ", library1.arr[i]->name );
    printf( "%s  ", library1.arr[i]->genre );
    printf( "%s  ", library1.arr[i]->author );
    printf( "%d  ", library1.arr[i]->numOfPages );
    printf( "%d\n", library1.arr[i]->price );
}


问:
How to fix typescript error (Readonly<{}> & Readonly<{ children?: ReactNode; }>)?
How to fix typescript error?

I cloned the application from the working git repository, launched and received the error:

Property 'language' does not exist on type 'Readonly<{}> & Readonly<{
  children?: ReactNode; }>'.  TS2339

```<code>    <div className="login-block__form__head__text">
      {// @ts-ignore
      this.props.language === 'EN'// err
        ? 'Login'
        : 'LOGIN'}{' '}
    </div>
</code>```

Unfortunately, I do not know the typescript, so I have to ask for help.

答:
in this case, you didn't define props types.

```<code>interface PropType {
  language: string,
}

export default class ComponentName extends React.Component<PropType> {
...
}
</code>```

if you want to learn more about typescript, the following links would be helpful.

typescript in 5min

Body:
How to fix typescript error?

I cloned the application from the working git repository, launched and received the error:

Property 'language' does not exist on type 'Readonly<{}> & Readonly<{
  children?: ReactNode; }>'.  TS2339

      {// @ts-ignore
      this.props.language === 'EN'// err
        ? 'Login'
        : 'LOGIN'}{' '}

Unfortunately, I do not know the typescript, so I have to ask for help.

Body:
in this case, you didn't define props types.

interface PropType {
  language: string,
}

export default class ComponentName extends React.Component<PropType> {
...
}

if you want to learn more about typescript, the following links would be helpful.

typescript in 5min