问:
Cloud Data Fusion ETL from PostGres to BigQuery - idempotent load
I'm trying to use Google's Cloud Data Fusion (CDF) to perform an ETL of some OLTP data in PostGres into BigQuery (BQ). We will copy the contents of a few select tables into an equivalent table in BQ every night - we will add one column with the datestamp.

So imagine we have a table with two columns A & B, and one row of data like this in PostGres

```<code>|--------------------|
|    A    |    B     |
|--------------------|
|  egg    |  milk    |
|--------------------|
</code>```

Then over two days, the BigQuery table would look like this

```<code>|-------------------------------|
|    ds    |    A    |    B     |
|-------------------------------|
| 22-01-01 |   egg   |   milk   |
|-------------------------------|
| 22-01-02 |   egg   |   milk   |
|-------------------------------|
</code>```

However, I'm worried that the way I am doing this in CDF is not idempotent and if the pipeline runs twice I'll have duplicate data for a given day in BQ (not desired)

One idea is to delete rows for that day in BQ before doing the ETL (as part of the same pipeline). However, not sure how to do this, or if it is best practice. Any ideas?

答:
You can use one of these 2 options, depending on what you want to do with the information:

Option 1

You can create a blank new_table with the same schema (ds,A,B). You will insert the data into the old_table from Data Fusion. With the MERGE statement, you will compare the data from the old_table with the new_table; the data that does not exist into the new_table will be inserted, and the data that exist and have different data will update this other data.

```<code>MERGE merge_example.new_table T
USING dataset.old_table S
ON T.ds = S.ds
WHEN MATCHED THEN
 UPDATE SET T.A = s.a, T.B=s.b
WHEN NOT MATCHED THEN
 INSERT (ds,A, B) VALUES(ds, A, B)
</code>```

Option 2

It is the same process as Option 1, but this query only inserts the data that does not exist into the new_table.

```<code>insert into `dataset.new_table`
select ds, A, B from `dataset.old_table`
where ds not in (select ds from `dataset.new_table`)
</code>```

The difference between Option 1 and Option 2 is that option 1 will update the data that exists which has a different value in the new_table and insert the new data. Option 2 will just insert the new data.

You can execute these queries with a Scheduled Query once a day. You can see this documentation.

Body:
I'm trying to use Google's Cloud Data Fusion (CDF) to perform an ETL of some OLTP data in PostGres into BigQuery (BQ). We will copy the contents of a few select tables into an equivalent table in BQ every night - we will add one column with the datestamp.

So imagine we have a table with two columns A & B, and one row of data like this in PostGres

|--------------------|
|    A    |    B     |
|--------------------|
|  egg    |  milk    |
|--------------------|

Then over two days, the BigQuery table would look like this

|-------------------------------|
|    ds    |    A    |    B     |
|-------------------------------|
| 22-01-01 |   egg   |   milk   |
|-------------------------------|
| 22-01-02 |   egg   |   milk   |
|-------------------------------|

However, I'm worried that the way I am doing this in CDF is not idempotent and if the pipeline runs twice I'll have duplicate data for a given day in BQ (not desired)

One idea is to delete rows for that day in BQ before doing the ETL (as part of the same pipeline). However, not sure how to do this, or if it is best practice. Any ideas?

Body:
You can use one of these 2 options, depending on what you want to do with the information:

Option 1

You can create a blank new_table with the same schema (ds,A,B). You will insert the data into the old_table from Data Fusion. With the MERGE statement, you will compare the data from the old_table with the new_table; the data that does not exist into the new_table will be inserted, and the data that exist and have different data will update this other data.

MERGE merge_example.new_table T
USING dataset.old_table S
ON T.ds = S.ds
WHEN MATCHED THEN
 UPDATE SET T.A = s.a, T.B=s.b
WHEN NOT MATCHED THEN
 INSERT (ds,A, B) VALUES(ds, A, B)

Option 2

It is the same process as Option 1, but this query only inserts the data that does not exist into the new_table.

insert into `dataset.new_table`
select ds, A, B from `dataset.old_table`
where ds not in (select ds from `dataset.new_table`)

The difference between Option 1 and Option 2 is that option 1 will update the data that exists which has a different value in the new_table and insert the new data. Option 2 will just insert the new data.

You can execute these queries with a Scheduled Query once a day. You can see this documentation.


来源: stackexchange

问:
Convert nested dictionary to csv
I have a particular case where I want to create a csv using the inner values of a nested dictionary as the keys and the inner keys as the header. The 'healthy' key can contain more subkeys other than 'height' and 'weight', but the 'unhealthy' will either ever contain None or a string of values.
My current dictionary looks like this:

```<code>{0: {'healthy': {'height': 160,
                 'weight': 180},
    'unhealthy': None},
 1: {'healthy': {'height': 170,
                'weight': 250},
    'unhealthy': 'alcohol, smoking, overweight'}
}
</code>```

How would I convert this to this csv:

```<code>+------+--------+----------------------------+
|height|  weight|                   unhealthy|
+------+--------+----------------------------+
|160   |     180|                            |
+------+--------+----------------------------+
|170   |     250|alcohol, smoking, overweight|
+------+--------+----------------------------+
</code>```

Is there anyway of not hardcoding this and doing this without Pandas and saving it to a location?

答:
With D being your dictionary you can pass D.values() to pandas.json_normalize() and rename the columns if needed.

```<code>>>> import pandas as pd
>>> print(pd.json_normalize(D.values()).to_markdown(tablefmt='psql'))
+╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+
|    | unhealthy                    |   healthy.height |   healthy.weight |
|╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌|
|  0 |                              |              160 |              180 |
|  1 | alcohol, smoking, overweight |              170 |              250 |
+╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convert nested dictionary to csv

Body:
I have a particular case where I want to create a csv using the inner values of a nested dictionary as the keys and the inner keys as the header. The 'healthy' key can contain more subkeys other than 'height' and 'weight', but the 'unhealthy' will either ever contain None or a string of values.
My current dictionary looks like this:

{0: {'healthy': {'height': 160,
                 'weight': 180},
    'unhealthy': None},
 1: {'healthy': {'height': 170,
                'weight': 250},
    'unhealthy': 'alcohol, smoking, overweight'}
}

How would I convert this to this csv:

+------+--------+----------------------------+
|height|  weight|                   unhealthy|
+------+--------+----------------------------+
|160   |     180|                            |
+------+--------+----------------------------+
|170   |     250|alcohol, smoking, overweight|
+------+--------+----------------------------+

Is there anyway of not hardcoding this and doing this without Pandas and saving it to a location?

Body:
With D being your dictionary you can pass D.values() to pandas.json_normalize() and rename the columns if needed.

>>> import pandas as pd
>>> print(pd.json_normalize(D.values()).to_markdown(tablefmt='psql'))
+╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+
|    | unhealthy                    |   healthy.height |   healthy.weight |
|╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌|
|  0 |                              |              160 |              180 |
|  1 | alcohol, smoking, overweight |              170 |              250 |
+╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌+


问:
Using XPath to select button inside HTML with content of tag instead of numbered list
I am using python + selenium to automate common behavior through a website. I have now arrived at a point where there is a div
 with a number of
 inside href> tags. Please find a snippet of the HTML page below to clarify.

```<code><div class="teetime-grid" data-baan="1">
    <a href="#">

        <div class="btn btn-success teetime has-bookings " data-time="1645165200"
             title="Er zijn nog 3 beschikbare plaatsen op deze starttijd">
            <span class="time">07:20</span>
            <div class="icons">
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon vrij"> </span>
                <span class="icon vrij"> </span>
                <span class="icon vrij"> </span>

            </div>
        </div>
    </a>

    <a href="#">

        <div class="btn btn-success teetime has-bookings " data-time="1645165800"
             title="Er zijn nog 1 beschikbare plaatsen op deze starttijd">
            <span class="time">07:30</span>
            <div class="icons">
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon vrij"> </span>

            </div>
        </div>
    </a>
</div>
</code>```

I need to access specific
 inside the grid. In Selenium, I know I can do this by using:

```<code>driver = webdriver.Chrome()
driver.find_element_by_xpath("//a[2]/div")
</code>```

To select the second  tag in my above example, which in this case has a corresponding time of 07:30 associated with it (it's defined in the 07:30).

Is there also a way to access these elements by the contents of the  instead of specifying the number in the list of href> tags? Because now I still have to know which a[?] number corresponds to a certain time. If I have to look this up manually every time time there is no point in automating this browser action to begin with.

答:
To access the specific
 corresponding to the different time you can the following locator strategies:

Selecting 07:20:

```<code>element = driver.find_element(By.XPATH, "//a[./span[text()='07:20']]")
</code>```

Selecting 07:30:

```<code>element = driver.find_element(By.XPATH, "//a[./span[text()='07:30']]")
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.common.by import By
</code>```

Body:
I am using python + selenium to automate common behavior through a website. I have now arrived at a point where there is a div
 with a number of
 inside  tags. Please find a snippet of the HTML page below to clarify.

            07:20

            07:30

I need to access specific
 inside the grid. In Selenium, I know I can do this by using:

driver = webdriver.Chrome()
driver.find_element_by_xpath("//a[2]/div")

To select the second  tag in my above example, which in this case has a corresponding time of 07:30 associated with it (it's defined in the 07:30).

Is there also a way to access these elements by the contents of the  instead of specifying the number in the list of  tags? Because now I still have to know which a[?] number corresponds to a certain time. If I have to look this up manually every time time there is no point in automating this browser action to begin with.

Body:
To access the specific <div class="btn btn-success teetime has-bookings> corresponding to the different time you can the following locator strategies:

Selecting 07:20:

element = driver.find_element(By.XPATH, "//a[./span[text()='07:20']]")

Selecting 07:30:

element = driver.find_element(By.XPATH, "//a[./span[text()='07:30']]")

Note : You have to add the following imports :

from selenium.webdriver.common.by import By


问:
the project doesn't know how to run the profile ConsoleApp
I just downloaded Visual Studio 2022 (Although I much preferred 2019 but can't find it) and as soon as I open a simple "Hello World" project and try to run it, I have an error.

Using .Net 5.0 Runtime

How can I fix this? is this a 2022 issue or if I miraculously find Visual Studio 2019 somewhere online it'll show the same error?

UPDATE: 2019 works fine, it's just 2022. I'll work on 2019 but if anyone has a solution maybe it'll help other people :)

答: Using the Modify action in "Uninstall or change a program" fixed it for me.  Most notably my VS2022 installation had "forgotten" the Desktop workflow selection that I selected at the original installation.</p>


问:
Infinite Marquee responsive no gap
I have a problem with this code.
I want to apply a marquee effect to this words with continues animation.
In my result, at the 100% Keyframe, the animation return to 0 and the effect is orrible!
I want animation to be fully responsive.
Thank u very much!

With this video you can see the error -> VIDEO

var elements = $('ul.tithome li').length;

for(var i=0;i < elements; i++){
 $(".tithome").clone().prependTo( ".scorri" );
};

var liEle = [];
var liEle = $(".tithome li");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cont{
  width: 100%;
  overflow: hidden;
}

.scorri{
  position:relative;
  display: flex;
  width: 100%;
  animation-name: marquee;
  animation-duration: 20s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  justify-content: space-between;
}

.tithome{
  display: contents;
}

.tithome li{
  width: fit-content;
  display: inline-block;
  list-style: none;
  padding-right: 30px;
  font-size: 40px;
}

@keyframes marquee {
  0% { left: 0; }
  100% {left: -88.79%;}
}</code>```

Governance

HR

Sales

```

答:
i just saw this post. It saves my time. Thanks a lot. By the way i create a pen for this and just remove some empty spaces from list and change it to scss.

if someone needs it can find from this address

https://codepen.io/tsdln/pen/LYOLdXQ

```<code>var elements = $('ul.list li').length;
</code>```

Title: Infinite Marquee responsive no gap

Body:
I have a problem with this code.
I want to apply a marquee effect to this words with continues animation.
In my result, at the 100% Keyframe, the animation return to 0 and the effect is orrible!
I want animation to be fully responsive.
Thank u very much!

With this video you can see the error -> VIDEO

var elements = $('ul.tithome li').length;

for(var i=0;i < elements; i++){
 $(".tithome").clone().prependTo( ".scorri" );
};

var liEle = [];
var liEle = $(".tithome li");

.cont{
  width: 100%;
  overflow: hidden;
}

.scorri{
  position:relative;
  display: flex;
  width: 100%;
  animation-name: marquee;
  animation-duration: 20s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  justify-content: space-between;
}

.tithome{
  display: contents;
}

.tithome li{
  width: fit-content;
  display: inline-block;
  list-style: none;
  padding-right: 30px;
  font-size: 40px;
}

@keyframes marquee {
  0% { left: 0; }
  100% {left: -88.79%;}
}

Governance

HR

Sales

Body:
i just saw this post. It saves my time. Thanks a lot. By the way i create a pen for this and just remove some empty spaces from list and change it to scss.

if someone needs it can find from this address

https://codepen.io/tsdln/pen/LYOLdXQ

var elements = $('ul.list li').length;


问:
Django:How i can call the values of the fields of a form that i want to display properly when i want to generate a pdf printout
Hi stackoverflow team;

Am newbie on django ,I Hope i can find solution or someone can help me because am really stuck on , I have spent the whole day searching without reaching my goal;

I want to generate a printout after fill out a form , this form contain the fields "longeur", "hauteur", "element", the user will fill out this form then he will click on a button to display the  "moment" and the "area" that would be calculated automatically and be displayed under the form. but on the printout I would for now just  display the values typed by the user in the field "longuer" and "hauteur"

Here is the story of my code;

I have a the model class in models.py of the form(formulaire):

```<code>class Forms(models.Model):
    element = models.CharField(verbose_name=" Component ", max_length=60, default="e1")
    hauteur = models.FloatField(verbose_name=" Height ")
    longuer = models.FloatField(verbose_name=" Length between posts ")
</code>```

in the views.py: I have defined the function "forms_render_pdf_view" for generating the pdf where I have passed the fields of the form("longeur" and "hauteur" to the dictionary "context") that i want their values to be displayed on my pdf printout.

```<code>def forms_render_pdf_view(request, *args, **kwargs):
   template_path = 'pages/generate_pdf.html'
   context = {'longuer':request.GET.get('longuer'), 'hauteur':request.GET.get('hauteur')}
   response = HttpResponse(content_type='application/pdf')
   response['Content-Disposition'] = 'filename="report.pdf"'
   template = get_template(template_path)
   html = template.render(context)
   pisa_status = pisa.CreatePDF(
      html, dest=response)
   if pisa_status.err:
      return HttpResponse('We had some errors ```' + html + '```')
   return response
</code>```

the forms.py:

```<code>class FormsCreationForm(forms.ModelForm):
    class Meta:
        model = Forms
        fields = '__all__'
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
</code>```

and here is the the html file to render it to pdf:(generate_pdf.html) where i have called "hauteur" and "longeur" to display their values in the pdf.

```<code><!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  </head>
  <body style="font-size: 18px;"">
    <div style="padding: 3rem;" class="container">
        <h1>Hauteur:</h1>
        <p>{{ hauteur }}</p>
        <h1>Longueur:</h1>
        <p>{{ longueur }}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

    -->
  </body>
</html>
</code>```

But when i generate the printout i didn't find the values of them(it display "None" instead) and there is no error , I do no what I have forgot really!

Here is a picture of the pdf generated.

it displays the value "None" on the printout
---> a screenshoot added.

enter image description here

please Help me, any help will be appreciated How i can call the values of the fields that i want to display properly.!!?
Thanks in advance.

about the urls.py:

```<code>path('pdf/', views.forms_render_pdf_view, name='pdf_view'),
</code>```

PS: I want to know should i create a method save to save the data of the formular that i have developed to print the fields or not?

答:
Try to use POST insted of GET

Replace your code from:
context = {'longuer':request.GET.get('longuer'), 'hauteur':request.GET.get('hauteur')}

To:

context = {'longuer':request.POST.get('longuer'), 'hauteur':request.POST.get('hauteur')}

Or past your html template code for  FormsCreationForm  that submit data to view function (forms_render_pdf_view)

Update

Another Oops!!
template variable name not equal to model and context data
longueur != longuer
replace longueur to longuer in template

```<code> <p>{{ longuer }}</p>
</code>```

Body:
Hi stackoverflow team;

Am newbie on django ,I Hope i can find solution or someone can help me because am really stuck on , I have spent the whole day searching without reaching my goal;

I want to generate a printout after fill out a form , this form contain the fields "longeur", "hauteur", "element", the user will fill out this form then he will click on a button to display the  "moment" and the "area" that would be calculated automatically and be displayed under the form. but on the printout I would for now just  display the values typed by the user in the field "longuer" and "hauteur"

Here is the story of my code;

I have a the model class in models.py of the form(formulaire):

class Forms(models.Model):
    element = models.CharField(verbose_name=" Component ", max_length=60, default="e1")
    hauteur = models.FloatField(verbose_name=" Height ")
    longuer = models.FloatField(verbose_name=" Length between posts ")

in the views.py: I have defined the function "forms_render_pdf_view" for generating the pdf where I have passed the fields of the form("longeur" and "hauteur" to the dictionary "context") that i want their values to be displayed on my pdf printout.

def forms_render_pdf_view(request, *args, **kwargs):
   template_path = 'pages/generate_pdf.html'
   context = {'longuer':request.GET.get('longuer'), 'hauteur':request.GET.get('hauteur')}
   response = HttpResponse(content_type='application/pdf')
   response['Content-Disposition'] = 'filename="report.pdf"'
   template = get_template(template_path)
   html = template.render(context)
   pisa_status = pisa.CreatePDF(
      html, dest=response)
   if pisa_status.err:
      return HttpResponse('We had some errors
' + html + '
')
   return response

the forms.py:

class FormsCreationForm(forms.ModelForm):
    class Meta:
        model = Forms
        fields = '__all__'
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

and here is the the html file to render it to pdf:(generate_pdf.html) where i have called "hauteur" and "longeur" to display their values in the pdf.

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

Hauteur:

{{ hauteur }}

Longueur:

{{ longueur }}

    -->

But when i generate the printout i didn't find the values of them(it display "None" instead) and there is no error , I do no what I have forgot really!

Here is a picture of the pdf generated.

it displays the value "None" on the printout
---> a screenshoot added.

enter image description here

please Help me, any help will be appreciated How i can call the values of the fields that i want to display properly.!!?
Thanks in advance.

about the urls.py:

path('pdf/', views.forms_render_pdf_view, name='pdf_view'),

PS: I want to know should i create a method save to save the data of the formular that i have developed to print the fields or not?

Body:
Try to use POST insted of GET

Replace your code from:
context = {'longuer':request.GET.get('longuer'), 'hauteur':request.GET.get('hauteur')}

To:

context = {'longuer':request.POST.get('longuer'), 'hauteur':request.POST.get('hauteur')}

Or past your html template code for  FormsCreationForm  that submit data to view function (forms_render_pdf_view)

Update

Another Oops!!
template variable name not equal to model and context data
longueur != longuer
replace longueur to longuer in template

 <p>{{ longuer }}</p>


问:
How to perform arithmetic operation on a date in Python?
I have a date column in csv file say Date having dates in this format 04/21/2013 and I have one more column Next_Day. In Next_Day column I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has 04/21/2013 as date then I want 04/22/2013 in Next_Day column.

We can use +1 in excel but I don't know how to perform this in Python.

Please help me in resolving this.

答:
Same answer as a one-liner. Prints 1 day 1 hour & 30 minutes ago from now:</p>
```<code>python -c 'import datetime;print(datetime.datetime.now() - datetime.timedelta(days=1,hours=1,minutes=30))'

2022-02-08 13:11:06.304608
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Same answer as a one-liner. Prints 1 day 1 hour & 30 minutes ago from now:

python -c 'import datetime;print(datetime.datetime.now() - datetime.timedelta(days=1,hours=1,minutes=30))'

2022-02-08 13:11:06.304608


答:
So this may be very dumb way to do this, but if your dictionary has this structure and you don't mind about hardcoding the actual values, this might be the way

```<code>import csv

dictionary = {0: {'healthy': {'height': 160,
                              'weight': 180},
                  'unhealthy': None},
              1: {'healthy': {'height': 170,
                              'weight': 250},
                  'unhealthy': 'alcohol, smoking, overweight'}
              }

with open("out.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(['height', 'weight', 'unhealthy'])
    writer.writerows([
        [value['healthy']['height'],
         value['healthy']['weight'],
         value['unhealthy']
         ] for key, value in dictionary.items()])
</code>```

So the point is you just create an array of [<height>, <weight>, <unhealthy>] arrays and write it to csv file using python's builtin module's csv.writer.writerows()

Title: Convert nested dictionary to csv

Body:
So this may be very dumb way to do this, but if your dictionary has this structure and you don't mind about hardcoding the actual values, this might be the way

import csv

dictionary = {0: {'healthy': {'height': 160,
                              'weight': 180},
                  'unhealthy': None},
              1: {'healthy': {'height': 170,
                              'weight': 250},
                  'unhealthy': 'alcohol, smoking, overweight'}
              }

with open("out.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(['height', 'weight', 'unhealthy'])
    writer.writerows([
        [value['healthy']['height'],
         value['healthy']['weight'],
         value['unhealthy']
         ] for key, value in dictionary.items()])

So the point is you just create an array of [<height>, <weight>, <unhealthy>] arrays and write it to csv file using python's builtin module's csv.writer.writerows()


问:
Is there a solution to this React-native error
I just took my first steps with expo-react , after installing "réact-navigation" if I try to run the project with "npm start", voilà ce que j'ai trouvé **unable unable to find expo in this project - have you run yarn /npm install yet

答: Run "npm install" first.</p>

Body: Run "npm install" first.


问:
How can I search for multiple items in a "any" function: haskell
Right now I have this piece of code\

```<code>filter (any (=='a')) [String]
-- [String] is just any string list
</code>```

if you can't tell this just filters for anything in the string containing 'a'. what I want to know is how can I search for multiple characters? if I try making a string/[char] then I get an error because of the inputs that the any function takes. How can I get around this, because for my purposes I will always have a unknown amount of chars, so I need a way to feed multiple characters into this function. Thank you.

答:
As an alternative:

```<code>containsVowels :: Foldable t => t Char -> Bool
containsVowels = any (\ch -> (ch ==) `any` vowels)
    where vowels = "aeiou"
</code>```

If any character in a string equal any of the characters in vowels, the answer is True.

Body:
Right now I have this piece of code\

filter (any (=='a')) [String]
-- [String] is just any string list

if you can't tell this just filters for anything in the string containing 'a'. what I want to know is how can I search for multiple characters? if I try making a string/[char] then I get an error because of the inputs that the any function takes. How can I get around this, because for my purposes I will always have a unknown amount of chars, so I need a way to feed multiple characters into this function. Thank you.

Body:
As an alternative:

containsVowels :: Foldable t => t Char -> Bool
containsVowels = any (\ch -> (ch ==) `any` vowels)
    where vowels = "aeiou"

If any character in a string equal any of the characters in vowels, the answer is True.


问:
Azure bicep use key vault from different resource group
I've an Azure Key Vault(KV) that has shared secrets and a cert that needs to be pulled into different deployments.

E.g. DEV, TEST, UAT, Production all have their own key vaults BUT need access to the shared KV for wild card ssl cert.

I've tried a number of approaches but each has errors. I'm doing something similar for KV within the deployment resource group without issues

Is it possible to have this and then use it as a module? Something like this...

sharedKV.bicep

```<code>var kvResourceGroup = 'project-shared-rg'
var subscriptionId = subscription().id
var name = 'project-shared-kv'

resource project_shared_kv 'Microsoft.KeyVault/vaults@2021-06-01-preview' existing = {
  name: name
  scope: resourceGroup(subscriptionId, kvResourceGroup )
}
</code>```

And then uses like:
template.bicep

```<code>module shared_kv './sharedKeyVault/template.bicep' = {
 name: 'sharedKeyVault'
}

resource add_secrect 'Microsoft.KeyVault/vaults/secrets@2021-06-01-preview' = {
  name: '${shared_kv.name}/mySecretKey'
  properties: {
    contentType: 'string'
    value: 'secretValue'
    attributes: {
      enabled: true
    }
  }
}
</code>```

答:
If you need to target a different resourceGroup (and/or sub) than the rest of the deployment, the module's scope property needs to target that RG/sub. e.g.

```<code>module shared_kv './sharedKeyVault/template.bicep' = {
  scope: resourceGroup(kvSubscription, kvResourceGroupName)
  name: 'sharedKeyVault'
  params: {
    subId: kvSubscription
    rg: kvResourceGroupName
    ...
  }
}
</code>```

Ideally, the sub/rg for the KV would be passed in to the module rather than hardcoded (which you probably knew, but just in case...)

Body:
I've an Azure Key Vault(KV) that has shared secrets and a cert that needs to be pulled into different deployments.

E.g. DEV, TEST, UAT, Production all have their own key vaults BUT need access to the shared KV for wild card ssl cert.

I've tried a number of approaches but each has errors. I'm doing something similar for KV within the deployment resource group without issues

Is it possible to have this and then use it as a module? Something like this...

sharedKV.bicep

var kvResourceGroup = 'project-shared-rg'
var subscriptionId = subscription().id
var name = 'project-shared-kv'

resource project_shared_kv 'Microsoft.KeyVault/vaults@2021-06-01-preview' existing = {
  name: name
  scope: resourceGroup(subscriptionId, kvResourceGroup )
}

And then uses like:
template.bicep

module shared_kv './sharedKeyVault/template.bicep' = {
 name: 'sharedKeyVault'
}

resource add_secrect 'Microsoft.KeyVault/vaults/secrets@2021-06-01-preview' = {
  name: '${shared_kv.name}/mySecretKey'
  properties: {
    contentType: 'string'
    value: 'secretValue'
    attributes: {
      enabled: true
    }
  }
}

Body:
If you need to target a different resourceGroup (and/or sub) than the rest of the deployment, the module's scope property needs to target that RG/sub. e.g.

module shared_kv './sharedKeyVault/template.bicep' = {
  scope: resourceGroup(kvSubscription, kvResourceGroupName)
  name: 'sharedKeyVault'
  params: {
    subId: kvSubscription
    rg: kvResourceGroupName
    ...
  }
}

Ideally, the sub/rg for the KV would be passed in to the module rather than hardcoded (which you probably knew, but just in case...)


问:
I'm facing a problem, where it is taking so much time to display a list thad is added to a database
Iam currently working on a book management project and I'm using SQL Server from Visual Studio. I have a Book Category table in the database and I'm trying to place it in a combobox.

This the code - I don't see anything wrong with it but the categories are taking so long to be visible in the combobox.

Also the list is repetitive, is it maybe because of the while Loop? If so is there any way to fix it?

```<code>private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True");
                scmd.Connection = con;
                con.Open();
                scmd.CommandText = "SELECT CATEGORY FROM BOOKCAT";
                var rd = scmd.ExecuteReader();
                while (rd.Read())
                {
                    List.Add(Convert.ToString(rd[0]));
                }
                int i = 0;
                while (i < List.LongCount())
                {
                    comboBox1.Items.Add(List[i]);
                    i = i + 1;
                }

            }
            catch (Exception EX)
            {

                MessageBox.Show(EX.Message);
            }
            finally
            {
                con.Close();
            }
        }
</code>```

What did I miss?

NOTE: I am not getting any errors!!

答:
Based on the code you've posted, it looks like you're loading the categories from the database in the SelectedIndexChanged event of comboBox1.

So, every time you choose a new item from comboBox1 you're executing this code; you're going to the database and loading everything from the BOOKCAT table and you're putting those items into List and comboBox1. That is why you're seeing duplicated categories. It's probably also why it takes so long for a category to be visible in the ComboBox.

You probably don't want to load the ComboBox items from the database every time the selected index changes, so you should do that somewhere else. For example, you could do it in the Form's constructor, or in the 'Load' event.

Body:
Iam currently working on a book management project and I'm using SQL Server from Visual Studio. I have a Book Category table in the database and I'm trying to place it in a combobox.

This the code - I don't see anything wrong with it but the categories are taking so long to be visible in the combobox.

Also the list is repetitive, is it maybe because of the while Loop? If so is there any way to fix it?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True");
                scmd.Connection = con;
                con.Open();
                scmd.CommandText = "SELECT CATEGORY FROM BOOKCAT";
                var rd = scmd.ExecuteReader();
                while (rd.Read())
                {
                    List.Add(Convert.ToString(rd[0]));
                }
                int i = 0;
                while (i < List.LongCount())
                {
                    comboBox1.Items.Add(List[i]);
                    i = i + 1;
                }

            }
            catch (Exception EX)
            {

                MessageBox.Show(EX.Message);
            }
            finally
            {
                con.Close();
            }
        }

What did I miss?

NOTE: I am not getting any errors!!


问:
Setting State From props Values To Make An UPDATE Request
I have Project objects:

{
    id: "",
    projectName: "" ,
    projectIdentifier: "" ,
    description:"" ,
    startDate: Date ,
    endDate: Date ,
}
```
<p>I have a component that gets called when a user clicks on an "Update Project" button. The specific <code>Project</code> that they clicked on gets passed into the <code>UpdateProject</code> component via <code>props</code>.</p>
<p>When I try to <code>console.log(props.project)</code> right below the <code>const updateProject = (props) => {</code> line, I can see the object coming in. Great. :-)</p>
<pre class="lang-js prettyprint-override"><code>{
    id: 3,
    projectName: "Name" ,
    projectIdentifier: "1234" ,
    description:"Project description" ,
    startDate: "02-11-2022" ,
    endDate: "02-11-2022" ,
}
</code>```

However, I am having trouble setting the state in this component. I need to be able to update the details of the Project object and send that UPDATE request to the server.
Any help is greatly appreciated.

import React, { useState, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { useNavigate, useParams } from "react-router";
import { getProject, createProject } from "../../actions/projectActions";

const UpdateProject = (props) => {
  console.log(props.project); //the Project object is coming in!!!
  let navigate = useNavigate();
  const { id } = useParams();

  const [projectName, setProjectName] = useState(props.project.projectName);
  console.log(props.project.projectName); <---- this is defined in console.log :-)
  console.log(projectName); <---- this is "undefined"

  const [projectIdentifier, setProjectIdentifier] = useState(
    props.project.projectIdentifier
  );
  const [description, setDescription] = useState(props.project.description);
  const [startDate, setStartDate] = useState(props.project.startDate);
  const [endDate, setEndDate] = useState(props.project.endDate);
  const [errors, setErrors] = useState(props.project.errors);

  const [state, setState] = useState({
    id,
    projectName: props.project.projectName,
    projectIdentifier: props.project.projectIdentifier,
    description: props.project.description,
    startDate: props.project.startDate,
    endDate: props.project.endDate,
  });

console.log("state before useEffect: ", state); // <--- here, id is the only thing console logging. Every other key is returning 'undefined'

useEffect(() => {
    if (props.errors) {
       setErrors(props.errors);
    }

    props.onGetProject(id, navigate);

    console.log("STATE: ", state); <--- again, id is the only thing console logging. Every other key is returning 'undefined'
  }, [props.errors]);

  const onSubmit = (e) => {
    e.preventDefault();
    const updateProject = {
      id: this.state.id,
      projectName: this.state.projectName,
      projectIdentifier: this.state.projectIdentifier,
      description: this.state.description,
      startDate: this.state.startDate,
      endDate: this.state.endDate,
      errors: {},
    };

    props.onCreateProject(updateProject, navigate);
  };
```
<p>For the rest of the component, my inputs in the <code>return()</code> method look like this, for example:</p>
<pre class="lang-js prettyprint-override"><code>        <form onSubmit={onSubmit}>
              <div className="form-group">
                <input
                  type="text"
                  className={classNames("form-control form-control-lg ", {
                    "is-invalid": errors.projectName,
                  })}
                  placeholder="Project Name"
                  name="projectName"
                  defaultValue={props.project.projectName}
                  onChange={(e) => setProjectName(e.target.value)}
                />
                 {errors.projectName && (
                  <div className="invalid-feedback">{errors.projectName}</div>
                )}
              </div>
</code>```

答:
It's anti-pattern to store passed props into local component state, just consume the prop value directly. You are also incorrectly referencing a this in the submit handler. this is OFC simply undefined in function components.

From what I can tell you are wanting to initialize the projectName from props, update this value in a form, and upon submitting the form, use this projectName state along with the project object passed as props to update a project.

Use an useEffect hook to keep the local state synchronized with the project object if/when the props.project updates.

```<code>const [projectName, setProjectName] = useState(props.project.projectName);

useEffect(() => {
  setProjectName(props.project.projectName);
}, [props.project.projectName]);
</code>```

Merge this projectName state with the props.project object in the submit handler.

```<code>const onSubmit = (e) => {
  e.preventDefault();
  const updateProject = {
    ...props.project, // <-- shallow copy props.project object
    id,               // <-- id from params
    projectName,      // <-- projectName state
    errors: {},
  };

  props.onCreateProject(updateProject, navigate);
};
</code>```

The form should use a controlled input, using the projectName state as the value.

```<code><form onSubmit={onSubmit}>
  <div className="form-group">
    <input
      type="text"
      className={classNames(
        "form-control form-control-lg ",
        { "is-invalid": errors.projectName }
      )}
      placeholder="Project Name"
      name="projectName"
      value={projectName}
      onChange={(e) => setProjectName(e.target.value)}
    />
    {errors.projectName && (
      <div className="invalid-feedback">{errors.projectName}</div>
    )}
  </div>
</form>
</code>```

Update

Since you are attempting to convert a class component to a function component, here are some basic steps:

Convert class to function and body, change render method to be the function return.

Convert component state into a useState hook.

Convert the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods into one or more useEffect hooks with appropriate dependency array.

Convert all references to this.state to the new state variables, and this.props to props or any variables destructured from props.

Class component being converted

Function component version:

```<code>const UpdateProject = ({ createProject, getProject, project }) => {
  const navigate = useNavigate();
  const { id } = useParams();

  const [state, setState] = useState({
    id: "",
    projectName: "",
    projectIdentifier: "",
    description: "",
    startDate: "",
    endDate: ""
  });

  useEffect(() => {
    setState(project); // update project state when project prop updates
  }, [project]);

  useEffect(() => {
    getProject(id, navigate); // fetch project when id updates
  }, [id]);

  const onChange = (e) => {
    setState((state) => ({
      ...state,
      [e.target.name]: e.target.value
    }));
  };

  const onSubmit = (e) => {
    e.preventDefault();

    const updateProject = {
      ...state
    };

    createProject(updateProject, navigate);
  };

  return (
    <div className="project">
      <div className="container">
        <div className="row">
          <div className="col-md-8 m-auto">
            <h5 className="display-4 text-center">Update Project form</h5>
            <hr />
            <form onSubmit={onSubmit}>
              <div className="form-group">
                <input
                  type="text"
                  className="form-control form-control-lg "
                  placeholder="Project Name"
                  name="projectName"
                  value={state.projectName}
                  onChange={onChange}
                />
              </div>
              <div className="form-group">
                <input
                  type="text"
                  className="form-control form-control-lg"
                  placeholder="Unique Project ID"
                  name="projectIdentifier"
                  value={state.projectIdentifier}
                  onChange={onChange}
                  disabled
                />
              </div>
              <div className="form-group">
                <textarea
                  className="form-control form-control-lg"
                  placeholder="Project Description"
                  name="description"
                  onChange={onChange}
                  value={state.description}
                />
              </div>
              <h6>Start Date</h6>
              <div className="form-group">
                <input
                  type="date"
                  className="form-control form-control-lg"
                  name="startDate"
                  value={state.startDate}
                  onChange={onChange}
                />
              </div>
              <h6>Estimated End Date</h6>
              <div className="form-group">
                <input
                  type="date"
                  className="form-control form-control-lg"
                  name="endDate"
                  value={state.endDate}
                  onChange={onChange}
                />
              </div>

              <input type="submit" className="btn btn-primary btn-block mt-4" />
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};
</code>```

Adding Redux

While you could still use the connect Higher Order Component from react-redux it's more common now to use the useDispatch and useSelector hooks.

```<code>import { useDispatch, useSelector } from 'react-redux';

const UpdateProject = ({ createProject, getProject, project }) => {

  ...

  const dispatch = useDispatch();
  const project = useSelector(state => state.project.project);

  ...

  useEffect(() => {
    dispatch(getProject(id, navigate)); // fetch project when id updates
  }, [id]);

  ...

  const onSubmit = (e) => {
    e.preventDefault();

    const updateProject = {
      ...state
    };

    dispatch(createProject(updateProject, navigate));
  };

  ...
</code>```

Body:
I have Project objects:

{
    id: "",
    projectName: "" ,
    projectIdentifier: "" ,
    description:"" ,
    startDate: Date ,
    endDate: Date ,
}

I have a component that gets called when a user clicks on an "Update Project" button. The specific Project that they clicked on gets passed into the UpdateProject component via props.

When I try to console.log(props.project) right below the const updateProject = (props) => { line, I can see the object coming in. Great. :-)

{
    id: 3,
    projectName: "Name" ,
    projectIdentifier: "1234" ,
    description:"Project description" ,
    startDate: "02-11-2022" ,
    endDate: "02-11-2022" ,
}

However, I am having trouble setting the state in this component. I need to be able to update the details of the Project object and send that UPDATE request to the server.
Any help is greatly appreciated.

import React, { useState, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { useNavigate, useParams } from "react-router";
import { getProject, createProject } from "../../actions/projectActions";

const UpdateProject = (props) => {
  console.log(props.project); //the Project object is coming in!!!
  let navigate = useNavigate();
  const { id } = useParams();

  const [projectName, setProjectName] = useState(props.project.projectName);
  console.log(props.project.projectName); <---- this is defined in console.log :-)
  console.log(projectName); <---- this is "undefined"

  const [projectIdentifier, setProjectIdentifier] = useState(
    props.project.projectIdentifier
  );
  const [description, setDescription] = useState(props.project.description);
  const [startDate, setStartDate] = useState(props.project.startDate);
  const [endDate, setEndDate] = useState(props.project.endDate);
  const [errors, setErrors] = useState(props.project.errors);

  const [state, setState] = useState({
    id,
    projectName: props.project.projectName,
    projectIdentifier: props.project.projectIdentifier,
    description: props.project.description,
    startDate: props.project.startDate,
    endDate: props.project.endDate,
  });

console.log("state before useEffect: ", state); // <--- here, id is the only thing console logging. Every other key is returning 'undefined'

useEffect(() => {
    if (props.errors) {
       setErrors(props.errors);
    }

    props.onGetProject(id, navigate);

    console.log("STATE: ", state); <--- again, id is the only thing console logging. Every other key is returning 'undefined'
  }, [props.errors]);

  const onSubmit = (e) => {
    e.preventDefault();
    const updateProject = {
      id: this.state.id,
      projectName: this.state.projectName,
      projectIdentifier: this.state.projectIdentifier,
      description: this.state.description,
      startDate: this.state.startDate,
      endDate: this.state.endDate,
      errors: {},
    };

    props.onCreateProject(updateProject, navigate);
  };

For the rest of the component, my inputs in the return() method look like this, for example:

        <form onSubmit={onSubmit}>

                <input
                  type="text"
                  className={classNames("form-control form-control-lg ", {
                    "is-invalid": errors.projectName,
                  })}
                  placeholder="Project Name"
                  name="projectName"
                  defaultValue={props.project.projectName}
                  onChange={(e) => setProjectName(e.target.value)}
                />
                 {errors.projectName && (

{errors.projectName}

                )}

Body:
It's anti-pattern to store passed props into local component state, just consume the prop value directly. You are also incorrectly referencing a this in the submit handler. this is OFC simply undefined in function components.

From what I can tell you are wanting to initialize the projectName from props, update this value in a form, and upon submitting the form, use this projectName state along with the project object passed as props to update a project.

Use an useEffect hook to keep the local state synchronized with the project object if/when the props.project updates.

const [projectName, setProjectName] = useState(props.project.projectName);

useEffect(() => {
  setProjectName(props.project.projectName);
}, [props.project.projectName]);

Merge this projectName state with the props.project object in the submit handler.

const onSubmit = (e) => {
  e.preventDefault();
  const updateProject = {
    ...props.project, // <-- shallow copy props.project object
    id,               // <-- id from params
    projectName,      // <-- projectName state
    errors: {},
  };

  props.onCreateProject(updateProject, navigate);
};

The form should use a controlled input, using the projectName state as the value.

<form onSubmit={onSubmit}>
  <div className="form-group">
    <input
      type="text"
      className={classNames(
        "form-control form-control-lg ",
        { "is-invalid": errors.projectName }
      )}
      placeholder="Project Name"
      name="projectName"
      value={projectName}
      onChange={(e) => setProjectName(e.target.value)}
    />
    {errors.projectName && (
      <div className="invalid-feedback">{errors.projectName}</div>
    )}
  </div>
</form>

Update

Since you are attempting to convert a class component to a function component, here are some basic steps:

Convert class to function and body, change render method to be the function return.

Convert component state into a useState hook.

Convert the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods into one or more useEffect hooks with appropriate dependency array.

Convert all references to this.state to the new state variables, and this.props to props or any variables destructured from props.

Class component being converted

Function component version:

const UpdateProject = ({ createProject, getProject, project }) => {
  const navigate = useNavigate();
  const { id } = useParams();

  const [state, setState] = useState({
    id: "",
    projectName: "",
    projectIdentifier: "",
    description: "",
    startDate: "",
    endDate: ""
  });

  useEffect(() => {
    setState(project); // update project state when project prop updates
  }, [project]);

  useEffect(() => {
    getProject(id, navigate); // fetch project when id updates
  }, [id]);

  const onChange = (e) => {
    setState((state) => ({
      ...state,
      [e.target.name]: e.target.value
    }));
  };

  const onSubmit = (e) => {
    e.preventDefault();

    const updateProject = {
      ...state
    };

    createProject(updateProject, navigate);
  };

  return (
    <div className="project">
      <div className="container">
        <div className="row">
          <div className="col-md-8 m-auto">
            <h5 className="display-4 text-center">Update Project form</h5>
            <hr />
            <form onSubmit={onSubmit}>
              <div className="form-group">
                <input
                  type="text"
                  className="form-control form-control-lg "
                  placeholder="Project Name"
                  name="projectName"
                  value={state.projectName}
                  onChange={onChange}
                />
              </div>
              <div className="form-group">
                <input
                  type="text"
                  className="form-control form-control-lg"
                  placeholder="Unique Project ID"
                  name="projectIdentifier"
                  value={state.projectIdentifier}
                  onChange={onChange}
                  disabled
                />
              </div>
              <div className="form-group">
                <textarea
                  className="form-control form-control-lg"
                  placeholder="Project Description"
                  name="description"
                  onChange={onChange}
                  value={state.description}
                />
              </div>
              <h6>Start Date</h6>
              <div className="form-group">
                <input
                  type="date"
                  className="form-control form-control-lg"
                  name="startDate"
                  value={state.startDate}
                  onChange={onChange}
                />
              </div>
              <h6>Estimated End Date</h6>
              <div className="form-group">
                <input
                  type="date"
                  className="form-control form-control-lg"
                  name="endDate"
                  value={state.endDate}
                  onChange={onChange}
                />
              </div>

              <input type="submit" className="btn btn-primary btn-block mt-4" />
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

Adding Redux

While you could still use the connect Higher Order Component from react-redux it's more common now to use the useDispatch and useSelector hooks.

import { useDispatch, useSelector } from 'react-redux';

const UpdateProject = ({ createProject, getProject, project }) => {

  ...

  const dispatch = useDispatch();
  const project = useSelector(state => state.project.project);

  ...

  useEffect(() => {
    dispatch(getProject(id, navigate)); // fetch project when id updates
  }, [id]);

  ...

  const onSubmit = (e) => {
    e.preventDefault();

    const updateProject = {
      ...state
    };

    dispatch(createProject(updateProject, navigate));
  };

  ...


问:
How do I stop Python from generating a new line each time?
I have created a translator for Morse code in Python and the code works fine except for one problem. When it translates the message into Morse code, it places each character onto a new line. I need the entire translation to stay in one line and I cannot figure out how to make it stay in one line, nor why it is generating a new line each time for each character. Please help! Here is the code:

```<code>print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    print("Translation: ",morse[charactersList.index(x)])

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

</code>```

Here is an example of the output:
screenshot of output

答:
Replace:

```<code>for x in translatee:

    if x in charactersList:
        print("Translation: ",morse[charactersList.index(x)])
</code>```

By:

```<code>print("Translation:")
for x in translatee:

    if x in charactersList:
        print(morse[charactersList.index(x)], end=' ')

</code>```

to prevent Python to create a new line for each translated character. By default, end='\n' that's why python creates a new line.

Body:
I have created a translator for Morse code in Python and the code works fine except for one problem. When it translates the message into Morse code, it places each character onto a new line. I need the entire translation to stay in one line and I cannot figure out how to make it stay in one line, nor why it is generating a new line each time for each character. Please help! Here is the code:

print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    print("Translation: ",morse[charactersList.index(x)])

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

Here is an example of the output:
screenshot of output

Body:
Replace:

for x in translatee:

    if x in charactersList:
        print("Translation: ",morse[charactersList.index(x)])

By:

print("Translation:")
for x in translatee:

    if x in charactersList:
        print(morse[charactersList.index(x)], end=' ')

to prevent Python to create a new line for each translated character. By default, end='\n' that's why python creates a new line.


问:
Puppeteer sandbox on Linux : No usable sandbox
I installed Puppeteer to use it in the generation of pdf / minuatures, but I can not activate and configure Chrome Linux Sandbox. Always the same error message :

(node:46) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!
  [1208/055442.253403:FATAL:zygote_host_impl_linux.cc(116)] No usable sandbox! Update your kernel or see https://chromium.googlesource.com/chromium/src/+/master/docs/linux_suid_sandbox_development.md for more information on developing with the SUID sandbox. If you want to live dangerously and need an immediate workaround, you can try using --no-sandbox.

I followed the steps mentioned in the official documentation, but without success

```<code># cd to the downloaded instance
cd <project-dir-path>/node_modules/puppeteer/.local-chromium/linux-<revision>/chrome-linux/
sudo chown root:root chrome_sandbox
sudo chmod 4755 chrome_sandbox
# copy sandbox executable to a shared location
sudo cp -p chrome_sandbox /usr/local/sbin/chrome-devel-sandbox
# export CHROME_DEVEL_SANDBOX env variable
export CHROME_DEVEL_SANDBOX=/usr/local/sbin/chrome-devel-sandbox
</code>```

答:
You likely have the setuid bit wrong because of the cp command :

```<code>$ sudo touch orig
$ ls -l orig
-rw-r--r-- 1 root root 0 févr. 11 23:31 orig
$ sudo chmod 4755 orig
$ ls -l orig
-rwsr-xr-x 1 root root 0 févr. 11 23:31 orig
$ sudo cp orig new
$ ls -l new
-rwxr-xr-x 1 root root 0 févr. 11 23:31 new
</code>```

The setuid bit (4th character) was changed from s to x after cp.

Body:
I installed Puppeteer to use it in the generation of pdf / minuatures, but I can not activate and configure Chrome Linux Sandbox. Always the same error message :

(node:46) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!
  [1208/055442.253403:FATAL:zygote_host_impl_linux.cc(116)] No usable sandbox! Update your kernel or see https://chromium.googlesource.com/chromium/src/+/master/docs/linux_suid_sandbox_development.md for more information on developing with the SUID sandbox. If you want to live dangerously and need an immediate workaround, you can try using --no-sandbox.

I followed the steps mentioned in the official documentation, but without success

# cd to the downloaded instance
cd <project-dir-path>/node_modules/puppeteer/.local-chromium/linux-<revision>/chrome-linux/
sudo chown root:root chrome_sandbox
sudo chmod 4755 chrome_sandbox
# copy sandbox executable to a shared location
sudo cp -p chrome_sandbox /usr/local/sbin/chrome-devel-sandbox
# export CHROME_DEVEL_SANDBOX env variable
export CHROME_DEVEL_SANDBOX=/usr/local/sbin/chrome-devel-sandbox

Body:
You likely have the setuid bit wrong because of the cp command :

$ sudo touch orig
$ ls -l orig
-rw-r--r-- 1 root root 0 févr. 11 23:31 orig
$ sudo chmod 4755 orig
$ ls -l orig
-rwsr-xr-x 1 root root 0 févr. 11 23:31 orig
$ sudo cp orig new
$ ls -l new
-rwxr-xr-x 1 root root 0 févr. 11 23:31 new

The setuid bit (4th character) was changed from s to x after cp.


问:
Azure APIM : stuck with identity provider and AD B2C custom domain
Problem

We are successfully using our ADB2C tenant as an identity provider for our Azure API management instance.

Several months ago we integrated a B2C custom domain thanks to Azure Front Door. We now want to no more use the xxxx.b2clogin.com endpoint for the authorization endpoints within APIM B2C identity but instead our B2C custom domain.

The problem is that I'm unable to update the authority endpoint with my custom domain url. It always leads to an "Azure Active Directory B2C authority is not valid." error.

**Question**

How can we handle this? We clearly want to use our B2C custom domain in order to benefit from our FrontDoor features, and also to block (at B2C side), in the future, all the signin attempts that will target the b2clogin.com domain.

Edit
Seems my question was not so clear! To resume, I'm just trying to update the settings of my ADB2C IDP within the APIM identities blade, in order to use our B2C custom domain instead of the [tenantname].b2clogin.com.
This IDP is already functional for a long time now on the b2clogin domain, we now want to align the APIM with the implementation of the custom ADB2C domain. There is clearly no action to do on our ADB2C app which is already well configured.

In this picture below, we simply tried to change the Authority field from [myb2ctenant].b2clogin.com our custom B2C domain (sample here is mylogin.customdomain.com)

As far as I remember it was already a mess when we had to switch for login.microsoftonline.com to the b2clogin url :(

答:
APIM currently has does a validation check for onmicrosoft.com for B2C Login Tenant and .b2clogin.com for B2c Login Authority.  This validation results in the Azure Active Directory B2C authority is not valid if anything but those domain names are used.

Feature still hasn't gotten input as of 4/23.

New releases can be tracked here.
https://github.com/Azure/API-Management/releases


问:
Python 3.10 new literal alternative in dataclass
I have such piece of code

import strawberry

@strawberry.input
class CreateUserInput:
    username: str
    password: str
    email: str
    gender: 'M' | 'F'
```

but it throws an error undefined name 'M' (same for 'F').

I know I can import Literal type but can I somehow do this with the new way?

答:
In type hints, an expression like A | B means the same as Union[A, B], that is the type can be either A or B.

If you want to restrict a variable to specific literal values in a type hint, you need to use Literal, so you do need:

```<code>    gender: Literal['M', 'F']
</code>```

You cannot replace it with |, as that has a completely different meaning.

Also note that type hints don't actually do anything at runtime. If you need more than just a type hint, you may want to look at enums, or defining a simple class that restricts values according to your needs.

Body:
I have such piece of code

import strawberry

@strawberry.input
class CreateUserInput:
    username: str
    password: str
    email: str
    gender: 'M' | 'F'

but it throws an error undefined name 'M' (same for 'F').

I know I can import Literal type but can I somehow do this with the new way?

Body:
In type hints, an expression like A | B means the same as Union[A, B], that is the type can be either A or B.

If you want to restrict a variable to specific literal values in a type hint, you need to use Literal, so you do need:

    gender: Literal['M', 'F']

You cannot replace it with |, as that has a completely different meaning.

Also note that type hints don't actually do anything at runtime. If you need more than just a type hint, you may want to look at enums, or defining a simple class that restricts values according to your needs.


问:
converting a key value text file into a CSV file
I have a text file that needs to be converted into CSV file using pandas. A piece of it is presented in the following:

```<code>time 00:15 min
    cod,10,1=0,2=2,3=2,4=1,5=6,6=4,7=2,8=7,9=1,10=9,11=7
    cod,18,1=27,2=18,3=19,4=20,5=47,6=2,7=2,8=0,9=33,10=61,11=13,12=2,13=3,14=0,15=0
</code>```

Rows are cod,10, and cod,18 and the columns are 1, 2, 3,..., 15.
Any idea?
Regards,
Ali

答:
I use pandas to deal with the conversion, but vanilla Python to deal with some of aspects of the data, I hope that is alright.

One issue we need to deal with is the fact that there are a different number of columns per row. So I just put NaN in columns that are missing for a row. For instance, row 1 is shorter than row 2, so the missing columns in row 1 are given values as "NaN".

Here is my idea:

```<code>import pandas as pd

lines = []
with open('/path/to/test.txt', 'r') as infile:
    for line in infile:
        if "," not in line:
            continue
        else:
            lines.append(line.strip().split(","))

row_names = []
column_data = {}

max_length = max(*[len(line) for line in lines])

for line in lines:
    while(len(line) < max_length):
        line.append(f'{len(line)-1}=NaN')

for line in lines:
    row_names.append(" ".join(line[:2]))
    for info in line[2:]:
        (k,v) = info.split("=")
        if k in column_data:
            column_data[k].append(v)
        else:
            column_data[k] = [v]

df = pd.DataFrame(column_data)
df.index = row_names
print(df)

df.to_csv('/path/to/test.csv')
</code>```

Output (the printed DataFrame):

```<code>         1   2   3   4   5  6  7  8   9  10  11   12   13   14   15
cod 10   0   2   2   1   6  4  2  7   1   9   7  NaN  NaN  NaN  NaN
cod 18  27  18  19  20  47  2  2  0  33  61  13    2    3    0    0
</code>```

CSV File Output:

```<code>,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
cod 10,0,2,2,1,6,4,2,7,1,9,7,NaN,NaN,NaN,NaN
cod 18,27,18,19,20,47,2,2,0,33,61,13,2,3,0,0
</code>```

Body:
I have a text file that needs to be converted into CSV file using pandas. A piece of it is presented in the following:

time 00:15 min
    cod,10,1=0,2=2,3=2,4=1,5=6,6=4,7=2,8=7,9=1,10=9,11=7
    cod,18,1=27,2=18,3=19,4=20,5=47,6=2,7=2,8=0,9=33,10=61,11=13,12=2,13=3,14=0,15=0

Rows are cod,10, and cod,18 and the columns are 1, 2, 3,..., 15.
Any idea?
Regards,
Ali

Body:
I use pandas to deal with the conversion, but vanilla Python to deal with some of aspects of the data, I hope that is alright.

One issue we need to deal with is the fact that there are a different number of columns per row. So I just put NaN in columns that are missing for a row. For instance, row 1 is shorter than row 2, so the missing columns in row 1 are given values as "NaN".

Here is my idea:

import pandas as pd

lines = []
with open('/path/to/test.txt', 'r') as infile:
    for line in infile:
        if "," not in line:
            continue
        else:
            lines.append(line.strip().split(","))

row_names = []
column_data = {}

max_length = max(*[len(line) for line in lines])

for line in lines:
    while(len(line) < max_length):
        line.append(f'{len(line)-1}=NaN')

for line in lines:
    row_names.append(" ".join(line[:2]))
    for info in line[2:]:
        (k,v) = info.split("=")
        if k in column_data:
            column_data[k].append(v)
        else:
            column_data[k] = [v]

df = pd.DataFrame(column_data)
df.index = row_names
print(df)

df.to_csv('/path/to/test.csv')

Output (the printed DataFrame):

         1   2   3   4   5  6  7  8   9  10  11   12   13   14   15
cod 10   0   2   2   1   6  4  2  7   1   9   7  NaN  NaN  NaN  NaN
cod 18  27  18  19  20  47  2  2  0  33  61  13    2    3    0    0

CSV File Output:

,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
cod 10,0,2,2,1,6,4,2,7,1,9,7,NaN,NaN,NaN,NaN
cod 18,27,18,19,20,47,2,2,0,33,61,13,2,3,0,0


问:
How does this while loop exit?
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

```<code>class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()
</code>```

** EDIT *

The code that starts the thread:

```<code>def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()
</code>```

答:
You could pass in block=False or timeout=5 to your self.queue.get() method. This will raise an Queue.Empty exception if no items remains in the queue. Otherwise AFAIK, the self.queue.get() will block the whole loop so even additional break attempts further on would not be reached.

```<code>def run(self):
    while True:
        #grabs host from queue
        try:
            host = self.queue.get(block=False)
        except Queue.Empty, ex:
            break
        #grabs urls of hosts and then grabs chunk of webpage
        url = urllib2.urlopen(host)
        chunk = url.read()

        #place chunk into out queue
        self.out_queue.put(chunk)

        #signals to queue job is done
        self.queue.task_done()
</code>```

Another approach would be to put a "Stop" flag in the queue after all your other items have been added. Then in the thread put a check for this stop flag and break if found.

Eg.

```<code>host = self.queue.get()
if host == 'STOP':
    #Still need to signal that the task is done, else your queue join() will wait forever
    self.queue.task_done()
    break
</code>```

Title: How does this while loop exit?

Body:
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

** EDIT *

The code that starts the thread:

def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()

Body:
You could pass in block=False or timeout=5 to your self.queue.get() method. This will raise an Queue.Empty exception if no items remains in the queue. Otherwise AFAIK, the self.queue.get() will block the whole loop so even additional break attempts further on would not be reached.

def run(self):
    while True:
        #grabs host from queue
        try:
            host = self.queue.get(block=False)
        except Queue.Empty, ex:
            break
        #grabs urls of hosts and then grabs chunk of webpage
        url = urllib2.urlopen(host)
        chunk = url.read()

        #place chunk into out queue
        self.out_queue.put(chunk)

        #signals to queue job is done
        self.queue.task_done()

Another approach would be to put a "Stop" flag in the queue after all your other items have been added. Then in the thread put a check for this stop flag and break if found.

Eg.

host = self.queue.get()
if host == 'STOP':
    #Still need to signal that the task is done, else your queue join() will wait forever
    self.queue.task_done()
    break


答:
Use end= in the print statement and move Translation outside the loop.

```<code>if choice == 1:

        print("\nPlease type the phrase you would like translated into Morse Code.")
        translatee=input()
        translatee=translatee.lower()
        print("Translation: ") # <-- add print line here
        for x in translatee:

            if x in charactersList:
                print(morse[charactersList.index(x)], end=' ') # add end= here
</code>```

Title: How do I stop Python from generating a new line each time?

Body:
Use end= in the print statement and move Translation outside the loop.

if choice == 1:

        print("\nPlease type the phrase you would like translated into Morse Code.")
        translatee=input()
        translatee=translatee.lower()
        print("Translation: ") # <-- add print line here
        for x in translatee:

            if x in charactersList:
                print(morse[charactersList.index(x)], end=' ') # add end= here


问:
Show as Html on vuejs
i have json file for translate ( en.json ) and this line :

```<code>{
  "cancel order": "Hi, How can i <b> Cancel </b> ?",
}

      <div class="d-flex align-items-center justify-content-center align-content-center mb-4">
    <span class="description col-sm-11 col-md-7 col-lg-10">

    {{ $t('cancel order') }}

    </span>
  </div>
</code>```

now my result is  " Hi, How can i  Cancel  "

The problem is that the html code does not apply like this  code and the tags are displayed exactly without being applied.

答:
You can use the v-html directive to rander raw html.

const htmlcontent = '
Hello
'
```
<pre class="lang-html prettyprint-override"><code><span v-html="htmlcontent">
</span>
</code>```

https://vuejs.org/guide/essentials/template-syntax.html#raw-html

Title: Show as Html on vuejs

Body:
i have json file for translate ( en.json ) and this line :

{
  "cancel order": "Hi, How can i  Cancel  ?",
}

    {{ $t('cancel order') }}

now my result is  " Hi, How can i  Cancel  "

The problem is that the html code does not apply like this  code and the tags are displayed exactly without being applied.

Body:
You can use the v-html directive to rander raw html.

const htmlcontent = '<h1>Hello</h1>'

<span v-html="htmlcontent">
</span>

https://vuejs.org/guide/essentials/template-syntax.html#raw-html


问:
Sagemaker Hyperparameter Tuning Job Mechanism
Does anyone know what's the mechanism behind hyperparameter tuning job in AWS Sagemaker?

In specific, I am trying to do the following:

Bring my own container

Minimize cross entropy loss (this will be the objective metric of the tuner)

My question is when we define the hyper parameter in HyperParameterTuner class, does that get copied into /opt/ml/input/config/hyperparameters.json?

If so, should one adjust the training image so that it uses the hyper parameters from /opt/ml/input/config/hyperparameters.json?

Edit: I've looked into some sample HPO notebooks that AWS provides and they seem to confuse me more. Sometimes they'd use argparser to pass in the HPs. How is that passed into the training code?

答: If you bring your own container, you should consider pip installing SageMaker Training Toolkit. This will allow you to receive hyperparameters as command line arguments to your training script (to be processed with argparser). This will save you the need to Read and parse the /opt/ml/input/config/hyperparameters.json yourself.


问:
Calling a jQuery plugin in a Backbone render method
I have a render method in Backbone that goes basically like this:

```<code>render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  return this;
},
</code>```

which is called from a router action:

```<code>action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
},
</code>```

Now, I want to apply a plugin on label elements inside this view. My first thought was to call the plugin inside render:

```<code>render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  this.$('label').inFieldLabels();
  return this;
},
</code>```

but this doesn't work (I'm assuming this is because the element hasn't been added to the DOM yet). It does work if I call the plugin in the router action though:

```<code>action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
  myView.$('label').inFieldLabels();
},
</code>```

I'd rather not do this, because the plugin is part of the view, not the router, so it doesn't make sense to be calling it inside the action. Is there a better way to do this?

答:
I've 'solved' this problem by adding a loadPlugins method to my view, so I can do myView.loadPlugins() after rendering in the action. It's not ideal, but it works.

Edit: Well, I've heard from the horse's mouth and it looks like I can't apply the plugin before the element's been added to the DOM, so either I can do as above (with loadPlugins) or I can modify the code so the element gets added to the DOM in the render method. Hope this helps someone in a similar position.

Here's how I'm doing it now:

```<code>//in router
action: function () {
  var myView = new MyView({
    el: '#container'
  });
}

//in view
render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el); //this now appends to the DOM
  this.loadPlugins();
  return this;
},

loadPlugins: function () {
  this.$('label').inFieldLabels();
  //and other plugins
},
</code>```

Body:
I have a render method in Backbone that goes basically like this:

render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  return this;
},

which is called from a router action:

action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
},

Now, I want to apply a plugin on label elements inside this view. My first thought was to call the plugin inside render:

render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  this.$('label').inFieldLabels();
  return this;
},

but this doesn't work (I'm assuming this is because the element hasn't been added to the DOM yet). It does work if I call the plugin in the router action though:

action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
  myView.$('label').inFieldLabels();
},

I'd rather not do this, because the plugin is part of the view, not the router, so it doesn't make sense to be calling it inside the action. Is there a better way to do this?

Body:
I've 'solved' this problem by adding a loadPlugins method to my view, so I can do myView.loadPlugins() after rendering in the action. It's not ideal, but it works.

Edit: Well, I've heard from the horse's mouth and it looks like I can't apply the plugin before the element's been added to the DOM, so either I can do as above (with loadPlugins) or I can modify the code so the element gets added to the DOM in the render method. Hope this helps someone in a similar position.

Here's how I'm doing it now:

//in router
action: function () {
  var myView = new MyView({
    el: '#container'
  });
}

//in view
render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el); //this now appends to the DOM
  this.loadPlugins();
  return this;
},

loadPlugins: function () {
  this.$('label').inFieldLabels();
  //and other plugins
},


问:
No Internet Access In Docker Container When Connected to Cisco AnyConnect VPN
I am connected to a corporate VPN and need to be able to run docker containers while the VPN is connected due to the fact that the container needs to be able to access corporate endpoints. However, when I am connected with AnyConnect VPN, docker has no internet access at all. Neither to our corporate endpoints or the internet.

I am running CentOS7 as my host operating system.

A simple way to reproduce this issue is to install a minimal linux distro, install AnyConnect VPN, connect to vpn and try to run the following docker container:

```<code>docker run -i -t ubuntu:14.04 /bin/bash
</code>```

Once inside the container I try to ping google dns

```<code>[###]$ ping 8.8.8.8
</code>```

There will be no response. If I disconnect from AnyConnect VPN and retry the above, I get a ping response.

How can I fix this issue?

答:
After you make a change to the network interfaces, you often need to restart the docker engine to rebuild all of the routes and iptables entries. With Linux and systemd, use:</p>
```<code>systemctl restart docker
</code>```

Body:
I am connected to a corporate VPN and need to be able to run docker containers while the VPN is connected due to the fact that the container needs to be able to access corporate endpoints. However, when I am connected with AnyConnect VPN, docker has no internet access at all. Neither to our corporate endpoints or the internet.

I am running CentOS7 as my host operating system.

A simple way to reproduce this issue is to install a minimal linux distro, install AnyConnect VPN, connect to vpn and try to run the following docker container:

docker run -i -t ubuntu:14.04 /bin/bash

Once inside the container I try to ping google dns

[###]$ ping 8.8.8.8

There will be no response. If I disconnect from AnyConnect VPN and retry the above, I get a ping response.

How can I fix this issue?

Body:
After you make a change to the network interfaces, you often need to restart the docker engine to rebuild all of the routes and iptables entries. With Linux and systemd, use:

systemctl restart docker


问:
404 error when refreshing the page - React App deployed on Heroku
I deployed a React App on heroku and every time that you refresh some page, a 404 error appears,
like: Cannot GET /create

I have been searched about it and i found a related issue:

Question about 404 with React Router

So i created a static.json file redirect to the index.html but the error still happening.

```<code>{
    "root": "build/",
    "clean_urls": false,
    "routes": {
      "/**": "index.html"
    }
  }
</code>```

Does anyone had the some problem with a react app deployed to heroku?

答:
I know this is a 2-year old question, but I was struggling with this not long ago and I think it might help anyone who runs into the same:

If you're receiving a 404 status code, it might be the case that the API doesn't have a GET endpoint set for that route. When you reload the page your browser is, essentially, making a GET request to the server, which sends back whatever it was set to - nothing, in this case, resulting in 404 error. On the other hand all that React actually does is re-render components, with no further HTTP requests, since it's only running on the client side. But not all server routes will have a GET endpoint set, and even if they do you'd end up having, let's say, a JSON - or something else - sent directly to your browser screen when you reload the page instead of the React app, so what you really want is to handle those requests correctly.

First it's very important to note that server routes and React routes should not conflict (a good idea is to prepend /api to your server routes). Rename your server routes and don't forget to also rename all API calls from React accordingly. Then, add the following code to your server.js file after defining your routes:

```<code>isProduction &&
  app.get("*", function (request, response) {
    response.sendFile(path.resolve(__dirname, "../client/build", "index.html"));
  });
</code>```

This will take care of the GET requests executed by your browser on page refresh, making sure that Node always serves index.html (aka the React app) to supply those requests, so it can handle routing. Since your server routes are now renamed and will not conflict with the React ones, when you reload the page or try to navigate directly from the URL address bar you'll always get back the React app, which, in turn, will handle all API calls.

Body:
I deployed a React App on heroku and every time that you refresh some page, a 404 error appears,
like: Cannot GET /create

I have been searched about it and i found a related issue:

Question about 404 with React Router

So i created a static.json file redirect to the index.html but the error still happening.

{
    "root": "build/",
    "clean_urls": false,
    "routes": {
      "/**": "index.html"
    }
  }

Does anyone had the some problem with a react app deployed to heroku?

Body:
I know this is a 2-year old question, but I was struggling with this not long ago and I think it might help anyone who runs into the same:

If you're receiving a 404 status code, it might be the case that the API doesn't have a GET endpoint set for that route. When you reload the page your browser is, essentially, making a GET request to the server, which sends back whatever it was set to - nothing, in this case, resulting in 404 error. On the other hand all that React actually does is re-render components, with no further HTTP requests, since it's only running on the client side. But not all server routes will have a GET endpoint set, and even if they do you'd end up having, let's say, a JSON - or something else - sent directly to your browser screen when you reload the page instead of the React app, so what you really want is to handle those requests correctly.

First it's very important to note that server routes and React routes should not conflict (a good idea is to prepend /api to your server routes). Rename your server routes and don't forget to also rename all API calls from React accordingly. Then, add the following code to your server.js file after defining your routes:

isProduction &&
  app.get("*", function (request, response) {
    response.sendFile(path.resolve(__dirname, "../client/build", "index.html"));
  });

This will take care of the GET requests executed by your browser on page refresh, making sure that Node always serves index.html (aka the React app) to supply those requests, so it can handle routing. Since your server routes are now renamed and will not conflict with the React ones, when you reload the page or try to navigate directly from the URL address bar you'll always get back the React app, which, in turn, will handle all API calls.


问:
Randomly split sorted array into smaller sorted arrays
I have a big sorted array of unique numbers. I do want to split it into n smaller disjoint sorted arrays with unique values. For example, I have an array [1, 2, 3, 4, 5, 6, 7, 8, 9] and the algorithm I am looking for gives one of the following results (n=3):

[1, 4, 7], [5, 6, 9], [2, 3, 8]

[3, 8, 9], [1, 5, 7], [2, 4, 6]

[3, 4, 7], [1, 5, 8], [2, 6, 9], etc

Why I need it: I have a very big array (about 1 billion values) and I need to distribute values randomly between nodes in a simulated network, which together compute some aggregated value. They work more efficiently if they have sorted values. Since I am testing this system I need to run the simulation many times with the different amount of nodes, network topology, etc. Obviously simply splitting the data into several consecutive chunks is not suitable here.

答:
You can shuffle the list, split into chunks and the sort the chunks.
For example (solution in Python):

import random

n = 3
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

random.shuffle(lst)

for i in range(0, len(lst), n):
    print(sorted(lst[i : i + n]))
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>[1, 2, 8]
[3, 6, 9]
[4, 5, 7]
</code>```

Body:
You can shuffle the list, split into chunks and the sort the chunks.
For example (solution in Python):

import random

n = 3
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

random.shuffle(lst)

for i in range(0, len(lst), n):
    print(sorted(lst[i : i + n]))

Prints:

[1, 2, 8]
[3, 6, 9]
[4, 5, 7]


问:
Year-on-year change column in the data frame of monthly data
I am looking for the solution to my task. It is to add a new column to the data frame, which contains monthly data, that would have year-on-year change for each record that has a corresponding record of same month a year ago.

So, my code as of now is:

```<code>library(blsAPI)
cpi       <- blsAPI("CUUR0000SA0",2,TRUE)
cpi$value <- as.numeric(cpi$value)
cpi$date  <- as.Date(
     paste0("1 ",cpi$periodName," ",cpi$year),
     format = "%d %B %Y")
cpi <- cpi[order(cpi$date),]
</code>```

I would like to add new column with YoY change value for cpi$value column.

Body:
I am looking for the solution to my task. It is to add a new column to the data frame, which contains monthly data, that would have year-on-year change for each record that has a corresponding record of same month a year ago.

So, my code as of now is:

library(blsAPI)
cpi       <- blsAPI("CUUR0000SA0",2,TRUE)
cpi$value <- as.numeric(cpi$value)
cpi$date  <- as.Date(
     paste0("1 ",cpi$periodName," ",cpi$year),
     format = "%d %B %Y")
cpi <- cpi[order(cpi$date),]

I would like to add new column with YoY change value for cpi$value column.

Body:
Something like:

df <- data.frame(Date = c("2021-01-16", "2017-05-09"))
df |> dplyr::mutate(new = as.Date(Date) + 365)
#>         Date        new
#> 1 2021-01-16 2022-01-16
#> 2 2017-05-09 2018-05-09

library(lubridate)

df |>
  dplyr::mutate(new = as_date(Date) %m+% years(1))
#>         Date        new
#> 1 2021-01-16 2022-01-16
#> 2 2017-05-09 2018-05-09

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
How to implement Javascript async/await/promise in both of AsyncStorage and Json.parse?
Everyone, Here is my dirty code.

```<code>const parseJson = async value => {
  try{
    const parsedData = await JSON.parse(value);
    console.log('2', parsedData);
    return parsedData;
  }catch(e){}
}

const getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){}
}

useEffect(() => {
  const authStateData = getAuthStateData();
  console.log('3', authStateData);
}, [])
</code>```

Expected console state order is

```<code>1, 2, 3
</code>```

Real console state order is

```<code>3, 1, 2
</code>```

The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms.
so I need to wait all of them. This is basic of javascript concept: async, sync, promise.
Please help me, seniors!

答:
You are not awaiting the call to getAuthStateData in your useEffect callback, so it runs asynchronously, and the rest of the callback keeps running synchronously until the runtime has time to run the other tasks you've given it.

I think you meant to write this instead:

useEffect(async () => {
  const authStateData = await getAuthStateData();
  console.log('3', authStateData);
}, []);
```

Body:
Everyone, Here is my dirty code.

const parseJson = async value => {
  try{
    const parsedData = await JSON.parse(value);
    console.log('2', parsedData);
    return parsedData;
  }catch(e){}
}

const getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){}
}

useEffect(() => {
  const authStateData = getAuthStateData();
  console.log('3', authStateData);
}, [])

Expected console state order is

1, 2, 3

Real console state order is

3, 1, 2

The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms.
so I need to wait all of them. This is basic of javascript concept: async, sync, promise.
Please help me, seniors!


问:
Python console application - output above input line
I am trying to write a console application in Python3.

The problem is I would like all output messages EG: print("Status message") to be above the input line at the bottom.

```<code>Status message 1
Status message 2
Status message 3
Console:> I want to type here while the output messages displayed
</code>```

at the moment it looks more like this

```<code>Console:>  want to type here while the outStatus message 1
put messages displayed
</code>```

Is there anyway to do this without using curses?

答:
This can be done using ANSI escape sequences that provide in-band control of the console. This is how the curses library works on the backend.

This sequence should work for what you want, split apart for clarity:

```<code>print("\u001B[s", end="")     # Save current cursor position
print("\u001B[A", end="")     # Move cursor up one line
print("\u001B[999D", end="")  # Move cursor to beginning of line
print("\u001B[S", end="")     # Scroll up/pan window down 1 line
print("\u001B[L", end="")     # Insert new line
print(status_msg, end="")     # Print output status msg
print("\u001B[u", end="")     # Jump back to saved cursor position
</code>```

Note this is not specific to python and works on most consoles.

References:

http://xn--rpa.cc/irl/term.html - Great for TUI programming without curses, includes info on using a separate buffer for vim like screen switching

https://invisible-island.net/xterm/ctlseqs/ctlseqs.html - Full ANSI escape standard, the Wikipedia one excludes critical sequences

Body:
I am trying to write a console application in Python3.

The problem is I would like all output messages EG: print("Status message") to be above the input line at the bottom.

Status message 1
Status message 2
Status message 3
Console:> I want to type here while the output messages displayed

at the moment it looks more like this

Console:>  want to type here while the outStatus message 1
put messages displayed

Is there anyway to do this without using curses?

Body:
This can be done using ANSI escape sequences that provide in-band control of the console. This is how the curses library works on the backend.

This sequence should work for what you want, split apart for clarity:

print("\u001B[s", end="")     # Save current cursor position
print("\u001B[A", end="")     # Move cursor up one line
print("\u001B[999D", end="")  # Move cursor to beginning of line
print("\u001B[S", end="")     # Scroll up/pan window down 1 line
print("\u001B[L", end="")     # Insert new line
print(status_msg, end="")     # Print output status msg
print("\u001B[u", end="")     # Jump back to saved cursor position

Note this is not specific to python and works on most consoles.

References:

http://xn--rpa.cc/irl/term.html - Great for TUI programming without curses, includes info on using a separate buffer for vim like screen switching

https://invisible-island.net/xterm/ctlseqs/ctlseqs.html - Full ANSI escape standard, the Wikipedia one excludes critical sequences


问:
How can I include a JS file with query string in <h:outputScript>?
In JSF page I use this code to include a JS file:

```<code><h:outputScript library="js" name="reworkBase.js" />
</code>```

It works well, but I want to implement cache busting by adding a version parameter:

```<code><h:outputScript library="js" name="reworkBase.js?version=1" />
</code>```

But the JS file will not be found. I know it also works well if I use the

答: That's a bug in Mojarra. Their ScriptRenderer was as per issue 1212 fixed to support query strings. However, their fix was wrong for the case a library is specified. They used + instead of & as query string parameter separator, which only results in 404's:

Body:
In JSF page I use this code to include a JS file:

<h:outputScript library="js" name="reworkBase.js" />

It works well, but I want to implement cache busting by adding a version parameter:

<h:outputScript library="js" name="reworkBase.js?version=1" />

But the JS file will not be found. I know it also works well if I use the

Body:
That's a bug in Mojarra. Their ScriptRenderer was as per issue 1212 fixed to support query strings. However, their fix was wrong for the case a library is specified. They used + instead of &amp; as query string parameter separator, which only results in 404's:

<script src="/context/javax.faces.resource/reworkBase.js.xhtml?ln=js+version=1">

It should have been:

<script src="/context/javax.faces.resource/reworkBase.js.xhtml?ln=js&amp;version=1">

I've reported this bug as issue 2168.

In the meanwhile your best bet is to just omit the library altogether, given the library name of js (which obviously stands for "JavaScript") you seem not to be interested in using configureable look'n'feel/scripting libraries at all.

<h:outputScript name="js/reworkBase.js?version=1" />

This will result in the right URL.

<script src="/context/javax.faces.resource/js/reworkBase.js.xhtml?version=1">