问:
Is there way to commit based on last modification time of a project folder/file?
I am trying to add an existing C project to git. However, the last time I worked on this project was around a year back. If I initialize the existing project repository using the following,

git init && git add . && git commit -m "Hello World"

the commit date will be set to the current date.

Is it possible to set the commit date (the initial commit) based on the last modification time of the project folder/files ?

Update: Included previous updates as part of the answer to the first part.

答:
One way is to use --date when you commit, for example:
git commit -m "Hello World" --date "2005-04-07T22:13:13"


来源: stackexchange

问:
How to update Android Textview in an on going loop?
I'm using Kotlin. I have a loop that will continue going. But for some reason, I am unable to update the text view. Here is my simplified example.</p>

```<code>var i = 0
while (!Thread.currentThread().isInterrupted) {
    setString(i.toString())
    i++
    Log.i("Loging value of i === ", i.toString())
}

private fun setString (string : String) {
    tempText.text = string
}
</code>```

答:
What happened is because you are calling the UI updating inside a different Thread other than the main/UI Thread, your code can't reach the Views on the UI Thread.

Call the code that updates something on the UI inside a runOnUiThread like https://stackoverflow.com/a/11140429/10464730 (just copy the runOnUiThread part).

Or do a .post on the TextView like this https://stackoverflow.com/a/9884344/10464730. Most of the time I use runOnUiThread first. If doesn't work, that's when I use .post.

Sorry the code I posted are Java but I think you could look up the equivalent of it on Kotlin.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Kotlin. I have a loop that will continue going. But for some reason, I am unable to update the text view. Here is my simplified example.

var i = 0
while (!Thread.currentThread().isInterrupted) {
    setString(i.toString())
    i++
    Log.i("Loging value of i === ", i.toString())
}

private fun setString (string : String) {
    tempText.text = string
}


问:
Django Array contains a field
I am using Django, with mongoengine. I have a model Classes with an inscriptions list, And I want to get the docs that have an id in that list.

classes = Classes.objects.filter(inscriptions__contains=request.data['inscription'])

答:
Here's a general explanation of querying ArrayField membership:

Per the Django ArrayField docs, the __contains operator checks if a provided array is a subset of the values in the ArrayField.

So, to filter on whether an ArrayField contains the value "foo", you pass in a length 1 array containing the value you're looking for, like this:

```<code># matches rows where myarrayfield is something like ['foo','bar']
Customer.objects.filter(myarrayfield__contains=['foo'])
</code>```

The Django ORM produces the @> postgres operator, as you can see by printing the query:

```<code>print Customer.objects.filter(myarrayfield__contains=['foo']).only('pk').query
>>> SELECT "website_customer"."id" FROM "website_customer" WHERE "website_customer"."myarrayfield_" @> ['foo']::varchar(100)[]
</code>```

If you provide something other than an array, you'll get a cryptic error like DataError: malformed array literal: "foo"   DETAIL:  Array value must start with "{" or dimension information.

Title: Django Array contains a field

Body:
Here's a general explanation of querying ArrayField membership:

Per the Django ArrayField docs, the __contains operator checks if a provided array is a subset of the values in the ArrayField.

So, to filter on whether an ArrayField contains the value "foo", you pass in a length 1 array containing the value you're looking for, like this:

# matches rows where myarrayfield is something like ['foo','bar']
Customer.objects.filter(myarrayfield__contains=['foo'])

The Django ORM produces the @> postgres operator, as you can see by printing the query:

print Customer.objects.filter(myarrayfield__contains=['foo']).only('pk').query
>>> SELECT "website_customer"."id" FROM "website_customer" WHERE "website_customer"."myarrayfield_" @> ['foo']::varchar(100)[]

If you provide something other than an array, you'll get a cryptic error like DataError: malformed array literal: "foo"   DETAIL:  Array value must start with "{" or dimension information.


问:
How do I program tests in R so that they print nicely?
Statistical tests in R generate lists, but then when you call the test, the printing of these lists gives a special user-friendly structure to assist the reader.  To see what I'm talking about, consider an example where you use the t.test function in the stats package.

```<code>#Run a T-test on some example data
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50);
TEST <- stats::t.test(X,Y);

#Show structure of the TEST object
str(TEST);
List of 9
 $ statistic  : Named num -0.134
  ..- attr(*, "names")= chr "t"
 $ parameter  : Named num 10.2
  ..- attr(*, "names")= chr "df"
 $ p.value    : num 0.896
 $ conf.int   : num [1:2] -12.3 10.9
  ..- attr(*, "conf.level")= num 0.95
 $ estimate   : Named num [1:2] 32.8 33.5
  ..- attr(*, "names")= chr [1:2] "mean of x" "mean of y"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "difference in means"
 $ alternative: chr "two.sided"
 $ method     : chr "Welch Two Sample t-test"
 $ data.name  : chr "X and Y"
 - attr(*, "class")= chr "htest"
</code>```

This object is a list with nine elements, some of which are named via attributes.  However, when I print the TEST object, the returned information is structured in a different way than the standard printing of a list.

```<code>#Print the TEST object
TEST;

        Welch Two Sample t-test

data:  X and Y
t = -0.13444, df = 10.204, p-value = 0.8957
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.27046  10.87046
sample estimates:
mean of x mean of y
     32.8      33.5
</code>```

As you can see, this printed output is much more user-friendly than the standard printing for a list.  I would like to be able to program statistical tests in R which generate a list of outputs similar to the above, but which print in this user-friendly way.

My Questions: Why does R print the output of the list TEST in this special way?  If I create a list of outputs of a statistical test (e.g., like the above), how can I set the object to print in this way?

答:
Use one of the methods below that meets your needs the best.

```<code>X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39)
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50)
TEST <- stats::t.test(X,Y)

#default; printing data of htest class
print(TEST)

#printing every element of the list
lapply(TEST, print)
print.listof(TEST)

#printing the results as a dataframe
broom::tidy(TEST) #output of this one is included just for illustration

    # A tibble: 1 x 10
  estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method                  alternative
     <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>
1     -0.7      32.8      33.5    -0.134   0.896      10.2    -12.3      10.9 Welch Two Sample t-test two.sided
</code>```

To address OP's follow-up question:

"Each" class of data has a method of printing. As I outlined in my answer, print function looks at TEST and as it is class of htest it uses print.htest.

class(TEST)
# [1] "htest"

head(methods(print))
# [1] "print.acf"         "print.AES"         "print.all_vars"    "print.anova"
# [5] "print.anova.lme"   "print.ansi_string"
```

In my freshly opened R session, I have 185 different methods. As you loads libraries, the number will go higher.

If you want to dig deeper, then you need to look at the source code of print which can be found here: R source code on GitHub

Body:
Statistical tests in R generate lists, but then when you call the test, the printing of these lists gives a special user-friendly structure to assist the reader.  To see what I'm talking about, consider an example where you use the t.test function in the stats package.

#Run a T-test on some example data
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50);
TEST <- stats::t.test(X,Y);

#Show structure of the TEST object
str(TEST);
List of 9
 $ statistic  : Named num -0.134
  ..- attr(*, "names")= chr "t"
 $ parameter  : Named num 10.2
  ..- attr(*, "names")= chr "df"
 $ p.value    : num 0.896
 $ conf.int   : num [1:2] -12.3 10.9
  ..- attr(*, "conf.level")= num 0.95
 $ estimate   : Named num [1:2] 32.8 33.5
  ..- attr(*, "names")= chr [1:2] "mean of x" "mean of y"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "difference in means"
 $ alternative: chr "two.sided"
 $ method     : chr "Welch Two Sample t-test"
 $ data.name  : chr "X and Y"
 - attr(*, "class")= chr "htest"

This object is a list with nine elements, some of which are named via attributes.  However, when I print the TEST object, the returned information is structured in a different way than the standard printing of a list.

#Print the TEST object
TEST;

        Welch Two Sample t-test

data:  X and Y
t = -0.13444, df = 10.204, p-value = 0.8957
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.27046  10.87046
sample estimates:
mean of x mean of y
     32.8      33.5

As you can see, this printed output is much more user-friendly than the standard printing for a list.  I would like to be able to program statistical tests in R which generate a list of outputs similar to the above, but which print in this user-friendly way.

My Questions: Why does R print the output of the list TEST in this special way?  If I create a list of outputs of a statistical test (e.g., like the above), how can I set the object to print in this way?

Body:
Use one of the methods below that meets your needs the best.

X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39)
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50)
TEST <- stats::t.test(X,Y)

#default; printing data of htest class
print(TEST)

#printing every element of the list
lapply(TEST, print)
print.listof(TEST)

#printing the results as a dataframe
broom::tidy(TEST) #output of this one is included just for illustration

    # A tibble: 1 x 10
  estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method                  alternative
     <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>
1     -0.7      32.8      33.5    -0.134   0.896      10.2    -12.3      10.9 Welch Two Sample t-test two.sided

To address OP's follow-up question:

"Each" class of data has a method of printing. As I outlined in my answer, print function looks at TEST and as it is class of htest it uses print.htest.

class(TEST)
# [1] "htest"

head(methods(print))
# [1] "print.acf"         "print.AES"         "print.all_vars"    "print.anova"
# [5] "print.anova.lme"   "print.ansi_string"

In my freshly opened R session, I have 185 different methods. As you loads libraries, the number will go higher.

If you want to dig deeper, then you need to look at the source code of print which can be found here: R source code on GitHub


问:
How to enable .NET Core 3 preview SDK in VS2019?
I wanted to try out Blazor. I've installed .NET Core 3.0 preview 5 SDK, Blazor VS extension to enable project templates. I can create Blazor project, but I can't run it - I constantly get this notification.

In some tutorials I see that there should be a checkbox in VS options - to enable using of preview SDKs.

But it's not there in VS2019! Version is 16.1.1

答: If you are using the preview channel for vs 2019 then it is on by default:


问:
How to resume downloading image when interrupted?
How can I resume pull when disconnected? The pull process always start from the beginning every time I run docker pull some-image again after disconnected. My connection is so unstable that even downloading just a 100MB image take so long and almost fails every time. So, it is almost impossible for me to pull a bigger image. So, how can I resume the pull process?

答:
Docker's code isn't as updated as the moby in development repository on github.  People have been having issues for several years relating to this.  I had tried to manually use several patches which aren't in the upstream yet, and none worked decent.

The github repository for moby (docker's development repo) has a script called download-frozen-image-v2.sh.  This script uses bash, curl, and other things like JSON interpreters via command line.  It will retrieve a docker token, and then download all of the layers to a local directory.  You can then use 'docker load' to insert into your local docker installation.

It does not do well with resume though.  It had some comment in the script relating to 'curl -C' isn't working.  I had tracked down, and fixed this problem.  I made a modification which uses a ".headers" file to retrieve initially, which has always returned a 302 while I've been monitoring, and then retrieves the final using curl (+ resume support) to the layer tar file.  It also has to loop on the calling function which retrieves a valid token which unfortunately only lasts about 30 minutes.

It will loop this process until it receives a 416 stating that there is no resume possible since it's ranges have been fulfilled.  It also verifies the size against a curl header retrieval.  I have been able to retrieve all images necessary using this modified script.  Docker has many more layers relating to retrieval, and has remote control processes (Docker client) which make it more difficult to control, and they viewed this issue as only affecting some people on bad connections.

I hope this script can help you as much as it has helped me:

Changes:
fetch_blob function uses a temporary file for its first connection.  It then retrieves 30x HTTP redirect from this.  It attempts a header retrieval on the final url and checks whether the local copy has the full file.  Otherwise, it will begin a resume curl operation.  The calling function which passes it a valid token has a loop surrounding retrieving a token, and fetch_blob which ensures the full file is obtained.

The only other variation is a bandwidth limit variable which can be set at the top, or via "BW:10" command line parameter.  I needed this to allow my connection to be viable for other operations.

Click here for the modified script.

In the future it would be nice if docker's internal client performed resuming properly.  Increasing the amount of time for the token's validation would help tremendously..

Brief views of change code:

```<code>#loop until FULL_FILE is set in fetch_blob.. this is for bad/slow connections
            while [ "$FULL_FILE" != "1" ];do
                local token="$(curl -fsSL "$authBase/token?service=$authService&scope=repository:$image:pull" | jq --raw-output '.token')"
                fetch_blob "$token" "$image" "$layerDigest" "$dir/$layerTar" --progress
                sleep 1
            done
</code>```

Another section from fetch_blob:

```<code>while :; do
            #if the file already exists.. we will be resuming..
            if [ -f "$targetFile" ];then
                #getting current size of file we are resuming
                CUR=`stat --printf="%s" $targetFile`
                #use curl to get headers to find content-length of the full file
                LEN=`curl -I -fL "${curlArgs[@]}" "$blobRedirect"|grep content-length|cut -d" " -f2`

                #if we already have the entire file... lets stop curl from erroring with 416
                if [ "$CUR" == "${LEN//[!0-9]/}" ]; then
                    FULL_FILE=1
                    break
                fi
            fi

            HTTP_CODE=`curl -w %{http_code} -C - --tr-encoding --compressed --progress-bar -fL "${curlArgs[@]}" "$blobRedirect" -o "$targetFile"`
            if [ "$HTTP_CODE" == "403" ]; then
                #token expired so the server stopped allowing us to resume, lets return without setting FULL_FILE and itll restart this func w new token
                FULL_FILE=0
                break
            fi

            if [ "$HTTP_CODE" == "416" ]; then
                FULL_FILE=1
                break
            fi

            sleep 1
        done
</code>```

Body:
Docker's code isn't as updated as the moby in development repository on github.  People have been having issues for several years relating to this.  I had tried to manually use several patches which aren't in the upstream yet, and none worked decent.

The github repository for moby (docker's development repo) has a script called download-frozen-image-v2.sh.  This script uses bash, curl, and other things like JSON interpreters via command line.  It will retrieve a docker token, and then download all of the layers to a local directory.  You can then use 'docker load' to insert into your local docker installation.

It does not do well with resume though.  It had some comment in the script relating to 'curl -C' isn't working.  I had tracked down, and fixed this problem.  I made a modification which uses a ".headers" file to retrieve initially, which has always returned a 302 while I've been monitoring, and then retrieves the final using curl (+ resume support) to the layer tar file.  It also has to loop on the calling function which retrieves a valid token which unfortunately only lasts about 30 minutes.

It will loop this process until it receives a 416 stating that there is no resume possible since it's ranges have been fulfilled.  It also verifies the size against a curl header retrieval.  I have been able to retrieve all images necessary using this modified script.  Docker has many more layers relating to retrieval, and has remote control processes (Docker client) which make it more difficult to control, and they viewed this issue as only affecting some people on bad connections.

I hope this script can help you as much as it has helped me:

Changes:
fetch_blob function uses a temporary file for its first connection.  It then retrieves 30x HTTP redirect from this.  It attempts a header retrieval on the final url and checks whether the local copy has the full file.  Otherwise, it will begin a resume curl operation.  The calling function which passes it a valid token has a loop surrounding retrieving a token, and fetch_blob which ensures the full file is obtained.

The only other variation is a bandwidth limit variable which can be set at the top, or via "BW:10" command line parameter.  I needed this to allow my connection to be viable for other operations.

Click here for the modified script.

In the future it would be nice if docker's internal client performed resuming properly.  Increasing the amount of time for the token's validation would help tremendously..

Brief views of change code:

#loop until FULL_FILE is set in fetch_blob.. this is for bad/slow connections
            while [ "$FULL_FILE" != "1" ];do
                local token="$(curl -fsSL "$authBase/token?service=$authService&scope=repository:$image:pull" | jq --raw-output '.token')"
                fetch_blob "$token" "$image" "$layerDigest" "$dir/$layerTar" --progress
                sleep 1
            done

Another section from fetch_blob:

while :; do
            #if the file already exists.. we will be resuming..
            if [ -f "$targetFile" ];then
                #getting current size of file we are resuming
                CUR=`stat --printf="%s" $targetFile`
                #use curl to get headers to find content-length of the full file
                LEN=`curl -I -fL "${curlArgs[@]}" "$blobRedirect"|grep content-length|cut -d" " -f2`

                #if we already have the entire file... lets stop curl from erroring with 416
                if [ "$CUR" == "${LEN//[!0-9]/}" ]; then
                    FULL_FILE=1
                    break
                fi
            fi

            HTTP_CODE=`curl -w %{http_code} -C - --tr-encoding --compressed --progress-bar -fL "${curlArgs[@]}" "$blobRedirect" -o "$targetFile"`
            if [ "$HTTP_CODE" == "403" ]; then
                #token expired so the server stopped allowing us to resume, lets return without setting FULL_FILE and itll restart this func w new token
                FULL_FILE=0
                break
            fi

            if [ "$HTTP_CODE" == "416" ]; then
                FULL_FILE=1
                break
            fi

            sleep 1
        done


问:
When click, different content will shows up (content from database)
I'm creating a list of subjects when click it'll shows all the teachers that are teaching the subject. The subjects and teachers data are from MySQL database.

I've tried using javascript to do the "on click" function and php to retrieve the data from database but its not working.

```<code>        <?php do { ?>
        <?php do { ?>
        <script>
function showResult(b) {
  var res = document.getElementById('stafflist');
  if (b.classList.contains(<?php $row_Recordset1['subject'] ?>) = <?php $row_Recordset2['subject'] ?>) {
    res.innerHTML = <?php echo $row_Recordset2['StaffName'] ?>}
</script>

<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)); ?>

<div class="subjectlist">
  <p onclick="showResult(this)" class="<?php $row_Recordset2['subject'] ?>"><?php echo $row_Recordset2['subject']; ?></p>
</div>
<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset1)); ?>

<p id="stafflist"></p>
</code>```

答:
You need to call a JavaScript function on the "onclick" event that will use an AJAX call to populate the teachers that are teaching that subject.

Your PHP file should return a json with the list of teachers and you will use this json to populate the list.

Take this as an example:

```<code>function showResult(subject_id) {

    var url = "getResults.php";

    $.ajax({
        type: "POST",
        url: url,
        data: {subject_id:subject_id},
        dataType: 'JSON',
        beforeSend: function() {
            //You can show a preloader here
        }
    }).done(function(data) {
        //Hide the preloader
        //Populate the list
    }).fail(function() {
        //Hide the preloader
        //Show an error message
    });
}
</code>```

Body:
I'm creating a list of subjects when click it'll shows all the teachers that are teaching the subject. The subjects and teachers data are from MySQL database.

I've tried using javascript to do the "on click" function and php to retrieve the data from database but its not working.

        <?php do { ?>
        <?php do { ?>

<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)); ?>

  <p onclick="showResult(this)" class="<?php $row_Recordset2['subject'] ?>"><?php echo $row_Recordset2['subject']; ?>

<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset1)); ?>

Body:
You need to call a JavaScript function on the "onclick" event that will use an AJAX call to populate the teachers that are teaching that subject.

Your PHP file should return a json with the list of teachers and you will use this json to populate the list.

Take this as an example:

function showResult(subject_id) {

    var url = "getResults.php";

    $.ajax({
        type: "POST",
        url: url,
        data: {subject_id:subject_id},
        dataType: 'JSON',
        beforeSend: function() {
            //You can show a preloader here
        }
    }).done(function(data) {
        //Hide the preloader
        //Populate the list
    }).fail(function() {
        //Hide the preloader
        //Show an error message
    });
}


问:
How to load H20 trained model in Java UDF
I am trying to load trained xgboost model to be used in custom UDF written in Java. File is in zip format and stored in hdfs.

I have tried to read it using Path class but it's not working.

```<code>import org.apache.hadoop.fs.Path;

public EasyPredictModelWrapper loadModel(String xgBoostModelFile) {
        if (model == null) {

            synchronized (_lockObject) {
                if (model == null) {
                    log.info("Model has not been loaded, loading ...");
                    try {
                        Path path = new Path(xgBoostModelFile);
                        model = new EasyPredictModelWrapper(MojoModel.load(path)); // Doesn't compile since MojoModel only takes string as an input.
                    } catch (IOException e) {
                        log.error("Got an exception while trying to load xgBoostModel \n", e);
                    }
                }
            }
        }
        return model;
    }
</code>```

I Want to successfully load model.zip

答:
Got answer in H20 slack community.</p>

```<code>FileSystem fs = FileSystem.get(new Configuration());
Path path = new Path(xgBoostModelFile);
FSDataInputStream inputStream = fs.open(path);
MojoReaderBackend mojoReaderBackend = MojoReaderBackendFactory.createReaderBackend(inputStream,CachingStrategy.MEMORY);
model = new EasyPredictModelWrapper(MojoModel.load(mojoReaderBackend));
</code>```

Body:
I am trying to load trained xgboost model to be used in custom UDF written in Java. File is in zip format and stored in hdfs.

I have tried to read it using Path class but it's not working.

import org.apache.hadoop.fs.Path;

public EasyPredictModelWrapper loadModel(String xgBoostModelFile) {
        if (model == null) {

            synchronized (_lockObject) {
                if (model == null) {
                    log.info("Model has not been loaded, loading ...");
                    try {
                        Path path = new Path(xgBoostModelFile);
                        model = new EasyPredictModelWrapper(MojoModel.load(path)); // Doesn't compile since MojoModel only takes string as an input.
                    } catch (IOException e) {
                        log.error("Got an exception while trying to load xgBoostModel \n", e);
                    }
                }
            }
        }
        return model;
    }

I Want to successfully load model.zip

Body:
Got answer in H20 slack community.

FileSystem fs = FileSystem.get(new Configuration());
Path path = new Path(xgBoostModelFile);
FSDataInputStream inputStream = fs.open(path);
MojoReaderBackend mojoReaderBackend = MojoReaderBackendFactory.createReaderBackend(inputStream,CachingStrategy.MEMORY);
model = new EasyPredictModelWrapper(MojoModel.load(mojoReaderBackend));


问:
Azure microsoft graph api invited user not able to invite user
I am working on an app where i have some users on azure ad and some users need to be externals(ex:gmail).Iam using microsoft graph api to invite users from external. All these users are have user administrator role in AD.
I am able to invite external user successfully with internal user credentials. But when i try to invite external user again with the invited user details i am getting
error :
{
    "error": {
        "code": "BadRequest",
        "message": "Current authenticated context is not valid for this request. This occurs when a request is made to an endpoint that requires user sign-in. For example, /me requires a signed-in user.  Acquire a token on behalf of a user to make requests to these endpoints.  Use the OAuth 2.0 authorization code flow for mobile and native apps and the OAuth 2.0 implicit flow for single-page web apps.",
        "innerError": {
            "request-id": "2d6d6c29-4f13-4eeb-bae4-2d6cc0d2de00",
            "date": "2019-05-27T13:22:20"
        }
    }
}

I am using postman to check these apis.I have attached the request details to get the jwt token.Can you please help here. Let me know if you need more info.

答:
I can reproduce your issue if I add Google as an identity provider for B2B guest users.

I have also tried with Graph explorer. We can not even use this tool since the google account is not a microsoft account.

Maybe the only way to invite another guest user with the invited google account(isn't a microsoft account) is using Azure portal.

Google guest users must sign in using a link that includes the tenant context (for example, https://myapps.microsoft.com/?tenantid=<tenant id> or https://portal.azure.com/<tenant id>


问:
Why is 'error: unbound symbol' returned why I run my array comparison algorithm?
Given a list of lists in which the first element of the list is a name and the rest of the elements are integers, I am trying to build an algorithm that compares the similarity of two sub-lists by summing the difference between the elements at each position in the list.  I am using a let statement in this algorithm, and when I try to run it, the following error is returned:

Error: execute: unbound symbol: "arr2" [similarity-arrays, (anon)]

Why does this happen?

Code:

(define (get-list name arr)
  (if (eq? name (car (car arr)))
      (cdr (car arr))
      (get-list name (cdr arr))))
(define (similarity-arrays name1 name2 arrs result)
  (let ((arr1 (get-list name1 arrs))
       ((arr2 (get-list name2 arrs))))
        (if (= (length arr1)(length arr2))
          (let ((x1 (car arr1))
                (x2 (car arr2)))
                  (if (= 0 (length arr1))
                    result
                    (similarity-arrays
                      (cdr arr1)
                      (cdr arr2)
                      (+ result (- (car arr1)(car arr2))))))
          #f)))
(define dust
  (list (list 'akko 11 3 7 5 4 1 9 8 10 6 2)
        (list 'Alex 9 7 11 3 6 1 5 4 10 2 8)
        (list 'Aron 11 4 1 2 6 3 7 9 8 10 5)
        (list 'carter 7 3 8 2 5 4 11 9 10 6 1)
        (list 'Connery 10 2 6 4 5 1 7 3 9 11 8)
        (list 'Embryo 11 8 9 6 7 4 2 3 1 10 5)
        (list 'Jaycee 9 1 11 7 10 8 4 2 5 6 3)
        (list 'jeeelm 11 8 5 2 1 6 7 3 9 10 4)
        (list 'Jodast 10 7 4 6 5 1 11 9 8 3 2)
        (list 'KingDolphin 11 4 7 2 6 3 5 9 8 10 1)
        (list 'Knowledge 11 8 2 9 3 1 5 6 4 10 7)
        (list 'ruben 11 1 6 4 7 3 9 5 8 10 2)
        (list 'SickLizard 11 6 7 2 8 3 9 10 5 4 1)
        (list 'XIN 11 3 4 1 8 5 7 9 6 10 2)
        (list 'ZIPF 10 7 11 5 9 3 6 2 4 8 1)))

(similarity-arrays 'Jodast 'Akko dust 0)
```

答:
The proper syntax of let is:

(let ([binding expression]
      [binding2 expression2]
      ...)
  body ...)
```

<p>If you had formatted it correctly you would have seen that instead of <code>binding2</code> you have <code>(arr2 (get-list name2 arrs))</code> with no expression. The error message refers to that no binding <code>arr2</code> exists. So I'll format your code properly:</p>

<pre class="lang-scm prettyprint-override"><code>(define (similarity-arrays name1 name2 arrs result)
  (let ([arr1 (get-list name1 arrs)]
        [(arr2 (get-list name2 arrs))])
    (if (= (length arr1)(length arr2))
        (let ([x1 (car arr1)]
              [x2 (car arr2)])
          (if (= 0 (length arr1))
              result
              (similarity-arrays
               (cdr arr1)
               (cdr arr2)
               (+ result (- (car arr1)(car arr2))))))
        #f)))
</code>```

Now from R6RS there is no distinction between () and []. They mean the same. The only difference is that it's easier to spot errors. Do you spot it?

In many implementation I bet you'd get errors at compile time. Eg. Racket flagged this as bad syntax before running it just by hitting "check syntax".

Body:
The proper syntax of let is:

(let ([binding expression]
      [binding2 expression2]
      ...)
  body ...)

If you had formatted it correctly you would have seen that instead of binding2 you have (arr2 (get-list name2 arrs)) with no expression. The error message refers to that no binding arr2 exists. So I'll format your code properly:

(define (similarity-arrays name1 name2 arrs result)
  (let ([arr1 (get-list name1 arrs)]
        [(arr2 (get-list name2 arrs))])
    (if (= (length arr1)(length arr2))
        (let ([x1 (car arr1)]
              [x2 (car arr2)])
          (if (= 0 (length arr1))
              result
              (similarity-arrays
               (cdr arr1)
               (cdr arr2)
               (+ result (- (car arr1)(car arr2))))))
        #f)))

Now from R6RS there is no distinction between () and []. They mean the same. The only difference is that it's easier to spot errors. Do you spot it?

In many implementation I bet you'd get errors at compile time. Eg. Racket flagged this as bad syntax before running it just by hitting "check syntax".


问:
How can I use a cursor.forEach() in MongoDB using Node.js?
I have a huge collection of documents in my DB and I'm wondering how can I run through all the documents and update them, each document with a different value.</p>

答:
None of the previous answers mentions batching the updates. That makes them extremely slow  - tens or hundreds of times slower than a solution using bulkWrite.

Let's say you want to double the value of a field in each document. Here's how to do that fast  and with fixed memory consumption:

// Double the value of the 'foo' field in all documents
let bulkWrites = [];
const bulkDocumentsSize = 100;  // how many documents to write at once
let i = 0;
db.collection.find({ ... }).forEach(doc => {
  i++;

  // Update the document...
  doc.foo = doc.foo * 2;

  // Add the update to an array of bulk operations to execute later
  bulkWrites.push({
    replaceOne: {
      filter: { _id: doc._id },
      replacement: doc,
    },
  });

  // Update the documents and log progress every `bulkDocumentsSize` documents
  if (i % bulkDocumentsSize === 0) {
    db.collection.bulkWrite(bulkWrites);
    bulkWrites = [];
    print(`Updated ${i} documents`);
  }
});
// Flush the last <100 bulk writes
db.collection.bulkWrite(bulkWrites);
```

ContentLicense: CC BY-SA 3.0


问:
Calculate percentage share of values against a value which is a row observation in the data frame
I want to calculate the percentage share and create new columns using mutate. I have the following data:

```<code>country, metric, segment, value1990, value2000, value2010
canada, abc, rural, 10, 15, 16
canada, abc, urban, 12, 12, 18
canada, abc, total, 22, 27, 34
canada, xyz, rural, 6, 9, 10
canada, xyc, urban, 7, 8, 8
canada, xyc, total, 13, 17, 18
canada, population, rural, 80, 86, 95
canada, population, urban, 102, 110, 121
canada, population, total, 182, 196, 216
</code>```

The data frame consists data from several countries and across several years. I want to create a new column with the following values

```<code>country, metric, segment, value, percent1990, percent2000, percent2010

canada, abc, rural, 10, 15, 16, 12.5%, 17.4%, 16.8%
canada, abc, urban, 12, 12, 18, 11.7%, 10.9%, 14.8%
canada, abc, total, 22, 27, 34, 12.1%, 13.7%, 15.7%
canada, xyz, rural, 6, 9, 10, 7.5%, 10.4%, 10.5%
canada, xyc, urban, 7, 8, 8, 6.8%, 7.2%, 6.6%
canada, xyc, total, 13, 17, 18, 7.22%, 8.6%, 8.3%
canada, population, rural, 80, 86, 95, 100%, 100%, 100%
canada, population, urban, 102, 110, 121, 100%, 100%, 100%
canada, population, total, 182, 196, 216, 100%, 100%, 100%
</code>```

Essentially, I want to calculate the value variable's percentage share of the population depending on whether it is rural/urban/total, across multiple years.

E.g.
(row 1) percent_share = (10/80)*100 = 12.5%

(row 2) percent_share = (10/102)*100 = 11.76%

(row 3) percent_share = (10/182)*100 = 12.09%

I'm unable to go beyond the group_by chaining to ascertain how to input the necessary function

```<code>df = df %>%
     group_by (country, metric) %>%
     mutate(...)
</code>```

答:
EDIT: for new question data containing years

This would be easier if you moved the years and the total population to new columns. Here's one way to do that.

Assuming your example data is in a data frame named df1: first gather the years.

```<code>library(dplyr)
library(tidyr)

df1 <- df1 %>% gather(Year, Value, 4:6)
</code>```

Then filter for metric == population and join back to the original data.

```<code>df1 %>% filter(metric == "population") %>%
  left_join(filter(df1, metric != "population"),
            by = c("country", "segment", "Year")) %>%
  select(country, segment, Year, population = Value.x, metric = metric.y, value = Value.y)
</code>```

Result:

```<code>   country segment      Year population metric value
1   canada   rural value1990         80    abc    10
2   canada   rural value1990         80    xyz     6
3   canada   urban value1990        102    abc    12
4   canada   urban value1990        102    xyc     7
5   canada   total value1990        182    abc    22
6   canada   total value1990        182    xyc    13
7   canada   rural value2000         86    abc    15
8   canada   rural value2000         86    xyz     9
9   canada   urban value2000        110    abc    12
10  canada   urban value2000        110    xyc     8
11  canada   total value2000        196    abc    27
12  canada   total value2000        196    xyc    17
13  canada   rural value2010         95    abc    16
14  canada   rural value2010         95    xyz    10
15  canada   urban value2010        121    abc    18
16  canada   urban value2010        121    xyc     8
17  canada   total value2010        216    abc    34
18  canada   total value2010        216    xyc    18
</code>```

Then add a mutate:

```<code>df1 %>% filter(metric == "population") %>%
  left_join(filter(df1, metric != "population"),
            by = c("country", "segment", "Year")) %>%
  select(country, segment, Year, population = Value.x, metric = metric.y, value = Value.y) %>%
  mutate(percent_share = 100 * (value / population))
</code>```

Result:

```<code>   country segment      Year population metric value percent_share
1   canada   rural value1990         80    abc    10     12.500000
2   canada   rural value1990         80    xyz     6      7.500000
3   canada   urban value1990        102    abc    12     11.764706
4   canada   urban value1990        102    xyc     7      6.862745
5   canada   total value1990        182    abc    22     12.087912
6   canada   total value1990        182    xyc    13      7.142857
7   canada   rural value2000         86    abc    15     17.441860
8   canada   rural value2000         86    xyz     9     10.465116
9   canada   urban value2000        110    abc    12     10.909091
10  canada   urban value2000        110    xyc     8      7.272727
11  canada   total value2000        196    abc    27     13.775510
12  canada   total value2000        196    xyc    17      8.673469
13  canada   rural value2010         95    abc    16     16.842105
14  canada   rural value2010         95    xyz    10     10.526316
15  canada   urban value2010        121    abc    18     14.876033
16  canada   urban value2010        121    xyc     8      6.611570
17  canada   total value2010        216    abc    34     15.740741
18  canada   total value2010        216    xyc    18      8.333333
</code>```

Body:
I want to calculate the percentage share and create new columns using mutate. I have the following data:

country, metric, segment, value1990, value2000, value2010
canada, abc, rural, 10, 15, 16
canada, abc, urban, 12, 12, 18
canada, abc, total, 22, 27, 34
canada, xyz, rural, 6, 9, 10
canada, xyc, urban, 7, 8, 8
canada, xyc, total, 13, 17, 18
canada, population, rural, 80, 86, 95
canada, population, urban, 102, 110, 121
canada, population, total, 182, 196, 216

The data frame consists data from several countries and across several years. I want to create a new column with the following values

country, metric, segment, value, percent1990, percent2000, percent2010

canada, abc, rural, 10, 15, 16, 12.5%, 17.4%, 16.8%
canada, abc, urban, 12, 12, 18, 11.7%, 10.9%, 14.8%
canada, abc, total, 22, 27, 34, 12.1%, 13.7%, 15.7%
canada, xyz, rural, 6, 9, 10, 7.5%, 10.4%, 10.5%
canada, xyc, urban, 7, 8, 8, 6.8%, 7.2%, 6.6%
canada, xyc, total, 13, 17, 18, 7.22%, 8.6%, 8.3%
canada, population, rural, 80, 86, 95, 100%, 100%, 100%
canada, population, urban, 102, 110, 121, 100%, 100%, 100%
canada, population, total, 182, 196, 216, 100%, 100%, 100%

Essentially, I want to calculate the value variable's percentage share of the population depending on whether it is rural/urban/total, across multiple years.

E.g.
(row 1) percent_share = (10/80)*100 = 12.5%

(row 2) percent_share = (10/102)*100 = 11.76%

(row 3) percent_share = (10/182)*100 = 12.09%

I'm unable to go beyond the group_by chaining to ascertain how to input the necessary function

df = df %>%
     group_by (country, metric) %>%
     mutate(...)

Body:
EDIT: for new question data containing years

This would be easier if you moved the years and the total population to new columns. Here's one way to do that.

Assuming your example data is in a data frame named df1: first gather the years.

library(dplyr)
library(tidyr)

df1 <- df1 %>% gather(Year, Value, 4:6)

Then filter for metric == population and join back to the original data.

df1 %>% filter(metric == "population") %>%
  left_join(filter(df1, metric != "population"),
            by = c("country", "segment", "Year")) %>%
  select(country, segment, Year, population = Value.x, metric = metric.y, value = Value.y)

Result:

   country segment      Year population metric value
1   canada   rural value1990         80    abc    10
2   canada   rural value1990         80    xyz     6
3   canada   urban value1990        102    abc    12
4   canada   urban value1990        102    xyc     7
5   canada   total value1990        182    abc    22
6   canada   total value1990        182    xyc    13
7   canada   rural value2000         86    abc    15
8   canada   rural value2000         86    xyz     9
9   canada   urban value2000        110    abc    12
10  canada   urban value2000        110    xyc     8
11  canada   total value2000        196    abc    27
12  canada   total value2000        196    xyc    17
13  canada   rural value2010         95    abc    16
14  canada   rural value2010         95    xyz    10
15  canada   urban value2010        121    abc    18
16  canada   urban value2010        121    xyc     8
17  canada   total value2010        216    abc    34
18  canada   total value2010        216    xyc    18

Then add a mutate:

df1 %>% filter(metric == "population") %>%
  left_join(filter(df1, metric != "population"),
            by = c("country", "segment", "Year")) %>%
  select(country, segment, Year, population = Value.x, metric = metric.y, value = Value.y) %>%
  mutate(percent_share = 100 * (value / population))

Result:

   country segment      Year population metric value percent_share
1   canada   rural value1990         80    abc    10     12.500000
2   canada   rural value1990         80    xyz     6      7.500000
3   canada   urban value1990        102    abc    12     11.764706
4   canada   urban value1990        102    xyc     7      6.862745
5   canada   total value1990        182    abc    22     12.087912
6   canada   total value1990        182    xyc    13      7.142857
7   canada   rural value2000         86    abc    15     17.441860
8   canada   rural value2000         86    xyz     9     10.465116
9   canada   urban value2000        110    abc    12     10.909091
10  canada   urban value2000        110    xyc     8      7.272727
11  canada   total value2000        196    abc    27     13.775510
12  canada   total value2000        196    xyc    17      8.673469
13  canada   rural value2010         95    abc    16     16.842105
14  canada   rural value2010         95    xyz    10     10.526316
15  canada   urban value2010        121    abc    18     14.876033
16  canada   urban value2010        121    xyc     8      6.611570
17  canada   total value2010        216    abc    34     15.740741
18  canada   total value2010        216    xyc    18      8.333333


问:
Check string indentation?
I'm building an analyzer for a series of strings.
I need to check how much each line is indented (either by tabs or by spaces).

Each line is just a string in a text editor.
How do I check by how much a string is indented?

Or rather, maybe I could check how much whitespace or \t are before a string, but I'm unsure of how.

答:
```<code>def count_indentation(line) :
    count = 0
    try :
        while (line[count] == "\t") :
            count += 1
        return count
    except :
        return count
</code>```

Title: Check string indentation?


问:
Can the vanilla JS date object be used normally in React.js?
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

```<code>componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}
</code>```

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

```<code>{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}
</code>```

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

```<code>import React from "react";
import Calendar from "./Calendar"

function App() {
    return (
        <div>
            <Calendar />
        </div>

    )
}

export default App;
</code>```

File Calendar.js

```<code>import React from "react";
import Date from "./Date";

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

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;
</code>```

File Date.js

```<code>import React from "react";

function Date() {
    return (
        <div className="grid date">
            <p>1</p>
        </div>
    )
}

export default Date;
</code>```

答:
You're importing a component as Date which overshadows the Date global object. Meaning that when looking for Date in the scope chain, JavaScript will stop at the module scope with your custom Date component instead of going up to the global scope and finding the Date global.

```<code>import Date from "./Date";
</code>```

An easy way to avoid that is just to change the name in which your date component is imported.

```<code>import React from 'react';
import DateComponent from './Date';

class Calendar extends React.Component {
    componentDidMount() {
        // No ambiguity here anymore!
        const date = new Date();
        console.log(date);
    }

    render() {
        // Explicit component name.
        return <DateComponent />;
    }
}
</code>```

And to avoid any ambiguity in your project, I'd rename the Date.jsx file to DateComponent.jsx as well.

Another way to avoid this ambiguity is to use the window global object properties explicitly.

```<code>import React from 'react';
import Date from './Date';

class Calendar extends React.Component {
    componentDidMount() {
        // No ambiguity here anymore!
        const date = new window.Date();
        console.log(date);
    }

    render() {
        // Explicit component name.
        return <Date />;
    }
}
</code>```

Body:
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

import React from "react";
import Calendar from "./Calendar"

function App() {
    return (

            <Calendar />

    )
}

export default App;

File Calendar.js

import React from "react";
import Date from "./Date";

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

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;

File Date.js

import React from "react";

function Date() {
    return (

1

    )
}

export default Date;

Body:
You're importing a component as Date which overshadows the Date global object. Meaning that when looking for Date in the scope chain, JavaScript will stop at the module scope with your custom Date component instead of going up to the global scope and finding the Date global.

import Date from "./Date";

An easy way to avoid that is just to change the name in which your date component is imported.

import React from 'react';
import DateComponent from './Date';

class Calendar extends React.Component {
    componentDidMount() {
        // No ambiguity here anymore!
        const date = new Date();
        console.log(date);
    }

    render() {
        // Explicit component name.
        return <DateComponent />;
    }
}

And to avoid any ambiguity in your project, I'd rename the Date.jsx file to DateComponent.jsx as well.

Another way to avoid this ambiguity is to use the window global object properties explicitly.

import React from 'react';
import Date from './Date';

class Calendar extends React.Component {
    componentDidMount() {
        // No ambiguity here anymore!
        const date = new window.Date();
        console.log(date);
    }

    render() {
        // Explicit component name.
        return <Date />;
    }
}


问:
algorithm to find closest object
I need to map blue objects to red ones by distance. The center of each object is known. The yellow and green objects, if they are shown, are hints. They help to decide which red object is more important.

For example, in the situation shown in image below:

The bottom blue object should be mapped to the bottom most right red object since both green and yellow objects are very close to that red object.

The right blue object should be mapped to top-right red object since it's closer to it.

I have a naive solution, but I'm not quite sure what to do instead of "????" below

Do you have any suggestions?

My naive solution in sort of pseudo-code:

```<code>for each BLUE:
   find group P=(YELLOW_BLUE, GREEN_BLUE and RED_BLUE) when each object in P is the closest to BLUE
   vector<RED> redCandidates
   for each O in P:
       if O is YELLOW OR O is GREEN
          find closest RED to O
          insert RED to redCandidates

   if size of redCandidates is 0 -> return RED_BLUE
   else if size of redCandidates is 1 -> return redCandidates[0] since hint has more weight to the decision
   else if size of redCandidates is > 1 -> ????
</code>```

UPDATE1

After looking into Minimum Cost Flow problem suggested by @ldog, I decided to use Hungarian Algorithm. I created bipartite graph where each blue node is connected to each red node and the weights on the edges are the distance between blue and red.

Now, before I solve the graph, I need to apply rewards on the edges where yellow/green are close to red. I don't quite understand how to do that.

Let's say distance between blue 1 and the red 4 is D_1_4 = 10 and the distance between the yellow hint 11 and the red 4 is D_4_11 = 3. So, because D_1_4 > D_4_11, should I just add reward to the edge 1_4? Or, should I add the reward to each edge that enters node 4, meaning edges 1_4, 2_4 and 3_4?

答:
It seems your question is not fully formed and you are looking for a decent formulation of the things that you expressed in words.

Here are some suggestions:

Use intersection over union for dealing with how to assign similarity for overlapping areas.

There are many ways you could try to make what you expressed in words quantified, and therefore able to be optimized. One reasonable way to quantify what you expressed in words is as a minimization problem I will discuss below.

The minimization should assign one blue box to exactly one red box (given what you told me.) The green and yellow boxes are hints and are not included in this constraint, they are simply used to modify which red box is preferential over others. To formalize what you described in words, we have the set of red boxes R and the set of blue boxes B. There are m red boxes and n blue boxes with m >= n. Each pairing of blue box i with red box j has a preference w_{ij} (this preference is pre-calculated accounting for the hint boxes as well as spatial proximity.)

We wish to compute:

```<code>           max \sum_{i<j} w_{ij}x_{ij}
 such that
           \sum_{k} x_{ik} = 1, \sum_{l} x_{lj} = 1, x_{ik} \in {0,1}
</code>```

The variable x_{ij} is 1 if and only if blue box i is assigned to red box j, it is 0 otherwise.

This problem (is Totally Unimodular) and can be solved in polynomial time. In fact, it can be solved as an instance of the common Minimum Cost Flow problem. To do this, define a node in a graph for each blue box i, and a node in a graph for each red box j. Connect each blue node to each red node (directed blue->red) with an edge with weight -w_{ij} and capacity 1. Connect each blue node to the source (directed source -> blue) with an edge of capacity 1 and weight 0. Connect each red node to the sink (directed red->sink) with an edge of capacity 1 and weight 0. Give the source a supply of n and the sink a demand of n. Compute the Minimum Cost Flow on this graph (see for example lemon) and the resulting flow yields the maximum solution (alternatively minimum flow.)

Having described this in detail, I see this is already a common approach [1] to solve exactly problems like yours. Here is an implementation.

YMMV depending on how good you make your weights to be. You may want to try a machine learning approach to determine optimal weights using a ground truth dataset and an iterative refinement. The refinement can be computed for a fixed set of blue and red ground truth boxes by refining the weights w_{ij} until all other possible assignments other than the ground truth have a lower score of the optimization than the ground truth. This can be done iterative using any max-margin learning framework or technique, combined with the method I described above (and apparently is described in [1].)

[1] Zhang, Li, Nevatia: Global data association for multi-object tracking using network flows, CVPR (2008).

Title: algorithm to find closest object

Body:
I need to map blue objects to red ones by distance. The center of each object is known. The yellow and green objects, if they are shown, are hints. They help to decide which red object is more important.

For example, in the situation shown in image below:

The bottom blue object should be mapped to the bottom most right red object since both green and yellow objects are very close to that red object.

The right blue object should be mapped to top-right red object since it's closer to it.

I have a naive solution, but I'm not quite sure what to do instead of "????" below

Do you have any suggestions?

My naive solution in sort of pseudo-code:

for each BLUE:
   find group P=(YELLOW_BLUE, GREEN_BLUE and RED_BLUE) when each object in P is the closest to BLUE
   vector<RED> redCandidates
   for each O in P:
       if O is YELLOW OR O is GREEN
          find closest RED to O
          insert RED to redCandidates

   if size of redCandidates is 0 -> return RED_BLUE
   else if size of redCandidates is 1 -> return redCandidates[0] since hint has more weight to the decision
   else if size of redCandidates is > 1 -> ????

UPDATE1

After looking into Minimum Cost Flow problem suggested by @ldog, I decided to use Hungarian Algorithm. I created bipartite graph where each blue node is connected to each red node and the weights on the edges are the distance between blue and red.

Now, before I solve the graph, I need to apply rewards on the edges where yellow/green are close to red. I don't quite understand how to do that.

Let's say distance between blue 1 and the red 4 is D_1_4 = 10 and the distance between the yellow hint 11 and the red 4 is D_4_11 = 3. So, because D_1_4 > D_4_11, should I just add reward to the edge 1_4? Or, should I add the reward to each edge that enters node 4, meaning edges 1_4, 2_4 and 3_4?

Body:
It seems your question is not fully formed and you are looking for a decent formulation of the things that you expressed in words.

Here are some suggestions:

Use intersection over union for dealing with how to assign similarity for overlapping areas.

There are many ways you could try to make what you expressed in words quantified, and therefore able to be optimized. One reasonable way to quantify what you expressed in words is as a minimization problem I will discuss below.

The minimization should assign one blue box to exactly one red box (given what you told me.) The green and yellow boxes are hints and are not included in this constraint, they are simply used to modify which red box is preferential over others. To formalize what you described in words, we have the set of red boxes R and the set of blue boxes B. There are m red boxes and n blue boxes with m >= n. Each pairing of blue box i with red box j has a preference w_{ij} (this preference is pre-calculated accounting for the hint boxes as well as spatial proximity.)

We wish to compute:

           max \sum_{i<j} w_{ij}x_{ij}
 such that
           \sum_{k} x_{ik} = 1, \sum_{l} x_{lj} = 1, x_{ik} \in {0,1}

The variable x_{ij} is 1 if and only if blue box i is assigned to red box j, it is 0 otherwise.

This problem (is Totally Unimodular) and can be solved in polynomial time. In fact, it can be solved as an instance of the common Minimum Cost Flow problem. To do this, define a node in a graph for each blue box i, and a node in a graph for each red box j. Connect each blue node to each red node (directed blue->red) with an edge with weight -w_{ij} and capacity 1. Connect each blue node to the source (directed source -> blue) with an edge of capacity 1 and weight 0. Connect each red node to the sink (directed red->sink) with an edge of capacity 1 and weight 0. Give the source a supply of n and the sink a demand of n. Compute the Minimum Cost Flow on this graph (see for example lemon) and the resulting flow yields the maximum solution (alternatively minimum flow.)

Having described this in detail, I see this is already a common approach [1] to solve exactly problems like yours. Here is an implementation.

YMMV depending on how good you make your weights to be. You may want to try a machine learning approach to determine optimal weights using a ground truth dataset and an iterative refinement. The refinement can be computed for a fixed set of blue and red ground truth boxes by refining the weights w_{ij} until all other possible assignments other than the ground truth have a lower score of the optimization than the ground truth. This can be done iterative using any max-margin learning framework or technique, combined with the method I described above (and apparently is described in [1].)

[1] Zhang, Li, Nevatia: Global data association for multi-object tracking using network flows, CVPR (2008).


问:
got error when run cmd RAILS_ENV=production bundle exec rake assets:precompile
I'm trying to convert manageiq development mode to production mode so I applied precompile cmd and got error

ExecJS::RuntimeError: SyntaxError: Unexpected token: operator (>)
  (line: 2221, col: 46, pos: 3996497)

Error
      at new JS_Parse_Error (/tmp/execjs20190527-22386-1jyom7qjs:3623:11948)
      at js_error (/tmp/execjs20190527-22386-1jyom7qjs:3623:12167)
      at croak (/tmp/execjs20190527-22386-1jyom7qjs:3623:22038)
      at token_error (/tmp/execjs20190527-22386-1jyom7qjs:3623:22175)
      at unexpected (/tmp/execjs20190527-22386-1jyom7qjs:3623:22263)
      at expr_atom (/tmp/execjs20190527-22386-1jyom7qjs:3623:31244)
      at maybe_unary (/tmp/execjs20190527-22386-1jyom7qjs:3624:1752)
      at expr_ops (/tmp/execjs20190527-22386-1jyom7qjs:3624:2523)
      at maybe_conditional (/tmp/execjs20190527-22386-1jyom7qjs:3624:2615)
      at maybe_assign (/tmp/execjs20190527-22386-1jyom7qjs:3624:3058)

manageiq running in development mode correctly but unable to precompile the assets(which consist of JS, CSS files)

manageIq should compile properly and should start in production mode and generate production log

答:
Try the following instead:

```<code>cd /var/www/miq/vmdb
bin/update
</code>```

rake assets:precompile is only a part of what needs to happen, and bin/update does that as well as a number of other things.

Body:
Try the following instead:

cd /var/www/miq/vmdb
bin/update

rake assets:precompile is only a part of what needs to happen, and bin/update does that as well as a number of other things.


问:
Select shifted column values based on a different column conditional in pandas
I have a dataframe:

```<code>A     B
100   0.00
50   -0.50
100   1.00
120   0.20

</code>```

I would like to select shifted values on the A column based on a certain condition on the B column, so for instance if B >= 0.20 and my desired shift step is 2 I would get 100 (from B =1.00) and 50 (from B = 0.20 ), rows where B < 0.20 can be discarded.

答:
You can use shift with np.where to conditionally get the shifted values:

```<code>shiftstep = 2

df['shift'] = np.where(df['B'].ge(0.2), df['A'].shift(shiftstep), np.NaN)
</code>```

```<code>     A    B  shift
0  100  0.0    NaN
1   50 -0.5    NaN
2  100  1.0  100.0
3  120  0.2   50.0
</code>```

Body:
I have a dataframe:

A     B
100   0.00
50   -0.50
100   1.00
120   0.20

I would like to select shifted values on the A column based on a certain condition on the B column, so for instance if B >= 0.20 and my desired shift step is 2 I would get 100 (from B =1.00) and 50 (from B = 0.20 ), rows where B < 0.20 can be discarded.

Body:
You can use shift with np.where to conditionally get the shifted values:

shiftstep = 2

df['shift'] = np.where(df['B'].ge(0.2), df['A'].shift(shiftstep), np.NaN)

     A    B  shift
0  100  0.0    NaN
1   50 -0.5    NaN
2  100  1.0  100.0
3  120  0.2   50.0


问:
Where is the type Log defined inside of the Substrate runtime crate?
Take a look at this implementation:

```<code>impl consensus::Trait for Runtime {
    type Log = Log;
    type SessionKey = AuthorityId;

    // The Aura module handles offline-reports internally
    // rather than using an explicit report system.
    type InherentOfflineReport = ();
}
</code>```

How is Log defined? There is no use clause for importing this symbol.

Running

cargo rustc -- -Z unstable-options --pretty=expanded
```

does not show any Log entry with type clause. It does show other macro declarations after expanding macros at level 0, but I am not sure if this relevant.

I tried using the Atom IDE because it automatically parses the files and lets you find the definition of the symbols, but it did not help.

How can I find how Log is defined?

答:
Log is defined by construct_runtime macro.
Here are some relevant code:

construct_runtime macro:

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L79

```<code>macro_rules! construct_runtime {
    (
        pub enum $runtime:ident with Log ($log_internal:ident: DigestItem<$( $log_genarg:ty ),+>)
            where
                Block = $block:ident,
                NodeBlock = $node_block:ty,
                UncheckedExtrinsic = $uncheckedextrinsic:ident
        {
            $( $rest:tt )*
        }
    )
</code>```

calling __decl_outer_log

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L267

```<code>    $crate::__decl_outer_log!(
        $runtime;
        $log_internal < $( $log_genarg ),* >;
        {};
        $(
            $name: $module:: $( < $module_instance >:: )? { $( $modules $( ( $( $modules_args )* ) )* )* }
        )*
    );
</code>```

__decl_outer_log macro

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L706

```<code>macro_rules! __decl_outer_log {
    (
        $runtime:ident;
        $log_internal:ident <$( $log_genarg:ty ),+>;
        { $( $parsed:tt )* };
        $name:ident: $module:ident:: $(<$module_instance:ident>::)? {
            Log ( $( $args:ident )* ) $( $modules:ident $( ( $( $modules_args:ident )* ) )* )*
        }
        $( $rest:tt )*
    ) => {
</code>```

calling impl_outer_log

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L763

```<code>(
    $runtime:ident;
    $log_internal:ident <$( $log_genarg:ty ),+>;
    { $(
        $parsed_modules:ident $(< $parsed_instance:ident >)? ( $( $parsed_args:ident )* )
    )* };
) => {
    $crate::paste::item! {
        $crate::runtime_primitives::impl_outer_log!(
            pub enum Log($log_internal: DigestItem<$( $log_genarg ),*>) for $runtime {
                $( [< $parsed_modules $(_ $parsed_instance)? >] $(< $parsed_modules::$parsed_instance >)? ( $( $parsed_args ),* ) ),*
            }
        );
    }
};
</code>```

impl_outer_log macro:
https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/core/sr-primitives/src/lib.rs#L630

```<code>macro_rules! impl_outer_log {
    (
        $(#[$attr:meta])*
        pub enum $name:ident ($internal:ident: DigestItem<$( $genarg:ty ),*>) for $trait:ident {
            $( $module:ident $(<$instance:path>)? ( $( $sitem:ident ),* ) ),*
        }
    )
</code>```

which actually declare and implement the Log struct

You should be able to see the result when cargo expand the runtime crate.

Body:
Take a look at this implementation:

impl consensus::Trait for Runtime {
    type Log = Log;
    type SessionKey = AuthorityId;

    // The Aura module handles offline-reports internally
    // rather than using an explicit report system.
    type InherentOfflineReport = ();
}

How is Log defined? There is no use clause for importing this symbol.

Running

cargo rustc -- -Z unstable-options --pretty=expanded

does not show any Log entry with type clause. It does show other macro declarations after expanding macros at level 0, but I am not sure if this relevant.

I tried using the Atom IDE because it automatically parses the files and lets you find the definition of the symbols, but it did not help.

How can I find how Log is defined?

Body:
Log is defined by construct_runtime macro.
Here are some relevant code:

construct_runtime macro:

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L79

macro_rules! construct_runtime {
    (
        pub enum $runtime:ident with Log ($log_internal:ident: DigestItem<$( $log_genarg:ty ),+>)
            where
                Block = $block:ident,
                NodeBlock = $node_block:ty,
                UncheckedExtrinsic = $uncheckedextrinsic:ident
        {
            $( $rest:tt )*
        }
    )

calling __decl_outer_log

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L267

    $crate::__decl_outer_log!(
        $runtime;
        $log_internal < $( $log_genarg ),* >;
        {};
        $(
            $name: $module:: $( < $module_instance >:: )? { $( $modules $( ( $( $modules_args )* ) )* )* }
        )*
    );

__decl_outer_log macro

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L706

macro_rules! __decl_outer_log {
    (
        $runtime:ident;
        $log_internal:ident <$( $log_genarg:ty ),+>;
        { $( $parsed:tt )* };
        $name:ident: $module:ident:: $(<$module_instance:ident>::)? {
            Log ( $( $args:ident )* ) $( $modules:ident $( ( $( $modules_args:ident )* ) )* )*
        }
        $( $rest:tt )*
    ) => {

calling impl_outer_log

https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/srml/support/src/runtime.rs#L763

(
    $runtime:ident;
    $log_internal:ident <$( $log_genarg:ty ),+>;
    { $(
        $parsed_modules:ident $(< $parsed_instance:ident >)? ( $( $parsed_args:ident )* )
    )* };
) => {
    $crate::paste::item! {
        $crate::runtime_primitives::impl_outer_log!(
            pub enum Log($log_internal: DigestItem<$( $log_genarg ),*>) for $runtime {
                $( [< $parsed_modules $(_ $parsed_instance)? >] $(< $parsed_modules::$parsed_instance >)? ( $( $parsed_args ),* ) ),*
            }
        );
    }
};

impl_outer_log macro:
https://github.com/paritytech/substrate/blob/950e90e75dc7d16dcf99972fcc733945a832dc3e/core/sr-primitives/src/lib.rs#L630

macro_rules! impl_outer_log {
    (
        $(#[$attr:meta])*
        pub enum $name:ident ($internal:ident: DigestItem<$( $genarg:ty ),*>) for $trait:ident {
            $( $module:ident $(<$instance:path>)? ( $( $sitem:ident ),* ) ),*
        }
    )

which actually declare and implement the Log struct

You should be able to see the result when cargo expand the runtime crate.


问:
Angular material dynamic radio button able to select multiple but should allow only once in a group
I have an angular-material Tree with creating check boxes and radio button dynamically based on array

Array as follows:

```<code>{
    "Documents": {
      "angular": {
        "src": {
          "core": 0,
          "compiler": 0
        }
      },
      "material2": {
        "src": {
          "button": 1,
          "checkbox": 1,
          "input": 1
        }
      }
    }............................etc
}
</code>```

html part as follows:

```<code><mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle matTreeNodePadding>
    <div *ngIf="node.type;else other_content"> <!--- node.type == 1 then checkbox!-->
      <mat-checkbox>Check me!</mat-checkbox>
</div>

<ng-template #other_content><!--- node.type ==0 then radio button!-->
  <mat-radio-group>
  <mat-radio-button value=" {{node.filename}}">{{node.filename}}</mat-radio-button>
</mat-radio-group>
</ng-template>

  </mat-tree-node>

  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding>
    <button mat-icon-button matTreeNodeToggle
            [attr.aria-label]="'toggle ' + node.filename">
      <mat-icon>
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.filename}} : {{node.type}}
  </mat-tree-node>
</mat-tree>
</code>```

Angular Tree Reference Example

It looks as follows:

The issue is that as shown in picture I am able to check all radio button in a particular level of tree. But it should allow only one radio button from radio button group.

The issue occur because of below:

```<code><loop .....>

<mat-radio-group>
  <mat-radio-button value=" {{node.filename}}">{{node.filename}}</mat-radio-button>
</mat-radio-group>
</loop end>
</code>```

But in single iteration one set of   <mat-radio-group> is created but it should create as below:

```<code><mat-radio-group>
      loop through <mat-radio-button>
    </mat-radio-group>
</code>```

What should I do to make only Radio button can be selected in a particular group?

答:
Did you tried putting the mat-radio-group outside of mat-tree? Something like </p>

```<code><mat-radio-group>
    <mat-tree>
       <mat-tree-node>
            <mat-radio-button></mat-radio-button>
        </mat-tree-node>
    </mat-tree>
</mat-radio-group>
</code>```

Body:
I have an angular-material Tree with creating check boxes and radio button dynamically based on array

Array as follows:

{
    "Documents": {
      "angular": {
        "src": {
          "core": 0,
          "compiler": 0
        }
      },
      "material2": {
        "src": {
          "button": 1,
          "checkbox": 1,
          "input": 1
        }
      }
    }............................etc
}

html part as follows:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle matTreeNodePadding>

      <mat-checkbox>Check me!</mat-checkbox>

<ng-template #other_content>
  <mat-radio-group>
  <mat-radio-button value=" {{node.filename}}">{{node.filename}}</mat-radio-button>
</mat-radio-group>
</ng-template>

  </mat-tree-node>

  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding>
    <button mat-icon-button matTreeNodeToggle
            [attr.aria-label]="'toggle ' + node.filename">
      <mat-icon>
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.filename}} : {{node.type}}
  </mat-tree-node>
</mat-tree>

Angular Tree Reference Example

It looks as follows:

The issue is that as shown in picture I am able to check all radio button in a particular level of tree. But it should allow only one radio button from radio button group.

The issue occur because of below:

<loop .....>

<mat-radio-group>
  <mat-radio-button value=" {{node.filename}}">{{node.filename}}</mat-radio-button>
</mat-radio-group>
</loop end>

But in single iteration one set of   <mat-radio-group> is created but it should create as below:

<mat-radio-group>
      loop through <mat-radio-button>
    </mat-radio-group>

What should I do to make only Radio button can be selected in a particular group?

Body:
Did you tried putting the mat-radio-group outside of mat-tree? Something like

<mat-radio-group>
    <mat-tree>
       <mat-tree-node>
            <mat-radio-button></mat-radio-button>
        </mat-tree-node>
    </mat-tree>
</mat-radio-group>


问:
Using map function instead of for loop
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

```<code>def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)
</code>```

答:
You should avoid to use a global variable like 'numwords'. You have to return numwords in your wordcount() function.

This code works :

```<code>def wordcount(l):
    numwords = 0
    words = l.split()
    numwords += len(words)
    return numwords

f = open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print('Number of lines =', numlines)

numwords = 0
numwords = map(wordcount, lines)
print ('Number of words =', numwords)
</code>```

My testfile.txt contains :

```<code>Hello world
my name is
james bond
</code>```

Ouput :

```<code>('Number of lines =', 3)
('Number of words =', [2, 3, 2])
</code>```

Title: Using map function instead of for loop

Body:
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)

Body:
You should avoid to use a global variable like 'numwords'. You have to return numwords in your wordcount() function.

This code works :

def wordcount(l):
    numwords = 0
    words = l.split()
    numwords += len(words)
    return numwords

f = open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print('Number of lines =', numlines)

numwords = 0
numwords = map(wordcount, lines)
print ('Number of words =', numwords)

My testfile.txt contains :

Hello world
my name is
james bond

Ouput :

('Number of lines =', 3)
('Number of words =', [2, 3, 2])


问:
.Net Core 2.2, PutAsync, HttpContent Question
I am transitioning from node with express to .Net Core 2.2.  I'm trying to create a put request to push updates to an api.  I've figured out I can create it with

var client = new HttpClient();
 client.PutAsync(url, httpContent)

My first question is, how do I create the httpContent?  Normally in this situation I would create a JSON object, but of course that won't work here.

My second question is, I'm using .Net Core 2.2.  Is using the HttpClient the correct way or should I use the Factory?

答:
Please refer to the following code snippet to make a post request, you can achieve the put request at the same, just change the method to Put.

```<code>protected async Task<Tuple<HttpStatusCode, TOutput>> MakeRequest<TInput, TOutput>(string baseAdrress, string apiUrl, TInput data)
{
    var contentData = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.BaseAddress = new Uri(baseAdrress);

    var response = await client.SendAsync(new HttpRequestMessage
    {
        RequestUri = new Uri(apiUrl, UriKind.Relative),
        Content = contentData,
        Method = HttpMethod.Post
    });

    if (response.StatusCode == HttpStatusCode.InternalServerError)
    {
        return Tuple.Create(HttpStatusCode.InternalServerError, default(TOutput));
    }

    var stringData = await response.Content.ReadAsStringAsync();
    var jsonData = JsonConvert.DeserializeObject<TOutput>(stringData);

    return Tuple.Create(HttpStatusCode.OK, jsonData);
}
</code>```

Above code is just a quick demonstration for using http client, in real-world, you should use HttpClientFactory instead. There are multiple ways to use HttpClientFactory that you can read here at Microsoft Docs

Using HttpClient directly can lead to some issues that was mentioned by M$ "As a first issue, while this class is disposable, using it with the using statement is not the best choice because even when you dispose HttpClient object, the underlying socket is not immediately released and can cause a serious issue named ‘sockets exhaustion’."

Body:
Please refer to the following code snippet to make a post request, you can achieve the put request at the same, just change the method to Put.

protected async Task<Tuple<HttpStatusCode, TOutput>> MakeRequest<TInput, TOutput>(string baseAdrress, string apiUrl, TInput data)
{
    var contentData = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.BaseAddress = new Uri(baseAdrress);

    var response = await client.SendAsync(new HttpRequestMessage
    {
        RequestUri = new Uri(apiUrl, UriKind.Relative),
        Content = contentData,
        Method = HttpMethod.Post
    });

    if (response.StatusCode == HttpStatusCode.InternalServerError)
    {
        return Tuple.Create(HttpStatusCode.InternalServerError, default(TOutput));
    }

    var stringData = await response.Content.ReadAsStringAsync();
    var jsonData = JsonConvert.DeserializeObject<TOutput>(stringData);

    return Tuple.Create(HttpStatusCode.OK, jsonData);
}

Above code is just a quick demonstration for using http client, in real-world, you should use HttpClientFactory instead. There are multiple ways to use HttpClientFactory that you can read here at Microsoft Docs

Using HttpClient directly can lead to some issues that was mentioned by M$ "As a first issue, while this class is disposable, using it with the using statement is not the best choice because even when you dispose HttpClient object, the underlying socket is not immediately released and can cause a serious issue named ‘sockets exhaustion’."


问:
Is there any better way to Launch UWP apps from Console application
I tried to launch the UWP application from c# console application. It tried with below code which uses APPID

Process.Start(@"C:\Program Files (x86)\Windows Kits\10\App Certification Kit\microsoft.windows.softwarelogo.appxlauncher.exe", "1a75- 6f75 - 5ed3 - 8944 - 6b7df2bee095");

Is there any better way to launch UWP application programatically.

答:
To launch any UWP app on the system you can use the following API:

AppListEntry.LaunchAsync Method

To get the AppListEntry for the desired application, use the PackageManager APIs:
PackageManager.FindPackageForUser(String, String) Method

Package.GetAppListEntriesAsync Method

Alternatively, you can use the following Win32 API insteadp of the AppListEntry API:

IApplicationActivationManager::ActivateApplication method


问:
slurm: write exit code or job status into logfile when finished (completed or failed)
I need to make sure that all commands in my script finished successfully (returned 0 status). That's why my slurm script includes following lines:

```<code>set -e
set -x
</code>```

Now I would like the exit status of the whole script to be written in the logfile that's automatically created by slurm. I have tried echo $SLURM_JOB_EXIT_CODE (with no success) or echo $? (which I am not sure is what I need) as a last line of my script.

What's the proper way to do this? I need to differentiate between "failed" and "completed" jobs, preferably by checking logfiles only.

答:
I know this is an old question but here is my way of appending the final job status to the Slurm output.

res=$(sbatch job.sh)
echo $res
sleep 10s
ST="PENDING"
while [[ "$ST" != "COMPLETED" && "$ST" != "FAILED" ]] ; do
    ST=$(sacct -j ${res##* } -o State | awk 'FNR == 3 {print $1}')
    sleep 10s
done
echo "$ST" >> job.out # assuming stdout writes to job.out
```

Body:
I need to make sure that all commands in my script finished successfully (returned 0 status). That's why my slurm script includes following lines:

set -e
set -x

Now I would like the exit status of the whole script to be written in the logfile that's automatically created by slurm. I have tried echo $SLURM_JOB_EXIT_CODE (with no success) or echo $? (which I am not sure is what I need) as a last line of my script.

What's the proper way to do this? I need to differentiate between "failed" and "completed" jobs, preferably by checking logfiles only.


问:
How can I learn the top-level design of DefaultConfig in rocket-chip?
I'm new to rocket-chip generator and I want to learn the top-level design of the default Rocket Chip instance (the one defined by DefaultConfig) before extend my own top-level design. For example, how many tiles does it have? What cores are in each of the tiles?

How can I get started? Read the codes in rocket-chip\src\main\scala?
Or is there any document offers some information about the Rocket Chip instance of the DefaultConfig?

答: Try looking in src/main/scala/system/config.scala, you can find a class called Default config, then track that you can get all the configurations.


问:
interfaces and generalisation in TypeScript
I have four entities (models) in TypeScript as follows:

Base class/model:

```<code>export interface BaseClass {
  id: string;
  entityId: string;
  entityName: string;
}
</code>```

Child Class 1:

```<code>import { BaseClass } from './base-class';

export interface ChildClass1 extends BaseClass {
  commentId: string;
  authorName: string;
}
</code>```

Child Class 2:

```<code>import { BaseClass } from './base-class';

export interface ChildClass2 extends BaseClass {
  authorName: string;
}
</code>```

Child Class 3:

```<code>import { BaseClass } from './base-class';

export interface ChildClass3 extends BaseClass {
  operationType: string;
}
</code>```

In my component, how can I achieve generalisation just like we have in Java.

For ex: Have an object named,

```<code>public models: BaseClass[] = [];
</code>```

How can I have different types of objects like ChildClass1, ChildClass2, ChildClass3 present in the models objects above.

EDIT:

The following is a screenshot that shows the error in Visual Studio Code.

答:
Yes, you can do this.  The problem you are probably having is that when you use a "fresh" object literal (that is, one that hasn't already been assigned to some variable) and assign it to a variable of a specified type, TypeScript uses excess property checks to warn you if you are adding unexpected properties.  Types in TypeScript are normally treated as open/extendable/generalizable, but in this one instance they are treated as closed/exact, because it's often an error to do this.

```<code>const excessPropertyErrors: BaseClass[] = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // error! excess property checks are biting us
</code>```

So, how can we prevent this from happening to us?  All sorts of ways, in fact.

One is to explicitly mention the subclasses we expect.  The type BaseClass and BaseClass | ChildClass1 | ChildClass2 | ChildClass3 are structurally identical, but they differ by how they see "extra" properties:

```<code>const explicitlyMentionSubclasses:
 Array<BaseClass | ChildClass1 | ChildClass2 | ChildClass3> = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // okay
</code>```

That would still throw an excess property error if you misspell operationType, so you might want to mention the types in some way.  Still, having the type of your variable carry around the subclasses is kind of limiting.

Another way to do this is to assign the fresh object literal to variables annotated with the specific subclass type you care about, and then put those variables in your array:

```<code>const childClass1: ChildClass1 =
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" };
const childClass2: ChildClass2 =
  { id: "f", entityId: "g", entityName: "h", authorName: "i" };
const childClass3: ChildClass3 =
  { id: "j", entityId: "k", entityName: "l", operationType: "m" };
const individualElements: BaseClass[] = [childClass1, childClass2, childClass3]; // okay
</code>```

That's one of the safest ways you can do this, since each variable childClass1, childClass2 and childClass3 will be constrained and excess-property-checked to the relevant subclass.

Another way you can do this is to completely turn off excess property checks by having the object literals no longer be "fresh". First, assign the array to an unannotated variable; the type will be inferred by the compiler.  Then, assign the inferred-type variable to a BaseClass[] variable:

```<code>const completelyInferred = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
];
const noLongerFresh: BaseClass[] = twoStepProcess1; // okay
</code>```

That works, but keep in mind that there will be absolutely no checking of anything except the BaseClass members.  If you make operationType a number, it will still be accepted.

You could decide that you want BaseClass never to have excess property checks ever.  One way to turn that completely off is to define a BaseClass extension which explicitly allows any excess properties of any type:

```<code>interface BaseClassWithUnknownExtraProperties extends BaseClass {
  [k: string]: unknown;  // add index signature
}
const indexSignature: BaseClassWithUnknownExtraProperties[] = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // okay
</code>```

Finally, you might want to use a helper function to accept extensions of BaseClass (which turns off excess property checking):

```<code>const asBaseClassArray = <T extends BaseClass>(arr: T[]) => arr;
const usingHelperFunction: BaseClass[] = asBaseClassArray([
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]); // okay
</code>```

Hope one of those ways gives you some direction.  Good luck!

Link to code

Body:
I have four entities (models) in TypeScript as follows:

Base class/model:

export interface BaseClass {
  id: string;
  entityId: string;
  entityName: string;
}

Child Class 1:

import { BaseClass } from './base-class';

export interface ChildClass1 extends BaseClass {
  commentId: string;
  authorName: string;
}

Child Class 2:

import { BaseClass } from './base-class';

export interface ChildClass2 extends BaseClass {
  authorName: string;
}

Child Class 3:

import { BaseClass } from './base-class';

export interface ChildClass3 extends BaseClass {
  operationType: string;
}

In my component, how can I achieve generalisation just like we have in Java.

For ex: Have an object named,

public models: BaseClass[] = [];

How can I have different types of objects like ChildClass1, ChildClass2, ChildClass3 present in the models objects above.

EDIT:

The following is a screenshot that shows the error in Visual Studio Code.

Body:
Yes, you can do this.  The problem you are probably having is that when you use a "fresh" object literal (that is, one that hasn't already been assigned to some variable) and assign it to a variable of a specified type, TypeScript uses excess property checks to warn you if you are adding unexpected properties.  Types in TypeScript are normally treated as open/extendable/generalizable, but in this one instance they are treated as closed/exact, because it's often an error to do this.

const excessPropertyErrors: BaseClass[] = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // error! excess property checks are biting us

So, how can we prevent this from happening to us?  All sorts of ways, in fact.

One is to explicitly mention the subclasses we expect.  The type BaseClass and BaseClass | ChildClass1 | ChildClass2 | ChildClass3 are structurally identical, but they differ by how they see "extra" properties:

const explicitlyMentionSubclasses:
 Array<BaseClass | ChildClass1 | ChildClass2 | ChildClass3> = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // okay

That would still throw an excess property error if you misspell operationType, so you might want to mention the types in some way.  Still, having the type of your variable carry around the subclasses is kind of limiting.

Another way to do this is to assign the fresh object literal to variables annotated with the specific subclass type you care about, and then put those variables in your array:

const childClass1: ChildClass1 =
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" };
const childClass2: ChildClass2 =
  { id: "f", entityId: "g", entityName: "h", authorName: "i" };
const childClass3: ChildClass3 =
  { id: "j", entityId: "k", entityName: "l", operationType: "m" };
const individualElements: BaseClass[] = [childClass1, childClass2, childClass3]; // okay

That's one of the safest ways you can do this, since each variable childClass1, childClass2 and childClass3 will be constrained and excess-property-checked to the relevant subclass.

Another way you can do this is to completely turn off excess property checks by having the object literals no longer be "fresh". First, assign the array to an unannotated variable; the type will be inferred by the compiler.  Then, assign the inferred-type variable to a BaseClass[] variable:

const completelyInferred = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
];
const noLongerFresh: BaseClass[] = twoStepProcess1; // okay

That works, but keep in mind that there will be absolutely no checking of anything except the BaseClass members.  If you make operationType a number, it will still be accepted.

You could decide that you want BaseClass never to have excess property checks ever.  One way to turn that completely off is to define a BaseClass extension which explicitly allows any excess properties of any type:

interface BaseClassWithUnknownExtraProperties extends BaseClass {
  [k: string]: unknown;  // add index signature
}
const indexSignature: BaseClassWithUnknownExtraProperties[] = [
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // okay

Finally, you might want to use a helper function to accept extensions of BaseClass (which turns off excess property checking):

const asBaseClassArray = <T extends BaseClass>(arr: T[]) => arr;
const usingHelperFunction: BaseClass[] = asBaseClassArray([
  { id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
  { id: "f", entityId: "g", entityName: "h", authorName: "i" },
  { id: "j", entityId: "k", entityName: "l", operationType: "m" }
]); // okay

Hope one of those ways gives you some direction.  Good luck!

<a href="https://typescript-play.js.org/#code/JYOwLgpgTgZghgYwgAgEJwM4QMIBtMbIDeAUMssACYBcyGYUoA5gNxnITjBgCeAkjToNmbcpzDceAOTgBbCLXqMQrEgF8SJUJFiIU2ABbBclPAQCMHAB6QQlQuixmMhUuQQB7WfPADFwlVFkOABXMAMPKBl5f2VVDS1waHgkZENjU3wXACZrW3s0TBws13ZQ8MjohSE4tgTtZL00oxNnDABmPM4Cx2KCYnYPAAdoOAkPEAAVHhHYkXVNTxB6ayQXAAUoYeheAFEoLagMWl62gG0AXWQAXmQz9iIKQQAiOGeAGg4uXj9kZ4AjD5fCS8Kq0Z4IIGebziX7PShA8oRKJyarPCDPZBqd4PJ7gmBA8SSOFMQnfaSo8EGRFhZFgv7ATHY3FUcEAKzJIP4LwA1pzJPTnrggdsoGNgBNprM-rImSQLixkAB6JUcA6RACEqwgLmQQy2IygvGQCAMEAQPMIcCgKH+3GYyBCGEWExWECsQ1wwAQ3FwPAAskSJgBlEL-BAlHW0MgAQQOcB4AB5TiVkAAfZoZNqWDPpVolXK5lqZAjtAB8NzuLJeb0+RJ+L0BdfJgshn2hPjAcIRnyRlUpfwxWJx5EerL+BObXJJ-NBA+e1N7tP7MQZTJHxDxfw5U+JvNnFNXQpFhvFkpmaNlWPlipVyA8PITLuWYBNxeztDzJZclluY5rB5wk2wICvObYml4nbdjSFQokeQ5qGwSwrKaWYFp+74FpW-74oBLykruc5HouwTLnBaKMliSGuq+qH5qWGFoaW2Fbs8O4gQ24J8oRh5osKnyimeUwXuCV6ISQyGvqAlDAAAblQIRwLguy4BAnbHIUTglJclZnHR34YOY7aYQQ2TGUxLjtAqyqqg+T4STRyBgAA7h4waQEMmweGshm6dW4K1hx3LgsB9a8eC4EdrCLw9qRsGCghG44ROeHggRQWCiRfbkeClHMqOrHsWFcLcRl878fep7jMJ0rPGJN4OS+Tmue5ECeVsPnZCcRTnFctwuW5HleT55i3rZj48JoDS6KkKYEAA6twBgAKogDyIAeM5IC7DYYpeYaEg6l0dgOD1qZuHcPJzCoFy0CEa0bVtdSNSs0nusGwBMCAYwhDa3VaQtS2retm3bbtcD7TswA6jptz3AV46vKlfyhS2YFQpB0XgrF2UJeu-kpTxM48ZlMF0vOeVJYVyPPKVYWChVgnVVKl5ytZd52ZNL2vpgc0uHGYo8JWiaTMdPRnQQZYABTWlAtCTJcACUNwVrL1FNU6zAABIQLghoAGL3Qg1X-X0Liw8EGB8xgAsJlL8ObojgXFY2B6thjMK+DFZMrmiiUE88k5BcTZXET7OVrsOAdFeSJVu+VJ6jMzIkymzitjfeE0kEAA" rel="nofollow noreferrer">Link to code