问:
OpenMP Nested For Loop Race Condition
I am having a race problem with the current situation. I am trying to create the amount of threads as there are cores, use locks on OMP. I have tried to do #pragma omp critical and also #pragma amp atomic and none of them are helping. I am getting some crazy negative numbers... I know how to do it using private, but I want to actually synchronize the threads, not create multiple variables for the threads and then combine at the end.

```<code>// multiplication
#pragma omp parallel for
for (i = 0; i < N; i++)
{
     for (j = 0; j < N; j++)
     {
          c[i][j] = 0.;
          for (k = 0; k < N; k++)
          {
               omp_set_lock(&lock);
               //#pragma omp critical
               //#pragma omp atomic
               c[i][j] += a[i][k] * b[k][j];
               threadTasks[omp_get_thread_num()]++;
               omp_unset_lock(&lock);
          }
          printf("[%d, %d]: Thread ID %d\n", i, j, omp_get_thread_num());
     }
}
</code>```

答:
For multiple nested loops with various operations, I will not use #pragma omp parallel for, instead I break down into #pragma omp parallel and #pragma omp for collapse(2).
See the full code below:

```<code>#pragma omp parallel
{
#pragma omp for collapse(2)
    for (i = 0; i < N; i++){
        for (j = 0; j < N; j++){
            c_parallel[i][j] = 0.;
            for (k = 0; k < N; k++) {
               c_parallel[i][j] += a_parallel[i][k] * b_parallel[k][j];
            }
        }
    }

}//end parallel region

</code>```

I am using vector< vector<float>> for the matrix and got 300% faster performance on i5 4 cores/Win10.

Title: OpenMP Nested For Loop Race Condition

Body:
I am having a race problem with the current situation. I am trying to create the amount of threads as there are cores, use locks on OMP. I have tried to do #pragma omp critical and also #pragma amp atomic and none of them are helping. I am getting some crazy negative numbers... I know how to do it using private, but I want to actually synchronize the threads, not create multiple variables for the threads and then combine at the end.

// multiplication
#pragma omp parallel for
for (i = 0; i < N; i++)
{
     for (j = 0; j < N; j++)
     {
          c[i][j] = 0.;
          for (k = 0; k < N; k++)
          {
               omp_set_lock(&lock);
               //#pragma omp critical
               //#pragma omp atomic
               c[i][j] += a[i][k] * b[k][j];
               threadTasks[omp_get_thread_num()]++;
               omp_unset_lock(&lock);
          }
          printf("[%d, %d]: Thread ID %d\n", i, j, omp_get_thread_num());
     }
}

Body:
For multiple nested loops with various operations, I will not use #pragma omp parallel for, instead I break down into #pragma omp parallel and #pragma omp for collapse(2).
See the full code below:

#pragma omp parallel
{
#pragma omp for collapse(2)
    for (i = 0; i < N; i++){
        for (j = 0; j < N; j++){
            c_parallel[i][j] = 0.;
            for (k = 0; k < N; k++) {
               c_parallel[i][j] += a_parallel[i][k] * b_parallel[k][j];
            }
        }
    }

}//end parallel region

I am using vector< vector<float>> for the matrix and got 300% faster performance on i5 4 cores/Win10.


来源: stackexchange

问:
SQL Delete feature does not function in table
I have three files connecting to each other, my issue is that my delete function does not seem to be working. I'd like to know what is missing in my "public function Delete_Lease($db) {" the codes are shown are shown below. Basically, I use a for each to display a table, the edit works with no problem but the delete just stays on the same page and has no effect.

Table Name: for_lease

Values: leaseid, lease_type, lease_name, lease_address, lease_price, lease_condition, lease_description, featured_photo, createddate

for_lease.php

```<code><?php
  session_start();
  require_once('for_lease.vc.php');
?>

 <?php foreach($lstProperty as $rowProperty) { ?>
       <tr align="center">
         <td>
          <a href="for_lease_edit.php?i=<?php echo($rowProperty['leaseid']); ?>"><input type="submit" class="btn bg-color-blue color-white form-control" name="edit" value="EDIT"></a>
         </td>

         <td>
           <?php
             echo($rowProperty['lease_name']);
           ?>
         </td>

         <td>
           <?php
             echo($rowProperty['lease_address']);
           ?>
         </td>

         <td>
           <?php
             echo($rowProperty['lease_type']);
           ?>
         </td>

         <td>
           <?php
             echo 'PHP'.' '.number_format(($rowProperty['lease_price']));
           ?>
         </td>

         <td>
           <?php
             echo($rowProperty['lease_condition']);
           ?>
         </td>

         <td>
           <?php
             echo( date("Y-m-d", strtotime($rowProperty['createddate']) ));
           ?>
         </td>

         <td>
           <a href="for_lease.php?delete=<?php echo($rowProperty['leaseid']); ?>" onclick="return confirm('Are you sure?');"><input type="submit" class="btn bg-color-red color-white form-control" name="delete" value="DELETE"></a>
         </td>
       </tr>
 <?php } ?>
</code>```

for_lease.vc.php

```<code><?php
  $routePath = "../";

  require_once($routePath . "_config/db.php");
    $dbConfig = new config_db();
    $db = $dbConfig->init();

  require_once($routePath . "_mc/Property.mc.php");

  $mcProperty = new Property_MC();

  $lstProperty = $mcProperty->SelectObj_ByLeaseId($db);

  if (isset($_GET['delete'])){
    $rowProperty = $mcProperty->Delete_Lease($db);
  }
?>
</code>```

Property.mc.php

```<code><?php
Class Property_MC {

  public function SelectObj_ByLeaseId($db) {
  $stmt = $db->prepare(
    " SELECT leaseid, lease_type, lease_name, lease_address, lease_price, lease_condition, lease_description, createddate
      FROM for_lease"
  );

  $stmt->execute();
  $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

  return $row;
  }

  public function Delete_Lease($db) {
  $stmt = $db->prepare(
    " DELETE * FROM
        for_lease
      WHERE
        leaseid = :leaseid "
  );
  }

} ?>
</code>```

答:
You're not executing the sql statement, you are only preparing it. Also, the way you're code is setup, you will need to pass the leaseid to your delete function.

Try this.

for_lease.vc.php

```<code><?php
  $routePath = "../";

  require_once($routePath . "_config/db.php");
    $dbConfig = new config_db();
    $db = $dbConfig->init();

  require_once($routePath . "_mc/Property.mc.php");

  $mcProperty = new Property_MC();

  $lstProperty = $mcProperty->SelectObj_ByLeaseId($db);

  if (isset($_GET['delete'])){
    $rowProperty = $mcProperty->Delete_Lease($db, $_GET['delete']);
  }
?>
</code>```

Property.mc.php

```<code> public function Delete_Lease($db, $leaseid) {
  $stmt = $db->prepare(
    " DELETE FROM
        for_lease
      WHERE
        leaseid = :leaseid "
  );

  $stmt->execute([':leaseid' => $leaseid]);

  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three files connecting to each other, my issue is that my delete function does not seem to be working. I'd like to know what is missing in my "public function Delete_Lease($db) {" the codes are shown are shown below. Basically, I use a for each to display a table, the edit works with no problem but the delete just stays on the same page and has no effect.

Table Name: for_lease

Values: leaseid, lease_type, lease_name, lease_address, lease_price, lease_condition, lease_description, featured_photo, createddate

for_lease.php

<?php
  session_start();
  require_once('for_lease.vc.php');
?>

 <?php foreach($lstProperty as $rowProperty) { ?>

          <a href="for_lease_edit.php?i=<?php echo($rowProperty['leaseid']); ?>"><input type="submit" class="btn bg-color-blue color-white form-control" name="edit" value="EDIT">

           <?php
             echo($rowProperty['lease_name']);
           ?>

           <?php
             echo($rowProperty['lease_address']);
           ?>

           <?php
             echo($rowProperty['lease_type']);
           ?>

           <?php
             echo 'PHP'.' '.number_format(($rowProperty['lease_price']));
           ?>

           <?php
             echo($rowProperty['lease_condition']);
           ?>

           <?php
             echo( date("Y-m-d", strtotime($rowProperty['createddate']) ));
           ?>

           <a href="for_lease.php?delete=<?php echo($rowProperty['leaseid']); ?>" onclick="return confirm('Are you sure?');"><input type="submit" class="btn bg-color-red color-white form-control" name="delete" value="DELETE">

 <?php } ?>

for_lease.vc.php

<?php
  $routePath = "../";

  require_once($routePath . "_config/db.php");
    $dbConfig = new config_db();
    $db = $dbConfig->init();

  require_once($routePath . "_mc/Property.mc.php");

  $mcProperty = new Property_MC();

  $lstProperty = $mcProperty->SelectObj_ByLeaseId($db);

  if (isset($_GET['delete'])){
    $rowProperty = $mcProperty->Delete_Lease($db);
  }
?>

Property.mc.php

<?php
Class Property_MC {

  public function SelectObj_ByLeaseId($db) {
  $stmt = $db->prepare(
    " SELECT leaseid, lease_type, lease_name, lease_address, lease_price, lease_condition, lease_description, createddate
      FROM for_lease"
  );

  $stmt->execute();
  $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

  return $row;
  }

  public function Delete_Lease($db) {
  $stmt = $db->prepare(
    " DELETE * FROM
        for_lease
      WHERE
        leaseid = :leaseid "
  );
  }

} ?>

Body:
You're not executing the sql statement, you are only preparing it. Also, the way you're code is setup, you will need to pass the leaseid to your delete function.

Try this.

for_lease.vc.php

<?php
  $routePath = "../";

  require_once($routePath . "_config/db.php");
    $dbConfig = new config_db();
    $db = $dbConfig->init();

  require_once($routePath . "_mc/Property.mc.php");

  $mcProperty = new Property_MC();

  $lstProperty = $mcProperty->SelectObj_ByLeaseId($db);

  if (isset($_GET['delete'])){
    $rowProperty = $mcProperty->Delete_Lease($db, $_GET['delete']);
  }
?>

Property.mc.php

 public function Delete_Lease($db, $leaseid) {
  $stmt = $db->prepare(
    " DELETE FROM
        for_lease
      WHERE
        leaseid = :leaseid "
  );

  $stmt->execute([':leaseid' => $leaseid]);

  }


问:
How to redirect my user after posting a comment
So I just learned how to add comments on my blog. Now the problem is that I can't redirect my user to the concerned blog post. That's really frustrating because I see a lot of people on the Internet talking about get_absolute_url and it confuses me a lot. </p>

```<code>from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Annonce, Comments
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)
</code>```

答:
You are correct that you can use a get_absolute_url [Django-doc] here. You can add such method to a model, for example:

```<code># app/models.py

from django.db import models
from django.urls import <b>reverse</b>

class Annonce(models.Model):

    # ...

    def <b>get_absolute_url</b>(self):
        return reverse('annonce_detail', kwargs={'pk': self.pk})</code>```

Here annonce_detail is the name of a hypothetical view, so in your urls.py, we then have a path like:

```<code># app/urls.py

from django.urls import path
from app import views

urlpatterns = [
    path('annonce/<int:pk>', views.annonce_detail, name=<b>'annonce_detail'</b>),
    # ...
]</code>```

This means that for a given Annonce object, we can ask some_annonce.get_absolute_url(), and it will respond with something like /annonce/123.

Now redirect [Django-doc] takes model objects with a get_absolute_url into account. Indeed, as the documentation says:

Returns an HttpResponseRedirect to the appropriate URL for the
  arguments passed.

The arguments could be:

A model: the model's get_absolute_url() function will be called.

A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.

An absolute or relative URL, which will be used as-is for the redirect location.

By default issues a temporary redirect; pass permanent=True to issue
  a permanent redirect.

If you thus have defined such get_absolute_url on that model, you can pass that object to redirect, like:

```<code>def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return <b>redirect(annonce)</b>

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)</code>```

Note: models typically have singular names, so Comment, not Comments.

Note: you might want to consider working with forms [Django-doc] since the given input is not per se valid, and a form can do proper validation, as well as removing a lot of boilerplate code.

Body:
So I just learned how to add comments on my blog. Now the problem is that I can't redirect my user to the concerned blog post. That's really frustrating because I see a lot of people on the Internet talking about get_absolute_url and it confuses me a lot.

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Annonce, Comments
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)

Body:
You are correct that you can use a get_absolute_url [Django-doc] here. You can add such method to a model, for example:

# app/models.py

from django.db import models
from django.urls import reverse

class Annonce(models.Model):

    # ...

    def get_absolute_url(self):
        return reverse('annonce_detail', kwargs={'pk': self.pk})

Here annonce_detail is the name of a hypothetical view, so in your urls.py, we then have a path like:

# app/urls.py

from django.urls import path
from app import views

urlpatterns = [
    path('annonce/<int:pk>', views.annonce_detail, name='annonce_detail'),
    # ...
]

This means that for a given Annonce object, we can ask some_annonce.get_absolute_url(), and it will respond with something like /annonce/123.

Now redirect [Django-doc] takes model objects with a get_absolute_url into account. Indeed, as the documentation says:

Returns an HttpResponseRedirect to the appropriate URL for the
  arguments passed.

The arguments could be:

A model: the model's get_absolute_url() function will be called.

A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.

An absolute or relative URL, which will be used as-is for the redirect location.

By default issues a temporary redirect; pass permanent=True to issue
  a permanent redirect.

If you thus have defined such get_absolute_url on that model, you can pass that object to redirect, like:

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)

Note: models typically have singular names, so Comment, not Comments.

Note: you might want to consider working with forms [Django-doc] since the given input is not per se valid, and a form can do proper validation, as well as removing a lot of boilerplate code.


问:
How to skip option values and return first some
I have a list of options, i want to skip none values and return the first some.

```<code>val list = List(None, None, None, Some(3));

list.dropWhile(!_.exists).take(1) // return 3
</code>```

Actually it's like this:

```<code>val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.dropWhile(!solve(_).isDefined).take(1) // returns the result of solve method
</code>```

and I need solve functions to be called once for each None results, and once for the last Some result.

答:
like this:</p>

```<code>def solve(hand: Hand): HandValue = all.foldLeft[Option[HandValue]](None) {
  case (None, solver) => solver.solve(hand)
  case (Some(value), _) => Some(value)
} get
</code>```

Body:
I have a list of options, i want to skip none values and return the first some.

val list = List(None, None, None, Some(3));

list.dropWhile(!_.exists).take(1) // return 3

Actually it's like this:

val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.dropWhile(!solve(_).isDefined).take(1) // returns the result of solve method

and I need solve functions to be called once for each None results, and once for the last Some result.

Body:
like this:

def solve(hand: Hand): HandValue = all.foldLeft[Option[HandValue]](None) {
  case (None, solver) => solver.solve(hand)
  case (Some(value), _) => Some(value)
} get


答:
```<code>def takeFirst[T](list : List[Option[T]]): Option[T] = list.find(_.isDefined).flatten
</code>```

Title: How to skip option values and return first some


答:
Delete_Lease is missing binding and execution as well as what lease id to delete.
the sql for delete does not need the "*".

Property.mc.php

```<code>public function Delete_Lease($db, $leaseid) {
    $stmt = $db->prepare(
        "DELETE FROM
        for_lease
        WHERE
        leaseid = :leaseid "
        );
    $stmt->execute(['leaseid' => $leaseid]);
}
</code>```

for_lease.vc.php

```<code>if (isset($_GET['delete'])){
    $rowProperty = $mcProperty->Delete_Lease($db, $_GET['leaseid']);
}
</code>```

fix delete button that overwrites delete id in for_lease.php

```<code><td>
    <a href="for_lease.php?leaseid=<?php echo($rowProperty['leaseid']); ?>" onclick="return confirm('Are you sure?');"><input type="submit" class="btn bg-color-red color-white form-control" name="delete" value="DELETE"></a>
</td>
</code>```

Title: SQL Delete feature does not function in table

Body:
Delete_Lease is missing binding and execution as well as what lease id to delete.
the sql for delete does not need the "*".

Property.mc.php

public function Delete_Lease($db, $leaseid) {
    $stmt = $db->prepare(
        "DELETE FROM
        for_lease
        WHERE
        leaseid = :leaseid "
        );
    $stmt->execute(['leaseid' => $leaseid]);
}

for_lease.vc.php

if (isset($_GET['delete'])){
    $rowProperty = $mcProperty->Delete_Lease($db, $_GET['leaseid']);
}

fix delete button that overwrites delete id in for_lease.php

<td>
    <a href="for_lease.php?leaseid=<?php echo($rowProperty['leaseid']); ?>" onclick="return confirm('Are you sure?');"><input type="submit" class="btn bg-color-red color-white form-control" name="delete" value="DELETE"></a>
</td>


问:
Having different output item numbers on different ports gnuradio
I have a block which has two output ports in gnuradio. I need to return a single items to one output port and some specific n output items on another output port. Is this possible or always it returns same number of items on different ports</p>

答:
It's possible. gr::block has a method called produce(int,int) to allow you to do exactly that. You'll have to return WORK_CALLED_PRODUCE instead of returning a  number of samples.

Of course, not producing the same amount on all outputs means that you can't use sync_block and quite likely will have to implement a forecast() too.


问:
Using async/await with a forEach loop
Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.

```<code>import fs from 'fs-promise'

async function printFiles () {
  const files = await getFilePaths() // Assume this works fine

  files.forEach(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  })
}

printFiles()
</code>```

This code does work, but could something go wrong with this? I had someone tell me that you're not supposed to use async/await in a higher-order function like this, so I just wanted to ask if there was any issue with this.

答:
Bergi's solution works nicely when fs is promise based.
You can use bluebird, fs-extra or fs-promise for this.

However, solution for node's native fs libary is as follows:

```<code>const result = await Promise.all(filePaths
    .map( async filePath => {
      const fileContents = await getAssetFromCache(filePath, async function() {

        // 1. Wrap with Promise
        // 2. Return the result of the Promise
        return await new Promise((res, rej) => {
          fs.readFile(filePath, 'utf8', function(err, data) {
            if (data) {
              res(data);
            }
          });
        });
      });

      return fileContents;
    }));
</code>```

Note:
require('fs') compulsorily takes function as 3rd arguments, otherwise throws error:

```<code>TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
</code>```

Title: Using async/await with a forEach loop

Body:
Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.

import fs from 'fs-promise'

async function printFiles () {
  const files = await getFilePaths() // Assume this works fine

  files.forEach(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  })
}

printFiles()

This code does work, but could something go wrong with this? I had someone tell me that you're not supposed to use async/await in a higher-order function like this, so I just wanted to ask if there was any issue with this.

Body:
Bergi's solution works nicely when fs is promise based.
You can use bluebird, fs-extra or fs-promise for this.

However, solution for node's native fs libary is as follows:

const result = await Promise.all(filePaths
    .map( async filePath => {
      const fileContents = await getAssetFromCache(filePath, async function() {

        // 1. Wrap with Promise
        // 2. Return the result of the Promise
        return await new Promise((res, rej) => {
          fs.readFile(filePath, 'utf8', function(err, data) {
            if (data) {
              res(data);
            }
          });
        });
      });

      return fileContents;
    }));

Note:
require('fs') compulsorily takes function as 3rd arguments, otherwise throws error:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function


问:
How to make my wpf app wait for 3 minutes before re-loading data?
I am using VS2010 - WPF - C#

in my application I fetch data from a web server and view it on my interface
the problem is that I want to keep fetching data and keep refreshing my interface every 3 minutes but I don't know how to do that...

I tried (Thread.Sleep(18000)) and it didn't work because my interface wouldn't show at all

I don't know how to use the Timer for such reason and I couldn't find what I'm looking for elsewhere

Please can you help me with it ?

Best Regards

答:
What programming model? Stock or something more sane with a MVVM approach?

Anyhow, use a TIMER to request a callback after 3 minutes. In the callback invoke back to the dispatcher thread of the window once you got the results of the web service call. Finished.

ContentLicense: CC BY-SA 3.0


问:
How to get input from text entry after destroying window
im new to this site (and Python) and this is my first post so im sorry if something is not clear. Basically, im trying to write a code that simulates a lottery. For this, i use tkinter and text-entry to fill in numbers. The problem appears when i destroy the input-window, where the guessed numbers are not saved. My question is, how do i destroy my window and get the input from the text-entry?

I've tried using IntVar without success, not sure if i understood it correctly.

from tkinter import*
import random

Part1 = list(range(1,51))
Part2 = list(range(1,11))

Numbers = [0]*7

for n in range (5):
    Number = random.choice(Part1)

    Position = Part1.index(Number)
    del Part1[Position]

    Numbers[n] = Number

for i in range (2):
    Number = random.choice(Part2)

    Position = Part2.index(Number)
    del Part2[Position]

    Numbers[5+i] = Number

print (Numbers)

def master1_quit():
    master1.destroy()

# def window():

master1 = Tk()

Label(master1, text="Guess numbers:").grid(row=0)

e1 = Text(master1, width=2, height=1)
e2 = Text(master1, width=2, height=1)
e3 = Text(master1, width=2, height=1)
e4 = Text(master1, width=2, height=1)
e5 = Text(master1, width=2, height=1)
e6 = Text(master1, width=2, height=1)
e7 = Text(master1, width=2, height=1)

e1.grid(row=0, column=1, padx=5)
e2.grid(row=0, column=2, padx=5)
e3.grid(row=0, column=3, padx=5)
e4.grid(row=0, column=4, padx=5)
e5.grid(row=0, column=5, padx=5)
e6.grid(row=0, column=7, padx=5)
e7.grid(row=0, column=8, padx=5)

master1.grid_columnconfigure(6, minsize=20) # Creates an empty column (nr. 6) with width 20

# Save guessed numbers
Guess = [e1.get(1.0, "end-1c"), e2.get(1.0, "end-1c"), e3.get(1.0, "end-1c"), e4.get(1.0, "end-1c"), e5.get(1.0, "end-1c"), e6.get(1.0, "end-1c"), e7.get(1.0, "end-1c")]

Button(master1, text='OK', command=master1_quit).grid(row=3, column=3, sticky=W, pady=5)

master1.mainloop()

# window()
```

Basically i want the variable "Guess" to be saved after the window is destroyed because i want to use it later.

Extra question:
Is it possible to write "def window()" and call the window with "window()" later in the code?

答:
Welcome to Stackoverflow and thanks for the clear question.

If you change the master1_quit function to update the global variable Guess as the window exits, Guess will show the final state of the 7 Text widgets, example below.  In your code Guess is filled from the 7 Text widgets as the UI is created.  At that point all the Text fields are empty.

```<code>def master1_quit():
    global Guess
    Guess = [e1.get(1.0, "end-1c"), e2.get(1.0, "end-1c"), e3.get(1.0, "end-1c"),
             e4.get(1.0, "end-1c"), e5.get(1.0, "end-1c"), e6.get(1.0, "end-1c"),
             e7.get(1.0, "end-1c")]
    master1.destroy()
</code>```

For such simple data you may find Entry widgets easier than Text widgets.  You can use e1.get() to recover the text in an Entry widget, with no parameters to worry about.

Body:
im new to this site (and Python) and this is my first post so im sorry if something is not clear. Basically, im trying to write a code that simulates a lottery. For this, i use tkinter and text-entry to fill in numbers. The problem appears when i destroy the input-window, where the guessed numbers are not saved. My question is, how do i destroy my window and get the input from the text-entry?

I've tried using IntVar without success, not sure if i understood it correctly.

from tkinter import*
import random

Part1 = list(range(1,51))
Part2 = list(range(1,11))

Numbers = [0]*7

for n in range (5):
    Number = random.choice(Part1)

    Position = Part1.index(Number)
    del Part1[Position]

    Numbers[n] = Number

for i in range (2):
    Number = random.choice(Part2)

    Position = Part2.index(Number)
    del Part2[Position]

    Numbers[5+i] = Number

print (Numbers)

def master1_quit():
    master1.destroy()

# def window():

master1 = Tk()

Label(master1, text="Guess numbers:").grid(row=0)

e1 = Text(master1, width=2, height=1)
e2 = Text(master1, width=2, height=1)
e3 = Text(master1, width=2, height=1)
e4 = Text(master1, width=2, height=1)
e5 = Text(master1, width=2, height=1)
e6 = Text(master1, width=2, height=1)
e7 = Text(master1, width=2, height=1)

e1.grid(row=0, column=1, padx=5)
e2.grid(row=0, column=2, padx=5)
e3.grid(row=0, column=3, padx=5)
e4.grid(row=0, column=4, padx=5)
e5.grid(row=0, column=5, padx=5)
e6.grid(row=0, column=7, padx=5)
e7.grid(row=0, column=8, padx=5)

master1.grid_columnconfigure(6, minsize=20) # Creates an empty column (nr. 6) with width 20

# Save guessed numbers
Guess = [e1.get(1.0, "end-1c"), e2.get(1.0, "end-1c"), e3.get(1.0, "end-1c"), e4.get(1.0, "end-1c"), e5.get(1.0, "end-1c"), e6.get(1.0, "end-1c"), e7.get(1.0, "end-1c")]

Button(master1, text='OK', command=master1_quit).grid(row=3, column=3, sticky=W, pady=5)

master1.mainloop()

# window()

Basically i want the variable "Guess" to be saved after the window is destroyed because i want to use it later.

Extra question:
Is it possible to write "def window()" and call the window with "window()" later in the code?

Body:
Welcome to Stackoverflow and thanks for the clear question.

If you change the master1_quit function to update the global variable Guess as the window exits, Guess will show the final state of the 7 Text widgets, example below.  In your code Guess is filled from the 7 Text widgets as the UI is created.  At that point all the Text fields are empty.

def master1_quit():
    global Guess
    Guess = [e1.get(1.0, "end-1c"), e2.get(1.0, "end-1c"), e3.get(1.0, "end-1c"),
             e4.get(1.0, "end-1c"), e5.get(1.0, "end-1c"), e6.get(1.0, "end-1c"),
             e7.get(1.0, "end-1c")]
    master1.destroy()

For such simple data you may find Entry widgets easier than Text widgets.  You can use e1.get() to recover the text in an Entry widget, with no parameters to worry about.


问:
Pivot/unstack a DataFrame with duplicate entries without aggregation
So I got a DataFrame as follow:

```<code>        Col_0 Col_1
Index_1
      A     0     2
      A     3     1
      A     2     2
      B     3     1
      B     4     3
      B     5     1
</code>```

And I would like to reshape to it into following format:

```<code>    Col_0     Col_1
    A    B    A    B
    0    3    2    1
    3    4    1    3
    2    5    2    1
</code>```

I've try pandas.pivot, pandas.unstack, pandas.groupby. None of it worked. Can anyone help me out with it? Much appreciated.

答:
Create the index with cumcount then pivot:

```<code>df['idx'] = df.groupby(df.index).cumcount()
df.reset_index().pivot(index='idx', columns='Index_1').rename_axis(None)
</code>```

Output:

```<code>        Col_0    Col_1
Index_1     A  B     A  B
0           0  3     2  1
1           3  4     1  3
2           2  5     2  1
</code>```

Body:
So I got a DataFrame as follow:

        Col_0 Col_1
Index_1
      A     0     2
      A     3     1
      A     2     2
      B     3     1
      B     4     3
      B     5     1

And I would like to reshape to it into following format:

    Col_0     Col_1
    A    B    A    B
    0    3    2    1
    3    4    1    3
    2    5    2    1

I've try pandas.pivot, pandas.unstack, pandas.groupby. None of it worked. Can anyone help me out with it? Much appreciated.

Body:
Create the index with cumcount then pivot:

df['idx'] = df.groupby(df.index).cumcount()
df.reset_index().pivot(index='idx', columns='Index_1').rename_axis(None)

Output:

        Col_0    Col_1
Index_1     A  B     A  B
0           0  3     2  1
1           3  4     1  3
2           2  5     2  1


问:
Who remember the algorithm to pack 4-bytes integer to array of 1-to-4 bytes depending from number of significant digits?
I need an efficient algorithm or idea to pack 4-bytes integers to as short as possible byte arrays. For example, I can pack values from 0x00000000 to 0x0000007f to the one-byte array, just assuming that the bit7=0 means 1-byte length.
If I have the number from 128 and longer, I need to invent smarter things to pack to 2-bytes array, 3-bytes array, etc.

Who remembers this algorithm? Please share.

答:
Variable Length Quantity: https://en.wikipedia.org/wiki/Variable-length_quantity

It's also used by UTF-8.


问:
remove spaces between fields of lines in Unix
When I do a desc hive table like below on a Linux terminal CLI.

```<code>hive -e "desc hive_db.hive_table"
</code>```

I get the following output

```<code>date                string
entity              string
key                 int
id                  string
direction           string
indicator           string
account_number      string
document_date       string
</code>```

Now I want to redirect the output to a file before doing it I want to remove the spaces between each fields and have just one space between them.

The expected output is below

```<code>date string
entity string
key int
id string
direction string
indicator string
account_number string
document_date string
</code>```

I have tried like below

```<code>hive -e "desc hive_db.hive_table" | tr -s " " > abc.txt
</code>```

The output I get is

```<code>date    string
entity  string
key     int
id  string
direction   string
indicator   string
account_number  string
document_date   string
</code>```

Th output I get is a close one but I have one space and one tab between each fields in each line

How can I achieve what I want?

答:
Try:

```<code>hive -e "desc hive_db.hive_table" | sed -E 's/[[:space:]]+/ /' > abc.txt
</code>```

[[:space:]]+ matches one or more of any kind of white space (tab, blank, or other including any unicode-defined white space).  s/[[:space:]]+/ / replaces that sequence of white space with a single blank.

Body:
When I do a desc hive table like below on a Linux terminal CLI.

hive -e "desc hive_db.hive_table"

I get the following output

date                string
entity              string
key                 int
id                  string
direction           string
indicator           string
account_number      string
document_date       string

Now I want to redirect the output to a file before doing it I want to remove the spaces between each fields and have just one space between them.

The expected output is below

date string
entity string
key int
id string
direction string
indicator string
account_number string
document_date string

I have tried like below

hive -e "desc hive_db.hive_table" | tr -s " " > abc.txt

The output I get is

date    string
entity  string
key     int
id  string
direction   string
indicator   string
account_number  string
document_date   string

Th output I get is a close one but I have one space and one tab between each fields in each line

How can I achieve what I want?

Body:
Try:

hive -e "desc hive_db.hive_table" | sed -E 's/[[:space:]]+/ /' > abc.txt

[[:space:]]+ matches one or more of any kind of white space (tab, blank, or other including any unicode-defined white space).  s/[[:space:]]+/ / replaces that sequence of white space with a single blank.


问:
Debug Assertion Failed in for
I got an error on second if

Making the exactly same if outside of for seems to work just fine, it returns the value from priority function, but when I try to do it in for it said that I'm trying to pass an invalid parameter to a function which considers it to be fatal.

```<code>#include <iostream>
#include <stack>
#include <string>
using namespace std;

int priority(char c);

int main()
{
stack<char>Operator;
string input;
string output;
getline(cin, input);
for (int i = 0; i < input.size(); i++)
{
    if (input[i] == '(' || input[i] == ')' || input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/')
        Operator.push(input[i]);
    else
        output.push_back(input[i]);
    if (priority(Operator.top()) == 3)
    {
        int aux = Operator.top();
        Operator.pop();
        while (priority(Operator.top() == 4))
        {
            output.push_back((char)Operator.top());
            Operator.pop();
        }
        Operator.push(aux);
    }
    if (priority(Operator.top() == 2))
    {
        Operator.pop();
        while (priority(Operator.top()) != 1)
        {
            output.push_back(Operator.top());
            Operator.pop();
        }
        Operator.pop();
    }
}
cout << output;
cin.ignore();
cin.get();
return 0;
}

int priority(char c)
{
if (c == '(')
    return 1;
if (c == ')')
    return 2;
if (c == '+' || c == '-')
    return 3;
if (c == '*' || c == '/')
    return 4;
}
</code>```

答:
The statement Operator.top() is being called on every symbol in the input string. That would probably work in case your string starts with a '(' symbol or with a unary plus, but what would happen in case of "2*2"?

As a perfect solution you should redesign your code to make it a finit automaton. As a simple ad hoc fix you should check if the current symbol is an operation or digit and don't call the Operator.top() in the latter case:

```<code>if (isdigit(input[i])) {
    output.push_back(input[i]);
}
else {
    Operator.push(input[i]);
    if (priority(Operator.top()) == 3) {
        // ...
    }
    // ...
}
</code>```

Title: Debug Assertion Failed in for

Body:
I got an error on second if

Making the exactly same if outside of for seems to work just fine, it returns the value from priority function, but when I try to do it in for it said that I'm trying to pass an invalid parameter to a function which considers it to be fatal.

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int priority(char c);

int main()
{
stack<char>Operator;
string input;
string output;
getline(cin, input);
for (int i = 0; i < input.size(); i++)
{
    if (input[i] == '(' || input[i] == ')' || input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/')
        Operator.push(input[i]);
    else
        output.push_back(input[i]);
    if (priority(Operator.top()) == 3)
    {
        int aux = Operator.top();
        Operator.pop();
        while (priority(Operator.top() == 4))
        {
            output.push_back((char)Operator.top());
            Operator.pop();
        }
        Operator.push(aux);
    }
    if (priority(Operator.top() == 2))
    {
        Operator.pop();
        while (priority(Operator.top()) != 1)
        {
            output.push_back(Operator.top());
            Operator.pop();
        }
        Operator.pop();
    }
}
cout << output;
cin.ignore();
cin.get();
return 0;
}

int priority(char c)
{
if (c == '(')
    return 1;
if (c == ')')
    return 2;
if (c == '+' || c == '-')
    return 3;
if (c == '*' || c == '/')
    return 4;
}

Body:
The statement Operator.top() is being called on every symbol in the input string. That would probably work in case your string starts with a '(' symbol or with a unary plus, but what would happen in case of "2*2"?

As a perfect solution you should redesign your code to make it a finit automaton. As a simple ad hoc fix you should check if the current symbol is an operation or digit and don't call the Operator.top() in the latter case:

if (isdigit(input[i])) {
    output.push_back(input[i]);
}
else {
    Operator.push(input[i]);
    if (priority(Operator.top()) == 3) {
        // ...
    }
    // ...
}


问:
Multiple Ace Editor content returns only one line
I have implemented two ACE editors on my single page. The first editor:

```<code>$('#custom_css').val(custom_css_editor.getSession().getValue());
</code>```

returns all the codes I've typed, but unfortunately the other editor:

```<code>$('#custom_script').val(custom_js_editor.getSession().getValue());
</code>```

returns only one line. What do you think is the cause of such glitch?

Here's what I want to show up:

Here are the codes I have:

var custom_css_editor = ace.edit("custom_css_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/css",
  maxLines: 10
});
var custom_js_editor = ace.edit("custom_js_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/javascript",
  maxLines: 10
});

document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('name', 'custom_css');
document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('id', 'custom_css');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('name', 'custom_script');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('id', 'custom_script');

custom_css_editor.session.on('change', function() {
  $('#custom_css').val(custom_css_editor.getValue());
});
$('#custom_css').val(custom_css_editor.session.getValue());
custom_js_editor.getSession().on('change', function() {
  $('#custom_script').val(custom_js_editor.getValue());
});
$('#custom_script').val(custom_js_editor.session.getValue());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
  <label class="lbl-input" for="custom_css">Custom CSS</label>
  <div id="custom_css_editor"></div>
</div>
<div class="form-group">
  <label class="lbl-input" for="custom_script">Custom Scripts</label>
  <div id="custom_js_editor"></div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.4/ace.js"></script></code>```

答: This happens because you are modifying the value of textarea .ace_text-input. Changing dom inside editor usually breaks it.

Body:
I have implemented two ACE editors on my single page. The first editor:

$('#custom_css').val(custom_css_editor.getSession().getValue());

returns all the codes I've typed, but unfortunately the other editor:

$('#custom_script').val(custom_js_editor.getSession().getValue());

returns only one line. What do you think is the cause of such glitch?

Here's what I want to show up:

Here are the codes I have:

var custom_css_editor = ace.edit("custom_css_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/css",
  maxLines: 10
});
var custom_js_editor = ace.edit("custom_js_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/javascript",
  maxLines: 10
});

document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('name', 'custom_css');
document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('id', 'custom_css');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('name', 'custom_script');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('id', 'custom_script');

custom_css_editor.session.on('change', function() {
  $('#custom_css').val(custom_css_editor.getValue());
});
$('#custom_css').val(custom_css_editor.session.getValue());
custom_js_editor.getSession().on('change', function() {
  $('#custom_script').val(custom_js_editor.getValue());
});
$('#custom_script').val(custom_js_editor.session.getValue());

  Custom CSS

  Custom Scripts


问:
Optimal 2D bin packing
Given a set of rectangles of various sizes (items) and a set of rectangles of identical sizes (bins), place items into as few bins as possible.

I'm aware of A Thousand Ways to Pack the Bin but I was wondering, if the number of items was suitably small and perhaps the dimensions were integers, is there a way to always pack the items optimally? Is anyone aware of a strategy or algorithm for optimal rectangle bin packing?

答: Have a look at the survey of Lodi et al. on two-dimensional bin packing problems which has a section on exact algorithms. For a very small number of items you may be able to solve the problem using integer programming models, for larger sizes you will likely need a tailored tree search or branch-and-bound algorithm. An example is the article of Pisinger & Sigurd which uses a Dantzig-Wolfe decomposition and relies on constraint programming to pack individual bins, and are able to solve problems with about 100 items.</p>

Title: Optimal 2D bin packing


问:
How to fix "Configuration system failed to initialize/Root element is missing" error when loading config file?
I got this error in my c# windows application: "Configuration system failed to initialize".

It was working fine. Suddenly I got this exception. It shows inner exception detail as "Root element is missing". (C:\Users\company\AppData\Local\Clickbase_Corp_Sverige_AB\TouchStation.vshost.exe_Url_no1nets4fg3oy2p2q2pnwgulbvczlv33\1.1.0.12\user.config)"}.This happens when I try to get values from Settings.cs class.

In program.cs file the below code is written

```<code>if (Properties.Settings.Default.CallUpgrade)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.CallUpgrade = false;
                Properties.Settings.Default.Save();
            }
</code>```

And calls settings.cs class where the below code throws above exception

```<code>    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("True")]

    public bool CallUpgrade {
        get {
            return ((bool)(this["CallUpgrade"]));
        }
        set {
            this["CallUpgrade"] = value;
        }
    }
</code>```

The below is my entire app.config

<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>

  </configSections>
  <appSettings>
    <add key="WebRoot" value="webroot" />
    <add key="TempDir" value="temp" />
    <add key="ServerPort" value="9338" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <userSettings>
    <TouchStation.Properties.Settings>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value>0000</value>
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>10</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
      <setting name="AutoStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DemoMode" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="UnlockPassword" serializeAs="String">
        <value>needle</value>
      </setting>
      <setting name="SynchronizerUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="SynchronizerPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="RunClientApplications" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="MapID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="ServerName" serializeAs="String">
        <value />
      </setting>
      <setting name="CallUpgrade" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="ServerPort" serializeAs="String">
        <value>9338</value>
      </setting>
    </TouchStation.Properties.Settings>
    <TouchStation.TouchStation>
      <setting name="ServerURL" serializeAs="String">
        <value />
      </setting>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value />
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="HideMouse" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="HideDesktopOnStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="LogServerPort" serializeAs="String">
        <value>9050</value>
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </userSettings>
  <applicationSettings>
    <TouchStation.TouchStation>
      <setting name="ClientSettingsURL" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </applicationSettings>
  <SitesInfo>
    <sites>
      <site Name="Local" FullName="Local Site" DatabaseConnectionString="Data\local.db" />
    </sites>
  </SitesInfo>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>
```

can anyone help me in this?

Thank You.

Regards,

jennie

答:
The cause of the XmlException entitled Root element is missing means the XML document  (The config file here) you're trying to load is not formatted properly, more exactly it's missing the root node.

Each XML file must have a root element / node which encloses all the other elements.

Your file must look like the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings"
            type="System.Configuration.UserSettingsGroup, System,
            Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        </sectionGroup>
    </configSections>
    <userSettings>
        <WindowsFormsApplication.Properties.Settings>
        </WindowsFormsApplication.Properties.Settings>
    </userSettings>
</configuration>
```

Body:
I got this error in my c# windows application: "Configuration system failed to initialize".

It was working fine. Suddenly I got this exception. It shows inner exception detail as "Root element is missing". (C:\Users\company\AppData\Local\Clickbase_Corp_Sverige_AB\TouchStation.vshost.exe_Url_no1nets4fg3oy2p2q2pnwgulbvczlv33\1.1.0.12\user.config)"}.This happens when I try to get values from Settings.cs class.

In program.cs file the below code is written

if (Properties.Settings.Default.CallUpgrade)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.CallUpgrade = false;
                Properties.Settings.Default.Save();
            }

And calls settings.cs class where the below code throws above exception

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("True")]

    public bool CallUpgrade {
        get {
            return ((bool)(this["CallUpgrade"]));
        }
        set {
            this["CallUpgrade"] = value;
        }
    }

The below is my entire app.config

<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>

  </configSections>
  <appSettings>
    <add key="WebRoot" value="webroot" />
    <add key="TempDir" value="temp" />
    <add key="ServerPort" value="9338" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <userSettings>
    <TouchStation.Properties.Settings>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value>0000</value>
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>10</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
      <setting name="AutoStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DemoMode" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="UnlockPassword" serializeAs="String">
        <value>needle</value>
      </setting>
      <setting name="SynchronizerUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="SynchronizerPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="RunClientApplications" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="MapID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="ServerName" serializeAs="String">
        <value />
      </setting>
      <setting name="CallUpgrade" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="ServerPort" serializeAs="String">
        <value>9338</value>
      </setting>
    </TouchStation.Properties.Settings>
    <TouchStation.TouchStation>
      <setting name="ServerURL" serializeAs="String">
        <value />
      </setting>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value />
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="HideMouse" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="HideDesktopOnStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="LogServerPort" serializeAs="String">
        <value>9050</value>
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </userSettings>
  <applicationSettings>
    <TouchStation.TouchStation>
      <setting name="ClientSettingsURL" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </applicationSettings>
  <SitesInfo>
    <sites>
      <site Name="Local" FullName="Local Site" DatabaseConnectionString="Data\local.db" />
    </sites>
  </SitesInfo>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

can anyone help me in this?

Thank You.

Regards,

jennie


问:
How to keep WIndows Container running?
I need to keep my Windows Container up so I can run further commands on it using docker exec.

On Linux, I'd start it to run either sleep infinity, or tail -f /dev/null. Alternatively, I could borrow pause.c from Kubernetes.

What does this look like on Windows?

答: Use ping -t localhost will do it

Title: How to keep WIndows Container running?

Body: Use ping -t localhost will do it


问:
Angular 7/json server: post request only accepts id
Im working with Angular 7 and json-server; at the moment I can successfully work with get and delete method's, but the post method is only posting the id and ignoring the 3 other propertys of the same class

Home HTML

```<code> <form (ngSubmit)="addUser()" class="col-md-6 offset-md-3">
      <div class="row">
        <div class="col-md-6 offset-md-3">
          <input required class="form-control top-dist" placeholder="name" type="text" [(ngModel)]="hero.name" name="name" />
        </div>

        <div class="col-md-6 offset-md-3">
          <input required type="number" class="form-control top-dist"  placeholder="age" name="age" [(ngModel)]="hero.age"/>
        </div>

        <div class="col-md-6 offset-md-3">
          <input required name="email" class="form-control top-dist" type="email"  placeholder="email" [(ngModel)]="hero.email" />
        </div>

        <div class="col-md-6 offset-md-3 text-center">
          <div >
            <input type="submit" value="submit" class="btn btn-danger top-dist " />
          </div>
        </div>
      </div>
    </form>
</code>```

Home TS:

```<code>export class HomeComponent implements OnInit {
  heroes: Hero[];
  hero: Hero = {
    id: null,
    name: null,
    age: null,
    email:null
  };
  constructor(private dataService: DataService) {

  }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes() {
    this.dataService.getHeroes().subscribe(data => {
      this.heroes = data;
      console.log(data)
    })
  }
  addUser(){
    if(this.hero.name!=null && this.hero.age!=null && this.hero.email!=null){
    this.dataService.addUser(this.hero).subscribe((data: Hero)=>{console.log(data)})
    }
  };
}
</code>```

The Service:

```<code>addUser(user: Hero){
  console.log(user) ---> logs all fields
  if(user.id===null){
    return this.http.post<Hero>(this.url, user,  {
      headers: new HttpHeaders ({
        'Content-Type':'aplication/json'
      })

    })
}
}
</code>```

In the service I can see that all user's fields are loged into the console, but back on home component, logging the subscribed observable, I can only see the ID, therefore only the id is rendered after. Can someone help?

This is the log of home. The first four were written in the file, the others with the post request:

答:
My guess is that the API endpoint is setup to only return Id on POST requests, which is a common pattern. To get around overwriting your other object properties, one thing you can try:</p>

```<code>this.dataService.addUser(this.hero).subscribe(
    (data: id) => this.hero = Object.assign({}, this.hero, { id: id })
)
</code>```

Body:
Im working with Angular 7 and json-server; at the moment I can successfully work with get and delete method's, but the post method is only posting the id and ignoring the 3 other propertys of the same class

Home HTML

 <form (ngSubmit)="addUser()" class="col-md-6 offset-md-3">

          <input required class="form-control top-dist" placeholder="name" type="text" [(ngModel)]="hero.name" name="name" />

          <input required type="number" class="form-control top-dist"  placeholder="age" name="age" [(ngModel)]="hero.age"/>

          <input required name="email" class="form-control top-dist" type="email"  placeholder="email" [(ngModel)]="hero.email" />

            <input type="submit" value="submit" class="btn btn-danger top-dist " />

    </form>

Home TS:

export class HomeComponent implements OnInit {
  heroes: Hero[];
  hero: Hero = {
    id: null,
    name: null,
    age: null,
    email:null
  };
  constructor(private dataService: DataService) {

  }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes() {
    this.dataService.getHeroes().subscribe(data => {
      this.heroes = data;
      console.log(data)
    })
  }
  addUser(){
    if(this.hero.name!=null && this.hero.age!=null && this.hero.email!=null){
    this.dataService.addUser(this.hero).subscribe((data: Hero)=>{console.log(data)})
    }
  };
}

The Service:

addUser(user: Hero){
  console.log(user) ---> logs all fields
  if(user.id===null){
    return this.http.post<Hero>(this.url, user,  {
      headers: new HttpHeaders ({
        'Content-Type':'aplication/json'
      })

    })
}
}

In the service I can see that all user's fields are loged into the console, but back on home component, logging the subscribed observable, I can only see the ID, therefore only the id is rendered after. Can someone help?

This is the log of home. The first four were written in the file, the others with the post request:

Body:
My guess is that the API endpoint is setup to only return Id on POST requests, which is a common pattern. To get around overwriting your other object properties, one thing you can try:

this.dataService.addUser(this.hero).subscribe(
    (data: id) => this.hero = Object.assign({}, this.hero, { id: id })
)


问:
For loop to ouput a specific pattern
Objective: Trying to output the following pattern using a for loop:

```<code>abcde
abcd
abc
ab
a
</code>```

Current code:
Obviously this doesn't work but my idea is to get the value in i so that 'a' doesn't loop after that number. How can I achieve this?

```<code>char x;
int i;
for (i = 5; i>1; i--)
    {
        for (x = 'a'; x<=(char)(i); x++)
        {
            System.out.print(x);
        }
        System.out.println();
    }
</code>```

答:
If you want the loop to stop i characters after 'a', you can do something like this:

```<code>for (i = 5; i >= 1; i--)
{
    for (x = 'a'; x < 'a' + i; x++)
        ...
</code>```

'a' + i is the value of the character i places after 'a'.

Title: For loop to ouput a specific pattern

Body:
Objective: Trying to output the following pattern using a for loop:

abcde
abcd
abc
ab
a

Current code:
Obviously this doesn't work but my idea is to get the value in i so that 'a' doesn't loop after that number. How can I achieve this?

char x;
int i;
for (i = 5; i>1; i--)
    {
        for (x = 'a'; x<=(char)(i); x++)
        {
            System.out.print(x);
        }
        System.out.println();
    }

Body:
If you want the loop to stop i characters after 'a', you can do something like this:

for (i = 5; i >= 1; i--)
{
    for (x = 'a'; x < 'a' + i; x++)
        ...

'a' + i is the value of the character i places after 'a'.


问:
Move to next element in array every time it calls the function Swift 3
I have an array of 5 images. After every 5 seconds, I wish to display the next element in the array every time it calls the nextImage() function.

```<code>var timer = Timer()

var arrayPhoto: [UIImage] = [
   UIImage(named: "1.jpg"!,
   UIImage(named: "2.jpg"!,
   UIImage(named: "3.jpg"!,
   UIImage(named: "4.jpg"!,
   UIImage(named: "5.jpg"!,
]

func nextImage() {
   // Displays 1.jpg when it first goes into the nextImage() function
   // Subsequently, to display 2.jpg the second time it goes into nextImage() function.
   // Repeat this till the end of the array.
   // If end of array, move to the start.
}

override func viewDidLoad() {
   timer = Timer.scheduledTimer(TimeInterval: 5, target: self, selector: (#selector(nextImage)), userInfo: nil, repeats: true)
}
</code>```

I am stuck at the nextImage function as I am very new to swift programming and would appreciate advice. Thanks.

答:
My solution on Swift 4.2:

Next element:

```<code>let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex + 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : 0
selectedSong = songPlaylist[nextIndex]
</code>```

Previous element:

```<code>let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex - 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : songPlaylist.count - 1
selectedSong = songPlaylist[nextIndex]
</code>```

Body:
I have an array of 5 images. After every 5 seconds, I wish to display the next element in the array every time it calls the nextImage() function.

var timer = Timer()

var arrayPhoto: [UIImage] = [
   UIImage(named: "1.jpg"!,
   UIImage(named: "2.jpg"!,
   UIImage(named: "3.jpg"!,
   UIImage(named: "4.jpg"!,
   UIImage(named: "5.jpg"!,
]

func nextImage() {
   // Displays 1.jpg when it first goes into the nextImage() function
   // Subsequently, to display 2.jpg the second time it goes into nextImage() function.
   // Repeat this till the end of the array.
   // If end of array, move to the start.
}

override func viewDidLoad() {
   timer = Timer.scheduledTimer(TimeInterval: 5, target: self, selector: (#selector(nextImage)), userInfo: nil, repeats: true)
}

I am stuck at the nextImage function as I am very new to swift programming and would appreciate advice. Thanks.

Body:
My solution on Swift 4.2:

Next element:

let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex + 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : 0
selectedSong = songPlaylist[nextIndex]

Previous element:

let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex - 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : songPlaylist.count - 1
selectedSong = songPlaylist[nextIndex]


问:
Stretching images when using as background image
I was trying to set an image as background image for my django application. But when i set it, it is getting displayed as tiled image. ie without actually stretching the image, same image is tiled and shown 4 times. Can somebody tell me how to stretch the image and set it as a background image. I will paste my code here. I am sure some attribute must be there setting this, which i couldnt find on googling.</p>

```<code><body bgcolor=" #408080" background="/static/paper.jpg" background-size: 100%; >
</code>```

答: Instead of using a background image on the body tag you should add a image tag right below body, set the position to absolute and a low z-index and then have width=100% and height=100%.</p>


问:
How to monitor number of RXJS subscriptions?
I'm using an Observable to provide event subscription interface for clients from a global resource, and I need to manage that resource according to the number of active subscriptions:

Allocate global resource when the number of subscriptions becomes greater than 0

Release global resource when the number of subscriptions becomes 0

Adjust the resource usage strategy based on the number of subscriptions

What is the proper way in RXJS to monitor the number of active subscriptions?

How to implement the following within RXJS syntax? -

```<code>const myEvent: Observable<any> = new Observable();

myEvent.onSubscription((newCount: number, prevCount: number) => {
   if(newCount === 0) {
      // release global resource
   } else {
      // allocate global resource, if not yet allocated
   }
   // for a scalable resource usage / load,
   // re-configure it, based on newCount
});
</code>```

I wouldn't expect a guaranteed notification on each change, hence newCount + prevCount params.

UPDATE-1

This is not a duplicate to this, because I need to be notified when the number of subscriptions changes, and not just to get the counter at some point.

UPDATE-2

Without any answer so far, I quickly came up with a very ugly and limited work-around, through complete incapsulation, and specifically for type Subject. Hoping very much to find a proper solution.

UPDATE-3

After a few answers, I'm still not sure how to implement what I'm trying, which is the following:

```<code>class CustomType {

}

class CountedObservable<T> extends Observable<T> {

    private message: string; // random property

    public onCount; // magical Observable that needs to be implemented

    constructor(message: string) {
        // super(); ???
        this.message = message;
    }

    // random method
    public getMessage() {
        return this.message;
    }
}

const a = new CountedObservable<CustomType>('hello'); // can create directly

const msg = a.getMessage(); // can call methods

a.subscribe((data: CustomType) => {
    // handle subscriptions here;
});

// need that magic onCount implemented, so I can do this:
a.onCount.subscribe((newCount: number, prevCont: number) => {
    // manage some external resources
});
</code>```

How to implement such class CountedObservable above, which would let me subscribe to itself, as well as its onCount property to monitor the number of its clients/subscriptions?

UPDATE-4

All suggested solutions seemed overly complex, and even though I accepted one of the answers, I ended up with a completely custom solution one of my own.

答:
You are really asking three separate questions here, and I question whether you really need the full capability that you mention. Since most of the resource managment stuff you are asking for is already provided for by the library, doing custom tracking code seems to be redundant. The first two questions:

Allocate global resource when the number of subscriptions becomes greater than 0

Release global resource when the number of subscriptions becomes 0

Can be done with the using + share operators:

```<code>class ExpensiveResource {
  constructor () {
    // Do construction
  }
  unsubscribe () {
   // Do Tear down
  }
}

// Creates a resource and ties its lifecycle with that of the created `Observable`
// generated by the second factory function
// Using will accept anything that is "Subscription-like" meaning it has a unsubscribe function.
const sharedStream$ = using(
  // Creates an expensive resource
  () => new ExpensiveResource(),
  // Passes that expensive resource to an Observable factory function
  er => timer(1000)
)
// Share the underlying source so that global creation and deletion are only
// processed when the subscriber count changes between 0 and 1 (or visa versa)
.pipe(share())
</code>```

After that sharedStream$ can be passed around as a base stream which will manage the underlying resource (assuming you implemented your unsubscribe correctly) so that the resource will be created and torn down as the number of subscribers transitions between 0 and 1.

Adjust the resource usage strategy based on the number of subscriptions

The third question I am most dubious on, but I'll answer it for completeness assuming you know your application better than I do (since I can't think of a reason why you would need specific handling at different usage levels other than going between 0 and 1).

Basically I would use a similar approach as above but I would encapuslate the transition logic slightly differently.

```<code>// Same as above
class ExpensiveResource {
  unsubscribe() {  console.log('Tear down this resource!')}
}

const usingReferenceTracking =
  (onUp, onDown) => (resourceFactory, streamFactory) => {
    let instance, refCount = 0
    // Again manage the global resource state with using
    const r$ = using(
      // Unfortunately the using pattern doesn't let the resource escape the closure
      // so we need to cache it for ourselves to use later
      () => instance || (instance = resourceFactory()),
      // Forward stream creation as normal
      streamFactory
      )
    ).pipe(
      // Don't forget to clean up the stream after all is said and done
      // Because its behind a share this should only happen when all subscribers unsubscribe
      finalize(() => instance = null)
      share()
    )
    // Use defer to trigger "onSubscribe" side-effects
    // Note as well that these side-effects could be merged with the above for improved performance
    // But I prefer them separate for easier maintenance.
    return defer(() => onUp(instance, refCount += 1) || r$)
      // Use finalize to handle the "onFinish" side-effects
      .pipe(finalize(() => onDown(instance, refCount -= 1)))

}

const referenceTracked$ = usingReferenceTracking(
  (ref, count) => console.log('Ref count increased to ' + count),
  (ref, count) => console.log('Ref count decreased to ' + count)
)(
  () => new ExpensiveResource(),
  ref => timer(1000)
)

referenceTracked$.take(1).subscribe(x => console.log('Sub1 ' +x))
referenceTracked$.take(1).subscribe(x => console.log('Sub2 ' +x))

// Ref count increased to 1
// Ref count increased to 2
// Sub1 0
// Ref count decreased to 1
// Sub2 0
// Ref count decreased to 0
// Tear down this resource!
</code>```

Warning: One side effect of this is that by definition the stream will be warm once it leaves the usingReferenceTracking function, and it will go hot on first subscription. Make sure you take this into account during the subscription phase.

Body:
I'm using an Observable to provide event subscription interface for clients from a global resource, and I need to manage that resource according to the number of active subscriptions:

Allocate global resource when the number of subscriptions becomes greater than 0

Release global resource when the number of subscriptions becomes 0

Adjust the resource usage strategy based on the number of subscriptions

What is the proper way in RXJS to monitor the number of active subscriptions?

How to implement the following within RXJS syntax? -

const myEvent: Observable<any> = new Observable();

myEvent.onSubscription((newCount: number, prevCount: number) => {
   if(newCount === 0) {
      // release global resource
   } else {
      // allocate global resource, if not yet allocated
   }
   // for a scalable resource usage / load,
   // re-configure it, based on newCount
});

I wouldn't expect a guaranteed notification on each change, hence newCount + prevCount params.

UPDATE-1

This is not a duplicate to this, because I need to be notified when the number of subscriptions changes, and not just to get the counter at some point.

UPDATE-2

Without any answer so far, I quickly came up with a very ugly and limited work-around, through complete incapsulation, and specifically for type Subject. Hoping very much to find a proper solution.

UPDATE-3

After a few answers, I'm still not sure how to implement what I'm trying, which is the following:

class CustomType {

}

class CountedObservable<T> extends Observable<T> {

    private message: string; // random property

    public onCount; // magical Observable that needs to be implemented

    constructor(message: string) {
        // super(); ???
        this.message = message;
    }

    // random method
    public getMessage() {
        return this.message;
    }
}

const a = new CountedObservable<CustomType>('hello'); // can create directly

const msg = a.getMessage(); // can call methods

a.subscribe((data: CustomType) => {
    // handle subscriptions here;
});

// need that magic onCount implemented, so I can do this:
a.onCount.subscribe((newCount: number, prevCont: number) => {
    // manage some external resources
});

How to implement such class CountedObservable above, which would let me subscribe to itself, as well as its onCount property to monitor the number of its clients/subscriptions?

UPDATE-4

All suggested solutions seemed overly complex, and even though I accepted one of the answers, I ended up with a completely custom solution one of my own.

Body:
You are really asking three separate questions here, and I question whether you really need the full capability that you mention. Since most of the resource managment stuff you are asking for is already provided for by the library, doing custom tracking code seems to be redundant. The first two questions:

Allocate global resource when the number of subscriptions becomes greater than 0

Release global resource when the number of subscriptions becomes 0

Can be done with the using + share operators:

class ExpensiveResource {
  constructor () {
    // Do construction
  }
  unsubscribe () {
   // Do Tear down
  }
}

// Creates a resource and ties its lifecycle with that of the created `Observable`
// generated by the second factory function
// Using will accept anything that is "Subscription-like" meaning it has a unsubscribe function.
const sharedStream$ = using(
  // Creates an expensive resource
  () => new ExpensiveResource(),
  // Passes that expensive resource to an Observable factory function
  er => timer(1000)
)
// Share the underlying source so that global creation and deletion are only
// processed when the subscriber count changes between 0 and 1 (or visa versa)
.pipe(share())

After that sharedStream$ can be passed around as a base stream which will manage the underlying resource (assuming you implemented your unsubscribe correctly) so that the resource will be created and torn down as the number of subscribers transitions between 0 and 1.

Adjust the resource usage strategy based on the number of subscriptions

The third question I am most dubious on, but I'll answer it for completeness assuming you know your application better than I do (since I can't think of a reason why you would need specific handling at different usage levels other than going between 0 and 1).

Basically I would use a similar approach as above but I would encapuslate the transition logic slightly differently.

// Same as above
class ExpensiveResource {
  unsubscribe() {  console.log('Tear down this resource!')}
}

const usingReferenceTracking =
  (onUp, onDown) => (resourceFactory, streamFactory) => {
    let instance, refCount = 0
    // Again manage the global resource state with using
    const r$ = using(
      // Unfortunately the using pattern doesn't let the resource escape the closure
      // so we need to cache it for ourselves to use later
      () => instance || (instance = resourceFactory()),
      // Forward stream creation as normal
      streamFactory
      )
    ).pipe(
      // Don't forget to clean up the stream after all is said and done
      // Because its behind a share this should only happen when all subscribers unsubscribe
      finalize(() => instance = null)
      share()
    )
    // Use defer to trigger "onSubscribe" side-effects
    // Note as well that these side-effects could be merged with the above for improved performance
    // But I prefer them separate for easier maintenance.
    return defer(() => onUp(instance, refCount += 1) || r$)
      // Use finalize to handle the "onFinish" side-effects
      .pipe(finalize(() => onDown(instance, refCount -= 1)))

}

const referenceTracked$ = usingReferenceTracking(
  (ref, count) => console.log('Ref count increased to ' + count),
  (ref, count) => console.log('Ref count decreased to ' + count)
)(
  () => new ExpensiveResource(),
  ref => timer(1000)
)

referenceTracked$.take(1).subscribe(x => console.log('Sub1 ' +x))
referenceTracked$.take(1).subscribe(x => console.log('Sub2 ' +x))

// Ref count increased to 1
// Ref count increased to 2
// Sub1 0
// Ref count decreased to 1
// Sub2 0
// Ref count decreased to 0
// Tear down this resource!

Warning: One side effect of this is that by definition the stream will be warm once it leaves the usingReferenceTracking function, and it will go hot on first subscription. Make sure you take this into account during the subscription phase.


答: Erwin is right. You will want to change x<=(char)(i) to x<'a' + (char)(i), as well as i = 5; i>1; i--) to i = 5; i>=1; i--).

Title: For loop to ouput a specific pattern


问:
Docker - Windows Container - Install DotNet Framework 472
I am trying to setup a Windows Docker image with .net framework 4.7.2.
For other reasons, I am starting from microsoft/windowsservercore

What I tried so far
- I have choco installed on my image, so my initial solution was to use choco install

```<code>choco install dotnet4.7.2 --allow-empty-checksums -y -v --trace -d
</code>```

What I get is 0x80004005

```<code>C:\users\ContainerAdministrator\AppData\Local\Temp\chocolatey> more .\dd_NDP472-KB4054530-x86-x64-AllOS-ENU_decompression_log.txt
??[5/25/2019, 22:26:33] === Logging started: 2019/05/25 22:26:33 ===
[5/25/2019, 22:26:33] Executable: C:\Users\ContainerAdministrator\AppData\Local\Temp\chocolatey\dotnetfx\4.7.2.20180712\NDP472-KB4054530-x86-x64-AllOS-ENU.exe v4.7.3081.0
[5/25/2019, 22:26:33] --- logging level: standard ---
[5/25/2019, 22:26:33] Successfully bound to the ClusApi.dll
[5/25/2019, 22:26:33] Error 0x800706d9: Failed to open the current cluster
[5/25/2019, 22:26:33] Cluster drive map: ''
[5/25/2019, 22:26:33] Considering drive: 'C:\'...
[5/25/2019, 22:26:33] Drive 'C:\' has been selected as the largest fixed drive
[5/25/2019, 22:26:33] Directory 'C:\b659e2a87b51ccf0f10d6292d1a4c2\' has been selected for file extraction
[5/25/2019, 22:26:33] Extracting files to: C:\b659e2a87b51ccf0f10d6292d1a4c2\
[5/25/2019, 22:26:33] Error 0x80004005: Failed to extract all files out of box container #0.
[5/25/2019, 22:26:33] Error 0x80004005: Failed to extract
</code>```

Looking for 0x80004005 , I found some similar issues
https://social.technet.microsoft.com/Forums/en-US/4808233e-1410-4305-a8d1-0e88f3a6fdc8/net-451-install-only-works-when-running-on-a-ui-session?forum=configmanagerapps

https://blog.nowmicro.com/2015/02/23/deploying-net-framework-4-5-2-configmgr-application/

Following some the ideas from links above, I did :

I downloaded manually NDP472-KB4054530-x86-x64-AllOS-ENU.exe

I extracted it locally, on host, from command line (with /extract). Basically I have a local directory with all content of the NDP472 (including
Setup.exe)

I am running the container using volume

docker run --name cw10 -v C:\MyNDP472:C:\tmp -d client-windows10

I am attaching to the container with cmd. From C:\tmp (which points to C:\MyNDP472 from host), I am running from command line.

Setup.exe /q /norestart /ChainingPackage "ADMINDEPLOYMENT" /x86 /x64 /redist /log "C:\tmp\reportdotnet.log"

The result is Final Result: Installation completed successfully with success code: (0x80070BC2), "The requested operation is successful. Changes will not be effective until the system is rebooted.

I am checking the registries (this time with Powershell)

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |Get-ItemProperty -name Version,Release -EA 0 |Where { $_.PSChildName -match '^(?!S)\p{L}'} |Select PSChildName, Version, Release

I still get previous version of .net framework  (Full 4.6.01586  394802) - the one that comes with the base image.
I reboot the container with docker restart. I get exactly the same. No changes.

My final goal : I want to build a C# sln solution with target 4.7.2.

I am out of ideas.
Any thought?

Thanks

答: You can use the same dockerfile which microsoft using for building their dotnetframework images here for SDK (https://github.com/microsoft/dotnet-framework-docker/blob/master/4.7.2/sdk/windowsservercore-ltsc2019/Dockerfile) or runtime (https://github.com/microsoft/dotnet-framework-docker/blob/master/4.7.2/runtime/windowsservercore-ltsc2019/Dockerfile)</p>

Body:
I am trying to setup a Windows Docker image with .net framework 4.7.2.
For other reasons, I am starting from microsoft/windowsservercore

What I tried so far
- I have choco installed on my image, so my initial solution was to use choco install

choco install dotnet4.7.2 --allow-empty-checksums -y -v --trace -d

What I get is 0x80004005

C:\users\ContainerAdministrator\AppData\Local\Temp\chocolatey> more .\dd_NDP472-KB4054530-x86-x64-AllOS-ENU_decompression_log.txt
??[5/25/2019, 22:26:33] === Logging started: 2019/05/25 22:26:33 ===
[5/25/2019, 22:26:33] Executable: C:\Users\ContainerAdministrator\AppData\Local\Temp\chocolatey\dotnetfx\4.7.2.20180712\NDP472-KB4054530-x86-x64-AllOS-ENU.exe v4.7.3081.0
[5/25/2019, 22:26:33] --- logging level: standard ---
[5/25/2019, 22:26:33] Successfully bound to the ClusApi.dll
[5/25/2019, 22:26:33] Error 0x800706d9: Failed to open the current cluster
[5/25/2019, 22:26:33] Cluster drive map: ''
[5/25/2019, 22:26:33] Considering drive: 'C:\'...
[5/25/2019, 22:26:33] Drive 'C:\' has been selected as the largest fixed drive
[5/25/2019, 22:26:33] Directory 'C:\b659e2a87b51ccf0f10d6292d1a4c2\' has been selected for file extraction
[5/25/2019, 22:26:33] Extracting files to: C:\b659e2a87b51ccf0f10d6292d1a4c2\
[5/25/2019, 22:26:33] Error 0x80004005: Failed to extract all files out of box container #0.
[5/25/2019, 22:26:33] Error 0x80004005: Failed to extract

Looking for 0x80004005 , I found some similar issues
https://social.technet.microsoft.com/Forums/en-US/4808233e-1410-4305-a8d1-0e88f3a6fdc8/net-451-install-only-works-when-running-on-a-ui-session?forum=configmanagerapps

https://blog.nowmicro.com/2015/02/23/deploying-net-framework-4-5-2-configmgr-application/

Following some the ideas from links above, I did :

I downloaded manually NDP472-KB4054530-x86-x64-AllOS-ENU.exe

I extracted it locally, on host, from command line (with /extract). Basically I have a local directory with all content of the NDP472 (including
Setup.exe)

I am running the container using volume

docker run --name cw10 -v C:\MyNDP472:C:\tmp -d client-windows10

I am attaching to the container with cmd. From C:\tmp (which points to C:\MyNDP472 from host), I am running from command line.

Setup.exe /q /norestart /ChainingPackage "ADMINDEPLOYMENT" /x86 /x64 /redist /log "C:\tmp\reportdotnet.log"

The result is Final Result: Installation completed successfully with success code: (0x80070BC2), "The requested operation is successful. Changes will not be effective until the system is rebooted.

I am checking the registries (this time with Powershell)

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |Get-ItemProperty -name Version,Release -EA 0 |Where { $_.PSChildName -match '^(?!S)\p{L}'} |Select PSChildName, Version, Release

I still get previous version of .net framework  (Full 4.6.01586  394802) - the one that comes with the base image.
I reboot the container with docker restart. I get exactly the same. No changes.

My final goal : I want to build a C# sln solution with target 4.7.2.

I am out of ideas.
Any thought?

Thanks


问:
Angular bootstrap Modal component not working?
I am trying to add Modals from bootstrap for angular, but it seems like it's not working : https://ng-bootstrap.github.io/#/components/modal/examples

I copy/pasted the last modal 'Global configuration of modals'

Of course I imported it and placed it in my declarations variables + in the constructor.

答:
Yep. This is a very common issue when adding modals, whether it's bootstrap or the Material library modals.

Take a look at their example here. You'll notice they added entryComponents: [NgbdModalContent]. Just make sure you do that as well in your code.

Specifically, do it inside the module file.


问:
.NET Api create Insert POST API for object with Many to Many Relationship
I have a model called Trucks, and a Model called Categories. There is a many to many relationship between the 2 models. I have created a Table called TruckCategory to map the many to many relationship. I am trying to create an API that will insert a new food truck with its categories. How do i do so in such a case?</p>

```<code>public class Truck
{
    public int TruckId { get; set; }
    public string Title { get; set; }
    public int Price { get; set; }
    [Range(1, 5)]
    public decimal Rating { get; set; }
    public string Hours { get; set; }
    public string Phone { get; set; }
    public Coordinates Coordinates { get; set; }
    public Address Location { get; set; }

    public virtual ICollection<TruckCategory> TruckCategory { get; set; }
}
</code>```

答:
If you are using visual studio, create an Api Controller class
like this one

```<code>public class PostingApiController : ApiController
{
    public string CreateTruckCategory(TruckAndCategory model)
    {
        try
        {
            using (var db = new YourEntity())
            {
                //extract the truck model
                Truck truck = new Truck
                {
                    //assign variables example
                    Title = model.Truck.Title;
                };
                //save truck data to db
                db.Truck.Add(truck);
                db.SaveChanges();
                //keep track of the truck id if it is auto increment
                var truckId = truck.TruckId;

                //also in the same way extract and save the category model keeping track of the ID,
                var categoryId = category.Id;

                //the save the link table with both IDs
                TruckCategory truckCategory = new TruckCategory
                {
                    CategoryId = categoryId;
                    TruckId = truckId;
                };
                //then save this link table
                db.TruckCategory.Add(truckCategory);
                db.SaveChanges();
            }

            return "success";
        }
        catch (Exception e)
        {
            return "failure";
        }
    }
}
</code>```

where you have your model as

```<code>public class TruckAndCategory{
    //class declaration here
    public Truck truck {get; set;}
    public Category category {get; set;}
}
</code>```

Body:
I have a model called Trucks, and a Model called Categories. There is a many to many relationship between the 2 models. I have created a Table called TruckCategory to map the many to many relationship. I am trying to create an API that will insert a new food truck with its categories. How do i do so in such a case?

public class Truck
{
    public int TruckId { get; set; }
    public string Title { get; set; }
    public int Price { get; set; }
    [Range(1, 5)]
    public decimal Rating { get; set; }
    public string Hours { get; set; }
    public string Phone { get; set; }
    public Coordinates Coordinates { get; set; }
    public Address Location { get; set; }

    public virtual ICollection<TruckCategory> TruckCategory { get; set; }
}

Body:
If you are using visual studio, create an Api Controller class
like this one

public class PostingApiController : ApiController
{
    public string CreateTruckCategory(TruckAndCategory model)
    {
        try
        {
            using (var db = new YourEntity())
            {
                //extract the truck model
                Truck truck = new Truck
                {
                    //assign variables example
                    Title = model.Truck.Title;
                };
                //save truck data to db
                db.Truck.Add(truck);
                db.SaveChanges();
                //keep track of the truck id if it is auto increment
                var truckId = truck.TruckId;

                //also in the same way extract and save the category model keeping track of the ID,
                var categoryId = category.Id;

                //the save the link table with both IDs
                TruckCategory truckCategory = new TruckCategory
                {
                    CategoryId = categoryId;
                    TruckId = truckId;
                };
                //then save this link table
                db.TruckCategory.Add(truckCategory);
                db.SaveChanges();
            }

            return "success";
        }
        catch (Exception e)
        {
            return "failure";
        }
    }
}

where you have your model as

public class TruckAndCategory{
    //class declaration here
    public Truck truck {get; set;}
    public Category category {get; set;}
}


问:
how to download single folder OR file in gitlab repository
i have one repository. In this repository multiple folders are available.

i have required only one folder in this repository.

i am already try to following command but it's not working.

git clone

答:
If only the content of that folder is of interest (not its history), you can, since GitLab 1.11 (May 2019) download only a folder.

Download archives of directories within a repository

Depending on the type of project and its size, downloading an archive of the entire project may be slow or unhelpful – particularly in the case of large monorepos.

In GitLab 11.11, you can now download an archive of the contents of the current directory, including subdirectories, so that you download only the files you need.

From issue 24704: see documentation.

With GitLab 14.4 (Oct. 2021), you have:

issue 28827 "Download a (sub-)folder from a repository via the Repositories API",

resolved with MR 71431 and commit 1b4e0a1:

curl --header "PRIVATE-TOKEN: <your_access_token>" \
"https://gitlab.com/api/v4/projects/<project_id>/repository/archive?sha=<commit_sha>&path=<path>"
```

It was not somehow mentioned in the "GitLab 1.44 released" page though.

Body:
If only the content of that folder is of interest (not its history), you can, since GitLab 1.11 (May 2019) download only a folder.

Download archives of directories within a repository

Depending on the type of project and its size, downloading an archive of the entire project may be slow or unhelpful – particularly in the case of large monorepos.

In GitLab 11.11, you can now download an archive of the contents of the current directory, including subdirectories, so that you download only the files you need.

From issue 24704: see documentation.

With GitLab 14.4 (Oct. 2021), you have:

issue 28827 "Download a (sub-)folder from a repository via the Repositories API",

resolved with MR 71431 and commit 1b4e0a1:

curl --header "PRIVATE-TOKEN: <your_access_token>" \
"https://gitlab.com/api/v4/projects/<project_id>/repository/archive?sha=<commit_sha>&path=<path>"

It was not somehow mentioned in the "GitLab 1.44 released" page though.


问:
RegEx for replacing part of a string in R
I am trying to do an exact pattern match using the gsub/sub and replace function. I am not getting the desired response. I am trying to remove the .x and .y from the names without affecting other names.

```<code>name = c("company", "deriv.x", "isConfirmed.y")
new.name = gsub(".x$|.y$", "", name)
new.name
[1] "compa"       "deriv"       "isConfirmed"
</code>```

company has become compa.

I have also tried

```<code>remove = c(".x", ".y")
replace(name, name %in% remove, "")
[1] "company"    "deriv.x"    "isConfirmed.y"
</code>```

I would like the outcome to be.
"company", "deriv", "isConfirmed"

How do I solve this problem?

答:
Here we can have a simple expression that removes the undesired . and anything after that:

```<code>(.+?)(?:\..+)?
</code>```

or for exact match:

```<code>(.+?)(?:\.x|\.y)?
</code>```

R Test

Your code might look like something similar to:

```<code>gsub("(.+?)(?:\\..+)?", "\\1", "deriv.x")
</code>```

or

```<code>gsub("(.+?)(?:\.x|\.y)?", "\\1", "deriv.x")
</code>```

R Demo

RegEx Demo 1

RegEx Demo 2

Description

Here, we are having a capturing group (.+?), where our desired output is and a non-capturing group (?:\..+)? which swipes everything after the undesired ..

Body:
I am trying to do an exact pattern match using the gsub/sub and replace function. I am not getting the desired response. I am trying to remove the .x and .y from the names without affecting other names.

name = c("company", "deriv.x", "isConfirmed.y")
new.name = gsub(".x$|.y$", "", name)
new.name
[1] "compa"       "deriv"       "isConfirmed"

company has become compa.

I have also tried

remove = c(".x", ".y")
replace(name, name %in% remove, "")
[1] "company"    "deriv.x"    "isConfirmed.y"

I would like the outcome to be.
"company", "deriv", "isConfirmed"

How do I solve this problem?

Body:
Here we can have a simple expression that removes the undesired . and anything after that:

(.+?)(?:\..+)?

or for exact match:

(.+?)(?:\.x|\.y)?

R Test

Your code might look like something similar to:

gsub("(.+?)(?:\\..+)?", "\\1", "deriv.x")

or

gsub("(.+?)(?:\.x|\.y)?", "\\1", "deriv.x")

R Demo

RegEx Demo 1

RegEx Demo 2

Description

Here, we are having a capturing group (.+?), where our desired output is and a non-capturing group (?:\..+)? which swipes everything after the undesired ..