问:
How to append an hyperlink at the end of an existing text in a textbox
I am trying to construct an anchor link based upon the text and url entered by the user and append it at the end of an existing text in a textbox. The following is my code. Nothing is added to the existing text in the txtDescription textbox. However, if I add the same link to a div, then it correctly appends the link to the div.</p>
```<code>    <!DOCTYPE html>
    <html>

   <head>
      <title>Test Page</title>
   </head>

   <body>
      <script type = "text/JavaScript">
        function addLink(){
         var link = $('<a>',
                {
                    text: $('#txtDisplayText').val(),
                    title: '',
                    href: $('#txtURL').val(),
                    target: "_blank"
                }).prop('outerHTML');
            $('#txtDescription').append(link);
    }
      </script>
         <input type="text" class="k-textbox" id="txtDescription" />
     <div class="row" style="padding-top: 10px;">
            <div class="col-sm-2">
                <label>Display Text</label>
                <br />
                <input type='text' id="txtDisplayText"  style="width: 100%" />
            </div>
            <div class="col-sm-2  columnSizeDouble">
                <label>URL</label>
                <br />
                <input type='text' id="txtURL"  style="width: 100%" />
            </div>
       <button id="btnAddLink" type="button" onclick="javascript:addLink();" class="buttonStyle"
       >Add Link</button>
        </div>
    </body>

   </html>
</code>```

答: I have replaced var link into var $link. Also replaced $('#txtDescription').append(link); into $('#txtDescription').val($link);</p>

Body:
I am trying to construct an anchor link based upon the text and url entered by the user and append it at the end of an existing text in a textbox. The following is my code. Nothing is added to the existing text in the txtDescription textbox. However, if I add the same link to a div, then it correctly appends the link to the div.

    <!DOCTYPE html>

      <title>Test Page</title>

         <input type="text" class="k-textbox" id="txtDescription" />

                Display Text

                <input type='text' id="txtDisplayText"  style="width: 100%" />

                URL

                <input type='text' id="txtURL"  style="width: 100%" />

       <button id="btnAddLink" type="button" onclick="javascript:addLink();" class="buttonStyle"
       >Add Link</button>


来源: stackexchange

问:
How to zip multiple RDDs in pyspark?
In spark there is zipPartitions to merge multiple RDDs into one. However, there is no such method available with pyspark RDD. If I use zip multiple times then I create one new dataframe per rdd that I combined, which is not what I want.

How can one zip multiple RDDs into one in pyspark?

答:
Good question. The introduction of zipPartitions in PySpark was proposed in 2016, but as you can read among comments, they never managed to find a good compromise between performances and solution complexity. The issue is now closed but I do not think it will be reopened in the near future. This is the solution proposed by Joseph E. Gonzalez.

The quickest way to use that API is to write it yourself (performances will not be that good of course). A very naive zipPartitions implementation is:

```<code>def zipPartitions(rdd1, rdd2, func):
    rdd1_numPartitions = rdd1.getNumPartitions()
    rdd2_numPartitions = rdd2.getNumPartitions()
    assert rdd1_numPartitions == rdd2_numPartitions, "rdd1 and rdd2 must have the same number of partitions"

    paired_rdd1 = rdd1.mapPartitionsWithIndex(lambda index, it: ((index, list(it)),))
    paired_rdd2 = rdd2.mapPartitionsWithIndex(lambda index, it: ((index, list(it)),))

    zipped_rdds = paired_rdd1.join(paired_rdd2, numPartitions=rdd1_numPartitions)\
        .flatMap(lambda x: func(x[1][0], x[1][1]))

    return zipped_rdds
</code>```

You can test it with:

```<code>rdd1 = sc.parallelize(range(30), 3)
rdd2 = sc.parallelize(range(50), 3)

zipPartitions(rdd1, rdd2, lambda it1, it2: itertools.zip_longest(it1, it2))\
    .glom().collect()
</code>```

Arguments are easy to understand, they are, in order, the first rdd, the second rdd and a function accepting 2 partition iterators, one for each rdd.
With the assert rdd1_numPartitions == rdd2_numPartitions I make sure both rdd have the same number of partitions, that is a precondition for the Scala version too.
Then I use mapPartitionsWithIndex on both rdds to transform, for example, an rdd with two partitions, from:

```<code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

To

```<code>[(0, [0, 1, 2, 3, 4]), (1, [5, 6, 7, 8, 9])]
</code>```

Note: the conversion from it to list(it) is unfortunately necessary because in most of the python implementations you cannot pickle generators, and the it parameter is a generator. There is an exception that allows you to convert it into a list, a case that pyspark handles with a very clever optimization, I am talking about an rdd created from a range(). In fact, considering the previous example,

```<code>range(10)
</code>```

becomes

```<code>[(0, range(0, 5)), (1, range(5, 10))]
</code>```

Next I can join the two new rdds on the partition index. numPartitions can be easily predicted because we have previously asserted that both rdd must have the same number of partitions, so they are in a 1-to-1 relationship. Finally, I can apply the passed function and flatten the list of partition results.

ContentLicense: CC BY-SA 4.0

Title: How to zip multiple RDDs in pyspark?

Body:
Good question. The introduction of zipPartitions in PySpark was proposed in 2016, but as you can read among comments, they never managed to find a good compromise between performances and solution complexity. The issue is now closed but I do not think it will be reopened in the near future. This is the solution proposed by Joseph E. Gonzalez.

The quickest way to use that API is to write it yourself (performances will not be that good of course). A very naive zipPartitions implementation is:

def zipPartitions(rdd1, rdd2, func):
    rdd1_numPartitions = rdd1.getNumPartitions()
    rdd2_numPartitions = rdd2.getNumPartitions()
    assert rdd1_numPartitions == rdd2_numPartitions, "rdd1 and rdd2 must have the same number of partitions"

    paired_rdd1 = rdd1.mapPartitionsWithIndex(lambda index, it: ((index, list(it)),))
    paired_rdd2 = rdd2.mapPartitionsWithIndex(lambda index, it: ((index, list(it)),))

    zipped_rdds = paired_rdd1.join(paired_rdd2, numPartitions=rdd1_numPartitions)\
        .flatMap(lambda x: func(x[1][0], x[1][1]))

    return zipped_rdds

You can test it with:

rdd1 = sc.parallelize(range(30), 3)
rdd2 = sc.parallelize(range(50), 3)

zipPartitions(rdd1, rdd2, lambda it1, it2: itertools.zip_longest(it1, it2))\
    .glom().collect()

Arguments are easy to understand, they are, in order, the first rdd, the second rdd and a function accepting 2 partition iterators, one for each rdd.
With the assert rdd1_numPartitions == rdd2_numPartitions I make sure both rdd have the same number of partitions, that is a precondition for the Scala version too.
Then I use mapPartitionsWithIndex on both rdds to transform, for example, an rdd with two partitions, from:

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

To

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

Note: the conversion from it to list(it) is unfortunately necessary because in most of the python implementations you cannot pickle generators, and the it parameter is a generator. There is an exception that allows you to convert it into a list, a case that pyspark handles with a very clever optimization, I am talking about an rdd created from a range(). In fact, considering the previous example,

range(10)

becomes

[(0, range(0, 5)), (1, range(5, 10))]

Next I can join the two new rdds on the partition index. numPartitions can be easily predicted because we have previously asserted that both rdd must have the same number of partitions, so they are in a 1-to-1 relationship. Finally, I can apply the passed function and flatten the list of partition results.


问:
How to refactor attributedText in Swift using different loops?
```<code>func attributedText() -> NSAttributedString {
    let string = termsTextView.text as NSString
    let attributedString = NSMutableAttributedString(
        string: string as String,
        attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)]
    )
    let boldFontAttribute = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15.0)]
    let semiBoldFontAttribute = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12.0)]
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "You"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "Services."))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "1. OVERVIEW."))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "II. TERMS AND CONDITIONS"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "A. Adults & Children."))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "18 Years Old and Older"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "Under 18 Years Old"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "B. Availability"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "C. Authorized Use"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "D. Linking (To & From) the Website; Advertisers"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "E. Privacy Policy"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "F. Prohibition against Harmful Transmissions & Appropriate Use of Website"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "User Content"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "G. Disclaimer of Warranties; Limitation Of Liability"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "I. Indemnification"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "J. Severability"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "K. Entire Agreement & Priority"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "L. Choice Of Law"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "M. Venue; Personal Jurisdiction; Service of Process"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "N. Headings For Convenience Only"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "O. Waiver"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "Q. Copyright Complaints"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "R. Contact"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "S. Local Laws"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "T. Prohibited Conduct"))
    return attributedString
}
</code>```

This is my code to set attributedText on UITextView
I am trying to refactor using different loops to remove repeated code as much as possible. like using enum or switch Case Any idea how can i achieve this? Thanks in

答:
Whatever approach you go for is going to be reasonably verbose as somehow you need to get all the text in there.  This approach might be slightly nicer (assumes you are only looking for one occurence of each, as this is what the above achieves):

```<code>let boldText = ["You", "Services.", "1. Overview", ...]

boldText.forEach{
   attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: $0}
}
</code>```

and the same for the other attributes.

IMO it's slightly more elegant, and it would mean you could move the arrays out into their own file and treat them as constants.  eg.

```<code>enum LookupTexts {
   static let boldText = ["You", "Services.", "1. Overview", ...]
   static let semiBoldText = [...]
}
</code>```

which would make the call site

```<code>LookupTexts.boldText.forEach{
   attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: $0}
</code>```

There is a problem with this and the original - what happens if the text doesn't exist?  You'd be better checking for the range of the text in an if let and then only apply the attribute it if you have a resulting valid range.

Body:
func attributedText() -> NSAttributedString {
    let string = termsTextView.text as NSString
    let attributedString = NSMutableAttributedString(
        string: string as String,
        attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)]
    )
    let boldFontAttribute = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15.0)]
    let semiBoldFontAttribute = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12.0)]
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "You"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "Services."))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "1. OVERVIEW."))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "II. TERMS AND CONDITIONS"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "A. Adults & Children."))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "18 Years Old and Older"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "Under 18 Years Old"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "B. Availability"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "C. Authorized Use"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "D. Linking (To & From) the Website; Advertisers"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "E. Privacy Policy"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "F. Prohibition against Harmful Transmissions & Appropriate Use of Website"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "User Content"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "G. Disclaimer of Warranties; Limitation Of Liability"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "I. Indemnification"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "J. Severability"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "K. Entire Agreement & Priority"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "L. Choice Of Law"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "M. Venue; Personal Jurisdiction; Service of Process"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "N. Headings For Convenience Only"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "O. Waiver"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "Q. Copyright Complaints"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "R. Contact"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "S. Local Laws"))
    attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: "T. Prohibited Conduct"))
    return attributedString
}

This is my code to set attributedText on UITextView
I am trying to refactor using different loops to remove repeated code as much as possible. like using enum or switch Case Any idea how can i achieve this? Thanks in

Body:
Whatever approach you go for is going to be reasonably verbose as somehow you need to get all the text in there.  This approach might be slightly nicer (assumes you are only looking for one occurence of each, as this is what the above achieves):

let boldText = ["You", "Services.", "1. Overview", ...]

boldText.forEach{
   attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: $0}
}

and the same for the other attributes.

IMO it's slightly more elegant, and it would mean you could move the arrays out into their own file and treat them as constants.  eg.

enum LookupTexts {
   static let boldText = ["You", "Services.", "1. Overview", ...]
   static let semiBoldText = [...]
}

which would make the call site

LookupTexts.boldText.forEach{
   attributedString.addAttributes(semiBoldFontAttribute, range: string.range(of: $0}

There is a problem with this and the original - what happens if the text doesn't exist?  You'd be better checking for the range of the text in an if let and then only apply the attribute it if you have a resulting valid range.


问:
How can i save data to text file from django form inputs?
I wanna save form input datas to text file and storage in local. But i am also new at django. Here is my sample codes... How can i save to form datas to text file? Thanks for help.

My models.py file

```<code>from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
#from datetime import datetime, date

class Post(models.Model):

    #post_date = models.DateField(auto_now_add = True)
    soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")
    soru6 = models.CharField(verbose_name='Birinci Evlilik', max_length=10000, default="")
</code>```

My forms.py file

```<code>from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'
        #field = ('title', 'author') yapılabilir

        widgets = {
            # 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}),
            # 'author': forms.Select(attrs={'class': 'form-control'}),
            # 'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}),
            'soru1': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}),
            'soru2': forms.TextInput(attrs={'class': 'form-control'}),
            'soru3': forms.TextInput(attrs={'class': 'form-control'}),
            'soru4': forms.TextInput(attrs={'class': 'form-control'}),
            'soru5': forms.TextInput(attrs={'class': 'form-control'}),
            'soru6': forms.TextInput(attrs={'class': 'form-control'}),
</code>```

my views.py file

```<code>from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import HttpResponse

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    ordering = ['-id']
    #ordering sıralamayı belli ediyor, negatif id yaptık en son eklenen en başa geliyor.

class ArticleDetailView(DetailView):
    model = Post
    template_name = 'article_details.html'
</code>```

答:
You can use basic Python methods open() and write(). You can access kwargs with self.get_form() in your View with form_class or similar option.

```<code>def post(self, request, *args, **kwargs):

    form = self.get_form()

    with open('text_file.txt', 'w') as file:
        file.write(f'Field_1: {form.data["field_1"]}\n')
        file.write(f'Field_2: {form.data["field_2"]}\n')
        ...
</code>```

example 'text_file.txt':

```<code>Field_1: SomeValue
Field_2: another value
Field_3: 3
...
</code>```

Body:
I wanna save form input datas to text file and storage in local. But i am also new at django. Here is my sample codes... How can i save to form datas to text file? Thanks for help.

My models.py file

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
#from datetime import datetime, date

class Post(models.Model):

    #post_date = models.DateField(auto_now_add = True)
    soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")
    soru6 = models.CharField(verbose_name='Birinci Evlilik', max_length=10000, default="")

My forms.py file

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'
        #field = ('title', 'author') yapılabilir

        widgets = {
            # 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}),
            # 'author': forms.Select(attrs={'class': 'form-control'}),
            # 'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}),
            'soru1': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}),
            'soru2': forms.TextInput(attrs={'class': 'form-control'}),
            'soru3': forms.TextInput(attrs={'class': 'form-control'}),
            'soru4': forms.TextInput(attrs={'class': 'form-control'}),
            'soru5': forms.TextInput(attrs={'class': 'form-control'}),
            'soru6': forms.TextInput(attrs={'class': 'form-control'}),

my views.py file

from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import HttpResponse

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    ordering = ['-id']
    #ordering sıralamayı belli ediyor, negatif id yaptık en son eklenen en başa geliyor.

class ArticleDetailView(DetailView):
    model = Post
    template_name = 'article_details.html'

Body:
You can use basic Python methods open() and write(). You can access kwargs with self.get_form() in your View with form_class or similar option.

def post(self, request, *args, **kwargs):

    form = self.get_form()

    with open('text_file.txt', 'w') as file:
        file.write(f'Field_1: {form.data["field_1"]}\n')
        file.write(f'Field_2: {form.data["field_2"]}\n')
        ...

example 'text_file.txt':

Field_1: SomeValue
Field_2: another value
Field_3: 3
...


问:
Support for ColorSetting trait on non-Light device types
Our hood supports a backlight which supports full RGB color change. The backlight on/off switch was implemented with a trigger, and we implemented the ColorSetting trait to change the color.

When trying to use Google Assistant to change the color however, we get the reply 'It looks like the device hasn't been set up yet'.
We tried changing the device type to 'Light', and the commands to change colors work flawlessly. Is the ColorSetting trait restricted to Light type only, and is there a workaround for this?

Thanks for your help

Edit: SYNC response for hood:

```<code>{
  "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
  "payload": {
      "agentUserId": "userID",
      "devices": [
          {
              "id": "HAID",
              "type": "action.devices.types.HOOD",
              "traits": [
                  "action.devices.traits.OnOff",
                  "action.devices.traits.StartStop",
                  "action.devices.traits.Modes",
                  "action.devices.traits.FanSpeed",
                  "action.devices.traits.Toggles",
                  "action.devices.traits.ColorSetting"
              ],
              "deviceInfo": {
                  "manufacturer": "MANUFACTURER",
                  "model": "MODEL",
                  "hwVersion": "",
                  "swVersion": ""
              },
              "name": {
                  "name": "Dunstabzugshaube",
                  "nicknames": [
                      "Dunstabzugshaube"
                  ],
                  "defaultNames": [
                      "Dunstabzugshaube"
                  ]
              },
              "willReportState": true,
              "attributes": {
                  "pausable": false,
                  "availableModes": [
                      {
                          "name": "program",
                          "name_values": [
                              {
                                  "name_synonym": [
                                      "program"
                                  ],
                                  "lang": "en"
                              }
                          ],
                          "settings": [
                              {
                                  "setting_name": "Auto",
                                  "setting_values": [
                                      {
                                          "lang": "en",
                                          "setting_synonym": [
                                              "auto",
                                              "automatic"
                                          ]
                                      }
                                  ]
                              },
                              {
                                  "setting_name": "circulation",
                                  "setting_values": [
                                      {
                                          "lang": "en",
                                          "setting_synonym": [
                                              "circulation",
                                              "ventilation",
                                              "airflow",
                                              "air flow"
                                          ]
                                      }
                                  ]
                              }
                          ],
                          "ordered": false
                      }
                  ],
                  "availableFanSpeeds": {
                      "speeds": [
                          {
                              "speed_name": "S1",
                              "speed_values": [
                                  {
                                      "lang": "en",
                                      "speed_synonym": [
                                          "fan stage 1",
                                          "Fan Stage 1",
                                          "lowest",
                                          "one"
                                      ]
                                  },
                                  {
                                      "lang": "de",
                                      "speed_synonym": [
                                          "lüfter stufe 1",
                                          "Lüfter Stufe 1",
                                          "minimum",
                                          "eins",
                                          "Stufe 1"
                                      ]
                                  }
                              ]
                          },
                          {
                              "speed_name": "S2",
                              "speed_values": [
                                  {
                                      "lang": "en",
                                      "speed_synonym": [
                                          "fan stage 2",
                                          "Fan Stage 2",
                                          "low",
                                          "two"
                                      ]
                                  },
                                  {
                                      "lang": "de",
                                      "speed_synonym": [
                                          "lüfter stufe 2",
                                          "Lüfter Stufe 2",
                                          "niedrig",
                                          "zwei",
                                          "Stufe 2"
                                      ]
                                  }
                              ]
                          },
                          {
                              "speed_name": "S3",
                              "speed_values": [
                                  {
                                      "lang": "en",
                                      "speed_synonym": [
                                          "fan stage 3",
                                          "Fan Stage 3",
                                          "medium",
                                          "three"
                                      ]
                                  },
                                  {
                                      "lang": "de",
                                      "speed_synonym": [
                                          "lüfter stufe 3",
                                          "Lüfter Stufe 3",
                                          "mittel",
                                          "drei",
                                          "Stufe 3"
                                      ]
                                  }
                              ]
                          }
                      ],
                      "ordered": true
                  },
                  "reversible": false,
                  "colorModel": "rgb",
                  "commandOnlyColorSetting": true,
                  "availableToggles": [
                      {
                          "name": "Light",
                          "name_values": [
                              {
                                  "name_synonym": [
                                      "light"
                                  ],
                                  "lang": "en"
                              }
                          ]
                      },
                      {
                          "name": "backlight",
                          "name_values": [
                              {
                                  "name_synonym": [
                                      "backlight",
                                      "mood light"
                                  ],
                                  "lang": "en"
                              },
                              {
                                  "name_synonym": [
                                      "Hintergrundbeleuchtung",
                                      "Stimmungslicht"
                                  ],
                                  "lang": "de"
                              }
                          ]
                      }
                  ]
              }
          }
      ]
  }
}
</code>```

Best,

Frank

答:
Your sync response provided above looks correct. Your concern about the command working flawlessly when you set the device type as LIGHT  is because LIGHT does have a recommended trait as ColorSetting. To clarify your concern further, some device types do have better support for certain types of relevant grammar/language, which might explain why ColorSetting works better when the device type is set to light.

Google constantly works on the NLU (Natural Language Understanding) algorithms, so this grammar issue would be resolved by now and the ColorSetting trait should now be widely accessible to more devices.

More information about the HOOD and LIGHT device types and their associated traits along with sync, execute and query responses can be found here:

https://developers.google.com/assistant/smarthome/guides/hood

https://developers.google.com/assistant/smarthome/guides/light

Body:
Our hood supports a backlight which supports full RGB color change. The backlight on/off switch was implemented with a trigger, and we implemented the ColorSetting trait to change the color.

When trying to use Google Assistant to change the color however, we get the reply 'It looks like the device hasn't been set up yet'.
We tried changing the device type to 'Light', and the commands to change colors work flawlessly. Is the ColorSetting trait restricted to Light type only, and is there a workaround for this?

Thanks for your help

Edit: SYNC response for hood:

{
  "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
  "payload": {
      "agentUserId": "userID",
      "devices": [
          {
              "id": "HAID",
              "type": "action.devices.types.HOOD",
              "traits": [
                  "action.devices.traits.OnOff",
                  "action.devices.traits.StartStop",
                  "action.devices.traits.Modes",
                  "action.devices.traits.FanSpeed",
                  "action.devices.traits.Toggles",
                  "action.devices.traits.ColorSetting"
              ],
              "deviceInfo": {
                  "manufacturer": "MANUFACTURER",
                  "model": "MODEL",
                  "hwVersion": "",
                  "swVersion": ""
              },
              "name": {
                  "name": "Dunstabzugshaube",
                  "nicknames": [
                      "Dunstabzugshaube"
                  ],
                  "defaultNames": [
                      "Dunstabzugshaube"
                  ]
              },
              "willReportState": true,
              "attributes": {
                  "pausable": false,
                  "availableModes": [
                      {
                          "name": "program",
                          "name_values": [
                              {
                                  "name_synonym": [
                                      "program"
                                  ],
                                  "lang": "en"
                              }
                          ],
                          "settings": [
                              {
                                  "setting_name": "Auto",
                                  "setting_values": [
                                      {
                                          "lang": "en",
                                          "setting_synonym": [
                                              "auto",
                                              "automatic"
                                          ]
                                      }
                                  ]
                              },
                              {
                                  "setting_name": "circulation",
                                  "setting_values": [
                                      {
                                          "lang": "en",
                                          "setting_synonym": [
                                              "circulation",
                                              "ventilation",
                                              "airflow",
                                              "air flow"
                                          ]
                                      }
                                  ]
                              }
                          ],
                          "ordered": false
                      }
                  ],
                  "availableFanSpeeds": {
                      "speeds": [
                          {
                              "speed_name": "S1",
                              "speed_values": [
                                  {
                                      "lang": "en",
                                      "speed_synonym": [
                                          "fan stage 1",
                                          "Fan Stage 1",
                                          "lowest",
                                          "one"
                                      ]
                                  },
                                  {
                                      "lang": "de",
                                      "speed_synonym": [
                                          "lüfter stufe 1",
                                          "Lüfter Stufe 1",
                                          "minimum",
                                          "eins",
                                          "Stufe 1"
                                      ]
                                  }
                              ]
                          },
                          {
                              "speed_name": "S2",
                              "speed_values": [
                                  {
                                      "lang": "en",
                                      "speed_synonym": [
                                          "fan stage 2",
                                          "Fan Stage 2",
                                          "low",
                                          "two"
                                      ]
                                  },
                                  {
                                      "lang": "de",
                                      "speed_synonym": [
                                          "lüfter stufe 2",
                                          "Lüfter Stufe 2",
                                          "niedrig",
                                          "zwei",
                                          "Stufe 2"
                                      ]
                                  }
                              ]
                          },
                          {
                              "speed_name": "S3",
                              "speed_values": [
                                  {
                                      "lang": "en",
                                      "speed_synonym": [
                                          "fan stage 3",
                                          "Fan Stage 3",
                                          "medium",
                                          "three"
                                      ]
                                  },
                                  {
                                      "lang": "de",
                                      "speed_synonym": [
                                          "lüfter stufe 3",
                                          "Lüfter Stufe 3",
                                          "mittel",
                                          "drei",
                                          "Stufe 3"
                                      ]
                                  }
                              ]
                          }
                      ],
                      "ordered": true
                  },
                  "reversible": false,
                  "colorModel": "rgb",
                  "commandOnlyColorSetting": true,
                  "availableToggles": [
                      {
                          "name": "Light",
                          "name_values": [
                              {
                                  "name_synonym": [
                                      "light"
                                  ],
                                  "lang": "en"
                              }
                          ]
                      },
                      {
                          "name": "backlight",
                          "name_values": [
                              {
                                  "name_synonym": [
                                      "backlight",
                                      "mood light"
                                  ],
                                  "lang": "en"
                              },
                              {
                                  "name_synonym": [
                                      "Hintergrundbeleuchtung",
                                      "Stimmungslicht"
                                  ],
                                  "lang": "de"
                              }
                          ]
                      }
                  ]
              }
          }
      ]
  }
}

Best,

Frank


问:
Dart: How to check if List of Objects is a List of Strings/ints/bools
For simple data types, you can use e.g.

```<code>object is String
</code>```

to check whether an Object variable is of a more specific type.

But let's you have a List, but want to check if it is a List of Strings. Intuitively we might try

```<code>List list = ['string', 'other string'];
print(list is List<String>);
</code>```

which returns false.

Similarly using the List.cast() method doesn't help, it will always succeed and only throw an error later on when using the list.

We could iterate over the entire list and check the type of each individual entry, but I was hoping there might be a better way.

答:
There is no other way. What you have is a List<Object?>/List<dynamic> (because the type is inferred from the variable type, which is a raw List type which gets instantiated to its bound). The list currently only contains String objects, but nothing prevents you from adding a new Object() to it.

So, the object itself doesn't know that it only contains strings, you have to look at each element to check that.

Or, when you create a list, just declare the variable as List<String> list = ...; or var list = ...;, then the object will be a List<String>.
If you are not the one creating the list, it's back to list.every((e) => e is String).

Body:
For simple data types, you can use e.g.

object is String

to check whether an Object variable is of a more specific type.

But let's you have a List, but want to check if it is a List of Strings. Intuitively we might try

List list = ['string', 'other string'];
print(list is List<String>);

which returns false.

Similarly using the List.cast() method doesn't help, it will always succeed and only throw an error later on when using the list.

We could iterate over the entire list and check the type of each individual entry, but I was hoping there might be a better way.


问:
Use <select> in Twig / Timber
I have the following code in a .twig WordPress template:

```<code><select id="filter-assessment-year">
<option disabled selected hidden>ASSESSMENT YEAR</option>
<optgroup label="Assessment Year">
    <option value="2022">2022 Assessment</option>
    <option value="2021">2021 Assessment</option>
    <option value="2020">2020 Assessment</option>
    <option value="2019">2019 Assessment</option>
</optgroup>
</select>
</code>```

I then need to output different code depending on which year the user selects. I want to basically say if user selects 2022 then output this code, else if user selects 2021 then output this code.

How can I use the above option selection to control the code output in my twig template?

Thank you

答:
You would need to use javascript for this. Try a library like Alpine JS if you're not already using jQuery.

const selectForm = document.getElementById('assesment');

selectForm.addEventListener("change", function(){
  if(selectForm.value === '2022'){
     alert('2022 Code will run');
  }
  if(selectForm.value === '2021'){
    alert('2021 Code will run');
  }
  if(selectForm.value === '2020'){
    alert('2020 Code will run');
  }
   if(selectForm.value === '2019'){
    alert('2019 Code will run');
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <select id="assesment" class="target">
      <option value="0">ASSESSMENT YEAR</option>
      <option value="2022">2022 Assessment</option>
      <option value="2021">2021 Assessment</option>
      <option value="2020">2020 Assessment</option>
      <option value="2019">2019 Assessment</option>
  </select>
</form></code>```

Title: Use <select> in Twig / Timber

Body:
I have the following code in a .twig WordPress template:

<select id="filter-assessment-year">
<option disabled selected hidden>ASSESSMENT YEAR</option>
<optgroup label="Assessment Year">
    <option value="2022">2022 Assessment</option>
    <option value="2021">2021 Assessment</option>
    <option value="2020">2020 Assessment</option>
    <option value="2019">2019 Assessment</option>
</optgroup>
</select>

I then need to output different code depending on which year the user selects. I want to basically say if user selects 2022 then output this code, else if user selects 2021 then output this code.

How can I use the above option selection to control the code output in my twig template?

Thank you

Body:
You would need to use javascript for this. Try a library like Alpine JS if you're not already using jQuery.

const selectForm = document.getElementById('assesment');

selectForm.addEventListener("change", function(){
  if(selectForm.value === '2022'){
     alert('2022 Code will run');
  }
  if(selectForm.value === '2021'){
    alert('2021 Code will run');
  }
  if(selectForm.value === '2020'){
    alert('2020 Code will run');
  }
   if(selectForm.value === '2019'){
    alert('2019 Code will run');
  }

});

<form>
  <select id="assesment" class="target">
      <option value="0">ASSESSMENT YEAR</option>
      <option value="2022">2022 Assessment</option>
      <option value="2021">2021 Assessment</option>
      <option value="2020">2020 Assessment</option>
      <option value="2019">2019 Assessment</option>
  </select>
</form>


问:
ComponentActivity ClassNotFoundException when trying to setup Instrumented tests, with Android Compose and Hilt
I'm setting up my first instrumented unit-test and getting an obscure crash in logcat.

The emulator starts and immediately crashes when the app tries to open and the unit test doesn't even run because the application wasn't in the right state.

```<code>2022-02-09 19:30:37.116 25764-25764/com.anotherday.day17.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.anotherday.day17.test, PID: 25764
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.anotherday.day17.test/androidx.activity.ComponentActivity}: java.lang.ClassNotFoundException: Didn't find class "androidx.activity.ComponentActivity" on path: DexPathList[[zip file "/data/app/~~NodQZs7v97-vYTPte3T7UQ==/com.anotherday.day17.test-25XuwB3vTwyNbSX-nlETDQ==/base.apk"],
</code>```

It seems to be looking for androidx.activity.ComponentActivity which is defined in the following gradle dependency:

 implementation 'androidx.activity:activity-compose:1.3.1'

Not sure where else to look, here's my first test and my project in git:
https://github.com/davida5/ComposeNotepad/blob/main/app/src/androidTest/java/com/anotherday/day17/navigation/NavigatorTest.kt

答:
Add the following to your AndroidManifest.xml:

```<code><manifest>
  <application>
    ...
    <activity android:name="androidx.activity.ComponentActivity" />
    ...
  <application>
<manifest>
</code>```

If you have a specific Manifest file for the debug variant, add this to that file instead, as this change isn't needed for the release variant.

Body:
I'm setting up my first instrumented unit-test and getting an obscure crash in logcat.

The emulator starts and immediately crashes when the app tries to open and the unit test doesn't even run because the application wasn't in the right state.

2022-02-09 19:30:37.116 25764-25764/com.anotherday.day17.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.anotherday.day17.test, PID: 25764
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.anotherday.day17.test/androidx.activity.ComponentActivity}: java.lang.ClassNotFoundException: Didn't find class "androidx.activity.ComponentActivity" on path: DexPathList[[zip file "/data/app/~~NodQZs7v97-vYTPte3T7UQ==/com.anotherday.day17.test-25XuwB3vTwyNbSX-nlETDQ==/base.apk"],

It seems to be looking for androidx.activity.ComponentActivity which is defined in the following gradle dependency:

 implementation 'androidx.activity:activity-compose:1.3.1'

Not sure where else to look, here's my first test and my project in git:
https://github.com/davida5/ComposeNotepad/blob/main/app/src/androidTest/java/com/anotherday/day17/navigation/NavigatorTest.kt

Body:
Add the following to your AndroidManifest.xml:

<manifest>
  <application>
    ...
    <activity android:name="androidx.activity.ComponentActivity" />
    ...
  <application>
<manifest>

If you have a specific Manifest file for the debug variant, add this to that file instead, as this change isn't needed for the release variant.


问:
Unity : Can't drag GameObject with Text on Script reference
I'm trying to change the Text of an UI GameObject with a script but Unity doesn't let me drag the GameObject with the text on the script reference and when i do public GameObject it says GameObject is not a Text.</p>
```<code>using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;

public class GhostName : MonoBehaviour
{
    public Text NameText;

    void Start()
    {
        NameText.text = "The Name is : ";
    }
}
</code>```

答: If anyone still get this issue, I had to change from "TextMeshPro" to "Text" Object.</p>

Body:
I'm trying to change the Text of an UI GameObject with a script but Unity doesn't let me drag the GameObject with the text on the script reference and when i do public GameObject it says GameObject is not a Text.

using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;

public class GhostName : MonoBehaviour
{
    public Text NameText;

    void Start()
    {
        NameText.text = "The Name is : ";
    }
}


问:
Splitting a string on the first space
I'd like to split a vector of character strings (people's names) into two columns (vectors).  The problem is some people have a 'two word' last name.  I'd like to split the first and last names into two columns.  I can slit out and take the first names using the code below but the last name eludes me. (look at obs 29 in the sample set below to get an idea as the Ford has a "last name" of Pantera L that must be kept together)

What I have attempted to do so far;

```<code>x<-rownames(mtcars)
unlist(strsplit(x, " .*"))
</code>```

What I'd like it to look like:

```<code>            MANUF       MAKE
27          Porsche     914-2
28          Lotus       Europa
29          Ford        Pantera L
30          Ferrari     Dino
31          Maserati    Bora
32          Volvo       142E
</code>```

答:
You can also use tidyr::extract after converting your vector into a data frame first - I think this would also be the more modern version of older solutions with reshape2

library(tidyr)

## first convert into a data frame
x <- data.frame(x = rownames(mtcars))

## use extract, and for example Joshua's regex
res <- extract(x, col = x, into = c("MANUF", "MAKE"), regex = "^(\\w+)\\s?(.*)$")

head(res)
#>     MANUF       MAKE
#> 1   Mazda        RX4
#> 2   Mazda    RX4 Wag
#> 3  Datsun        710
#> 4  Hornet    4 Drive
#> 5  Hornet Sportabout
#> 6 Valiant
```

ContentLicense: CC BY-SA 3.0

Title: Splitting a string on the first space

Body:
I'd like to split a vector of character strings (people's names) into two columns (vectors).  The problem is some people have a 'two word' last name.  I'd like to split the first and last names into two columns.  I can slit out and take the first names using the code below but the last name eludes me. (look at obs 29 in the sample set below to get an idea as the Ford has a "last name" of Pantera L that must be kept together)

What I have attempted to do so far;

x<-rownames(mtcars)
unlist(strsplit(x, " .*"))

What I'd like it to look like:

            MANUF       MAKE
27          Porsche     914-2
28          Lotus       Europa
29          Ford        Pantera L
30          Ferrari     Dino
31          Maserati    Bora
32          Volvo       142E


问:
GAS-built telegram bot: catching replies to bot
I wrote an bot on GAS to read from / write to a google sheet from telegram. I use the webhook method. I can address the bot with /read <args> and /write <args>. However, the less tech-savvy are not able to understand the principle of arguments...
So I want to make a conversational bot, like botfather. eg, if /read or /write are sent, then the bot ask in pm for the arguments, one by one.
The "reply in PM" part is easy, but I don't see how I can catch replies for arguments?

As far as I understand, the function doPost is called each time a command is sent to the bot which poses issues of interactivity, and requiring a slash-something command to run the script instead of a plain text reply (and as the GAS data is volatile, the ugly work-around of storing a variable to know the bot should do the 2nd action is impossible too).

Is it feasible with webhook method?

Should I switch to polling / getUpdates method? I'm guessing it could work that way,  with a time-out to exit the script in case of no reply, but I'm also guessing the PM chat should be set to 'no privacy' mode. or maybe it is intrinsic to the bot?

Any help appreciated!

答: The doGet and doPost are the functions that get called when you follow a web app url.  You can use them as an api if you use something like UrlFetchApp to access them or even an Http Request if you can handle the oauth.</p>


问:
Absolute centering a flex item loses the button hovers, why?
I'm trying to create a header for a page that puts the title of the page in the middle and centered absolutely. I tried to do this with flex box and justify-content:space-between However as shown below I get the title skewed depending on the buttons width on the right (I've exaggerated that to show the effect)

While I was able to absolutely center the title (using absolute positioning on the h1) as in the example of "Want", a strange side-effect shows up on the buttons- they aren't clickable anymore! I'm flummoxed. What's going on here? How do I center the title and still keep the buttons working (with flex)?

body {
  max-width: 32em;
  margin: 0 auto;
}

nav {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 2em;
  justify-content: space-between;
  border-bottom: 1px solid gray;
  margin: 20px auto;
}

/* My attempt at keeping h1 absolutely centered on the page width */

h1.want {
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
  top: 20px;
  padding: 0;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <div>
      <button>Foo</button>
    </div>
    <div>
      <div>
        <h1 class="want">Want</h1>
      </div>
    </div>
    <div>
      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>
    </div>
  </nav>
  The buttons don't work here!
  <nav>
    <div>
      <button>Foo</button>
    </div>
    <div>
      <div>
        <h1>Got this</h1>
      </div>
    </div>
    <div>
      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>
    </div>
  </nav>
  Buttons work here.
</header></code>```

答:
As mentioned user:Phix, problem is your headline (with position: absolute; property) overlay button. In this case you should add z-index to sibling node.

.button-wrapper {
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <style>
    body {
      max-width: 32em;
      margin: 0 auto;
    }

    nav {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100%;
      height: 2em;
      justify-content: space-between;
      border-bottom: 1px solid gray;
      margin: 20px auto;
    }
    /* My attempt at keeping h1 absolutely centered on the page width */

    h1.want {
      left: 0;
      position: absolute;
      right: 0;
      text-align: center;
      top: 20px;
      padding: 0;
      margin: 0;
    }
  </style>
</head>

<body>
  <header>
    <nav>
      <div class="button-wrapper">
        <button>Foo</button>
      </div>
      <div>
        <div>
          <h1 class="want">Want</h1>
        </div>
      </div>
      <div>
        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>
      </div>
    </nav>
    The buttons don't work here!
    <nav>
      <div>
        <button>Foo</button>
      </div>
      <div>
        <div>
          <h1>Got this</h1>
        </div>
      </div>
      <div>
        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>
      </div>
    </nav>
    Buttons work here.
  </header>
</body>

</html></code>```

Body:
I'm trying to create a header for a page that puts the title of the page in the middle and centered absolutely. I tried to do this with flex box and justify-content:space-between However as shown below I get the title skewed depending on the buttons width on the right (I've exaggerated that to show the effect)

While I was able to absolutely center the title (using absolute positioning on the h1) as in the example of "Want", a strange side-effect shows up on the buttons- they aren't clickable anymore! I'm flummoxed. What's going on here? How do I center the title and still keep the buttons working (with flex)?

body {
  max-width: 32em;
  margin: 0 auto;
}

nav {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 2em;
  justify-content: space-between;
  border-bottom: 1px solid gray;
  margin: 20px auto;
}

/* My attempt at keeping h1 absolutely centered on the page width */

h1.want {
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
  top: 20px;
  padding: 0;
  margin: 0;
}

      <button>Foo</button>

Want

      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>

  The buttons don't work here!

      <button>Foo</button>

Got this

      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>

  Buttons work here.

Body:
As mentioned user:Phix, problem is your headline (with position: absolute; property) overlay button. In this case you should add z-index to sibling node.

.button-wrapper {
  z-index: 1;
}

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      max-width: 32em;
      margin: 0 auto;
    }

    nav {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100%;
      height: 2em;
      justify-content: space-between;
      border-bottom: 1px solid gray;
      margin: 20px auto;
    }
    /* My attempt at keeping h1 absolutely centered on the page width */

    h1.want {
      left: 0;
      position: absolute;
      right: 0;
      text-align: center;
      top: 20px;
      padding: 0;
      margin: 0;
    }
  </style>
</head>

<body>
  <header>
    <nav>
      <div class="button-wrapper">
        <button>Foo</button>
      </div>
      <div>
        <div>
          <h1 class="want">Want</h1>
        </div>
      </div>
      <div>
        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>
      </div>
    </nav>
    The buttons don't work here!
    <nav>
      <div>
        <button>Foo</button>
      </div>
      <div>
        <div>
          <h1>Got this</h1>
        </div>
      </div>
      <div>
        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>
      </div>
    </nav>
    Buttons work here.
  </header>
</body>

</html>


问:
Call a function in it self?
I saw an example online that looks like this:

```<code> def DecimalToBinary(num):

      if num >= 1:
         DecimalToBinary(num // 2)
      print(num % 2, end = '')

print(DecimalToBinary(12))
</code>```

I'll be happy if someone explain it to me.

答: The function will run normally as if you called it outside of it</p>

Title: Call a function in it self?

Body:
I saw an example online that looks like this:

 def DecimalToBinary(num):

      if num >= 1:
         DecimalToBinary(num // 2)
      print(num % 2, end = '')

print(DecimalToBinary(12))

I'll be happy if someone explain it to me.


问:
OpsWorks Role to Start Instance
I am not able to start an OpsWorks instance after I have created the Instance within an OpsWorks Layer, which is part of an OpsWorks Stack.  The error that I get after attempting to start the 24/7 instance is the following:

An error occurred while starting the instance java-app1
OpsWorks failed to obtain the necessary credentials to start the instance on your behalf. Please try again after waiting a minute. If this error persists, please check the permissions of the stack IAM role.

The error indicates that I don't have my permissions set correctly for the IAM Role of my Stack.  I have created an OpsWorks Stack that contains a reference to a Role ARN that has the AWSOpsWorksFullAccess and AWSOpsWorksRole policies set for the Role's permissions.  I would have thought one of those two policies would be enough.

I can create a OpsWorks Layer within that Stack, and create an OpsWorks instance as well.  The created instance uses the DefaultInstanceProfileArn of the Stack.  In my case, that ARN references a Role that contains the following policies:
AmazonEC2FullAccess
AWSOpsWorksFullAccess
AWSOpsWorksRole
AmazonS3FullAccess

I know that the policies that I have applied are very broad, but at this point I'm just trying to get an OpsWorks instance to start.  What policy needs to be applied in order for OpsWorks to have the correct permissions to start an instance within my Stack?

答:
This confused me the most. Passing this mountant brings a lot of sights.

Open stack-setting, you will find your current IAM ROLE

Follow the document below to attach an inline policy.

https://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-servicerole.html

If you create a custom service role, you must ensure that it grants all the permissions that AWS OpsWorks Stacks needs to manage your stack. The following JSON sample is the policy statement for the standard service role; a custom service role should include at least the following permissions in its policy statement.

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Action": [
                "ec2:*",
                "iam:PassRole",
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:DescribeAlarms",
                "ecs:*",
                "elasticloadbalancing:*",
                "rds:*"
            ],
            "Effect": "Allow",
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "ec2.amazonaws.com"
                }
            }
        }
    ]
}
```

Title: OpsWorks Role to Start Instance


问:
jQuery - Change text in an input field after it's created
How can I write a script that will change an input field's text value, but the field is not yet created?

The script is loaded before the input field is created.  It needs to know that when any input with a certain class is created, it will then have some text put in to its value.  Can this be done with live()?

To clarify, the order of events are:

1 - Application-wide JavaScript for the page is loaded.  This contains script something along the lines of:

```<code>$('.myDiv input').each(function() {
    $(this).val('some text');
});
</code>```

2 - A second page-specific script is now loaded, which dynamically creates an input on the page, with no value.  I CANNOT MODIFY THIS SCRIPT. This is important, I need a solution that does not modify this script (otherwise I wouldn't be posting here).

```<code>$('.myDiv').html('<input type="text" />');
</code>```

答:
live() does not support the load event, unfortunately. Can you put it in the ready event?

```<code>$().ready(function(){ $('.myClass').val('my text');});
</code>```

You could also consider wrapping the jQuery-plugin and change the text immediately after the plugin has been applied. Read more about extending jQuery plugins here: Best Way to Extend a jQuery Plugin

Body:
How can I write a script that will change an input field's text value, but the field is not yet created?

The script is loaded before the input field is created.  It needs to know that when any input with a certain class is created, it will then have some text put in to its value.  Can this be done with live()?

To clarify, the order of events are:

1 - Application-wide JavaScript for the page is loaded.  This contains script something along the lines of:

$('.myDiv input').each(function() {
    $(this).val('some text');
});

2 - A second page-specific script is now loaded, which dynamically creates an input on the page, with no value.  I CANNOT MODIFY THIS SCRIPT. This is important, I need a solution that does not modify this script (otherwise I wouldn't be posting here).

$('.myDiv').html('<input type="text" />');

Body:
live() does not support the load event, unfortunately. Can you put it in the ready event?

$().ready(function(){ $('.myClass').val('my text');});

You could also consider wrapping the jQuery-plugin and change the text immediately after the plugin has been applied. Read more about extending jQuery plugins here: Best Way to Extend a jQuery Plugin


问:
How to use Pinia outside a component in js file
I am migrating from vue 4.x to pinia, one of my file needs api key from  store.
But I can't make it work even though I follow the Pinia documentation .
here is how I use pinia

// Repository.ts

```<code>import axios from "axios";

import { createPinia } from 'pinia'
import { useAuthStore } from '../stores/auth-store'
const pinia=createPinia();
let authStore = useAuthStore(pinia);
const baseURL = 'http://127.0.0.1:5678/res-api';

export default axios.create({
  baseURL,
  headers:{"Authorization":"Bearer " + authStore.getToken,
"Accept":"application/json"},

});

</code>```

Expected result : to get the token from the store.

Console error

```<code>Uncaught ReferenceError: Cannot access 'useAuthStore' before initialization
    at Repository.ts:6:17

Note: this working inside a component
</code>```

答:
According to the documentation the pinia you created must go as a parameter to app.use. Not only that, but useAuthStore must be a store defined with defineStore and must not take a parameter. I'll leave a link that can help you, it doesn't create the store but you can browse the side menu to see several examples.

https://pinia.vuejs.org/core-concepts/outside-component-usage.html

Body:
I am migrating from vue 4.x to pinia, one of my file needs api key from  store.
But I can't make it work even though I follow the Pinia documentation .
here is how I use pinia

// Repository.ts

import axios from "axios";

import { createPinia } from 'pinia'
import { useAuthStore } from '../stores/auth-store'
const pinia=createPinia();
let authStore = useAuthStore(pinia);
const baseURL = 'http://127.0.0.1:5678/res-api';

export default axios.create({
  baseURL,
  headers:{"Authorization":"Bearer " + authStore.getToken,
"Accept":"application/json"},

});

Expected result : to get the token from the store.

Console error

Uncaught ReferenceError: Cannot access 'useAuthStore' before initialization
    at Repository.ts:6:17

Note: this working inside a component


问:
Cost must be multiple by 5
I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

```<code>public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }

    }
</code>```

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.

答: You can make cost variable as a prop and round there any given value by user till it is valid.</p>

Title: Cost must be multiple by 5

Body:
I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }

    }

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.


问:
KeyError: 0 in if clause?
I try to plot the following dataframe:

```<code>x | y | end_x | end_y | outcome
94.8 | 34.4 | 91.2  | 4.0 | Successful
10.5 | 20.4| 52.3 | 55.8 | Unsuccessful
13.2 | 29.8 | 58.9 | 1.0 | Successful
</code>```

I cannot figure out what I do wrong here:

```<code>for x in range(len(df['x'])):
    if df['outcome'][x] == 'Successful':
        plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'][x]),color='green')
</code>```

I try to plot the rows only if df['outcome'] is equal to 'Successful'.

But I get this KeyError:

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-116-cb16460cada0> in <module>
     10
     11 for x in range(len(df['x'])):
---> 12     if df['outcome'][x] == 'Successful':
     13         plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'][x]),color='green')

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    851
    852         elif key_is_scalar:
--> 853             return self._get_value(key)
    854
    855         if is_hashable(key):

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
    959
    960         # Similar to Index.get_value, but we do not fall back to positional
--> 961         loc = self.index.get_loc(label)
    962         return self.index._get_values_for_loc(self, loc, label)
    963

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083
   3084         if tolerance is not None:

KeyError: 0
</code>```

What do I have to check here?

答:
Try this code in your editor:-

```<code>data = [[94.8,34.4 , 91.2  , 4.0 , "Successful"], [10.5 , 20.4, 52.3 , 55.8
, "Unsuccessful"],[13.2 , 29.8 , 58.9 , 1.0 , "Successful"]]
import pandas as pd
df = pd.DataFrame(data, columns=["x" , "y" , "end_x" , 'end_y' ,
"outcome"])
import matplotlib.pyplot as plt
for x in range(len(df['x'])):
    if df['outcome'][x] == 'Successful':
        plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y']
[x]),color='green')
</code>```

Title: KeyError: 0 in if clause?

Body:
I try to plot the following dataframe:

x | y | end_x | end_y | outcome
94.8 | 34.4 | 91.2  | 4.0 | Successful
10.5 | 20.4| 52.3 | 55.8 | Unsuccessful
13.2 | 29.8 | 58.9 | 1.0 | Successful

I cannot figure out what I do wrong here:

for x in range(len(df['x'])):
    if df['outcome'][x] == 'Successful':
        plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'][x]),color='green')

I try to plot the rows only if df['outcome'] is equal to 'Successful'.

But I get this KeyError:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-116-cb16460cada0> in <module>
     10
     11 for x in range(len(df['x'])):
---> 12     if df['outcome'][x] == 'Successful':
     13         plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'][x]),color='green')

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    851
    852         elif key_is_scalar:
--> 853             return self._get_value(key)
    854
    855         if is_hashable(key):

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
    959
    960         # Similar to Index.get_value, but we do not fall back to positional
--> 961         loc = self.index.get_loc(label)
    962         return self.index._get_values_for_loc(self, loc, label)
    963

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083
   3084         if tolerance is not None:

KeyError: 0

What do I have to check here?

Body:
Try this code in your editor:-

data = [[94.8,34.4 , 91.2  , 4.0 , "Successful"], [10.5 , 20.4, 52.3 , 55.8
, "Unsuccessful"],[13.2 , 29.8 , 58.9 , 1.0 , "Successful"]]
import pandas as pd
df = pd.DataFrame(data, columns=["x" , "y" , "end_x" , 'end_y' ,
"outcome"])
import matplotlib.pyplot as plt
for x in range(len(df['x'])):
    if df['outcome'][x] == 'Successful':
        plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y']
[x]),color='green')


问:
Python Snake Game snake does not follow
I am creating Snake game in pygame using Sprite logic

how do i chain the movement of the snake? another question on this has been answered here but i cant apply it to my code: see here

the minimal example above works. try it first and you will see my issue :)
the snake grows on collision with the red food... but its movement does not chain

thank you

```<code>import pygame
from random import randint
from sys import exit

pygame.init()
game_active = True #start the game on the Welcome Screen
clock = pygame.time.Clock() #an object to track time, for fps

def display_surface():
    """function to create the main window"""
    disp_surface = pygame.display.set_mode(size = (610, 700)) #creates a main display window
    pygame.display.set_caption("Snake")
    return disp_surface
disp_surface = display_surface() #MUST return this immediately so it can be pushed to pygame.display.update()

class snake(pygame.sprite.Sprite):
    def __init__(self, x_pos = 300, y_pos = 300):
        #Access the super class of Sprite
        super().__init__()
        image1 = pygame.image.load("square1.png").convert_alpha()
        self.x_pos = x_pos
        self.y_pos = y_pos

        self.image = image1
        self.rect = self.image.get_rect(x = x_pos, y = y_pos)

    def update(self, left, right, up, down):
        """defines the movement of the snake using arrow keys"""
        if left:
            self.rect.left -= 1
        if right:
            self.rect.right += 1
        if up:
            self.rect.top -= 1
        if down:
            self.rect.bottom += 1

snakegroup = pygame.sprite.Group()
original_snake = snake()
snakegroup.add(original_snake)

class food(pygame.sprite.Sprite):
    """class to control food action"""
    def __init__(self):
        super().__init__() #access the Sprite super class methods
        food1 = pygame.image.load("food1.png").convert_alpha()
        x_pos = randint(50,600)
        y_pos = randint(50,650)
        self.image = food1
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)

foods = pygame.sprite.GroupSingle()
foods.add(food())

multiplier_x_pos = 1
while True:
    """EVENT LOOP CODE"""
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            pygame.quit()
            exit()

        game_active = True
        if pygame.sprite.spritecollideany(foods.sprite, snakegroup):
            foods.empty()
            foods.add(food())
            foods.draw(disp_surface)

            snakegroup.add(snake(original_snake.rect.x-(25*multiplier_x_pos),original_snake.rect.y))
            multiplier_x_pos += 1
            snakegroup.update(left, right, up, down)

        keys = pygame.key.get_pressed()
        events = pygame.event.get()

        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]

        snakegroup.update(left,right,up,down)

    """PYGAME EVENT CODE"""
    if game_active:
        disp_surface = display_surface()

        snakegroup.draw(disp_surface)
        foods.draw(disp_surface)

    else:
        disp_surface.fill((64,64,64))

    pygame.display.update() #update all the surfaces on each frame
    clock.tick(120) #fps

</code>```

答:
See the answer referenced in your question How do I chain the movement of a snake's body?.

You need to use the 2nd solution and adjust the function that creates the snake body. The new function needs to update the positions of the Snakes body Sprites:

def update_body(track, distance):
    body = snakegroup.sprites()
    no_parts = len(body)
    body[0].update(*track[0])
    track_i = 1
    next_i = 1
    for i in range(1, no_parts):
        while track_i < len(track):
            pos = track[track_i]
            track_i += 1
            dx, dy = body[i-1].x_pos-pos[0], body[i-1].y_pos-pos[1]
            if math.sqrt(dx*dx + dy*dy) >= distance:
                body[i].update(*pos)
                next_i = i+1
                break
    while next_i < no_parts:
        body[next_i].update(*track[-1])
        next_i += 1
    del track[track_i:]
    return body
```
<hr />
<p>Example based on your (revised) code:</p>
<p><img src="https://i.stack.imgur.com/2WVYH.gif" alt="" /></p>
<pre class="lang-py prettyprint-override"><code>import pygame
import math
from random import randint
from sys import exit

pygame.init()
clock = pygame.time.Clock()
disp_surface = pygame.display.set_mode(size = (610, 700))

class Snake(pygame.sprite.Sprite):
    def __init__(self, x_pos = 300, y_pos = 300):
        #Access the super class of Sprite
        super().__init__()
        #self.image = pygame.image.load("square1.png").convert_alpha()
        self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (0, 255, 0), (10, 10), 10)
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.rect = self.image.get_rect(x = x_pos, y = y_pos)
    def update(self, x_pos, y_pos):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.rect = self.image.get_rect(center = (x_pos, y_pos))

class Food(pygame.sprite.Sprite):
    """class to control food action"""
    def __init__(self):
        super().__init__() #access the Sprite super class methods
        #self.image = pygame.image.load("food1.png").convert_alpha()
        self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (255, 0, 0), (10, 10), 10)
        x_pos = randint(50,600)
        y_pos = randint(50,650)
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)
    def update(self, pos):
        x_pos = randint(50,600)
        y_pos = randint(50,650)
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)

def update_body(track, distance):
    body = snakegroup.sprites()
    no_parts = len(body)
    body[0].update(*track[0])
    track_i = 1
    next_i = 1
    for i in range(1, no_parts):
        while track_i < len(track):
            pos = track[track_i]
            track_i += 1
            dx, dy = body[i-1].x_pos-pos[0], body[i-1].y_pos-pos[1]
            if math.sqrt(dx*dx + dy*dy) >= distance:
                body[i].update(*pos)
                next_i = i+1
                break
    while next_i < no_parts:
        body[next_i].update(*track[-1])
        next_i += 1
    del track[track_i:]
    return body

snakegroup = pygame.sprite.Group()
original_snake = Snake()
snakegroup.add(original_snake)
track = [(original_snake.x_pos, original_snake.y_pos)]

foods = pygame.sprite.GroupSingle()
foods.add(Food())

direction = (0, 0)
speed = 1
run = True
while run:
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            run = False
        if eachevent.type == pygame.KEYDOWN:
            if eachevent.key == pygame.K_LEFT and direction[0] != 1:
                direction = (-1, 0)
            if eachevent.key == pygame.K_RIGHT and direction[0] != -1:
                direction = (1, 0)
            if eachevent.key == pygame.K_UP and direction[1] != 1:
                direction = (0, -1)
            if eachevent.key == pygame.K_DOWN and direction[1] != -1:
                direction = (0, 1)

    track.insert(0, track[0][:])
    track[0] = (track[0][0] + direction[0] * speed) % disp_surface.get_width(), (track[0][1] + direction[1] * speed) % disp_surface.get_height()
    update_body(track, 20)

    if pygame.sprite.spritecollideany(foods.sprite, snakegroup):
        foods.empty()
        foods.add(Food())
        last_part = snakegroup.sprites()[-1]
        snakegroup.add(Snake(last_part.x_pos, last_part.y_pos))
        speed = min(10, speed + 1)

    disp_surface.fill((64,64,64))
    snakegroup.draw(disp_surface)
    foods.draw(disp_surface)
    pygame.display.update()
    clock.tick(120)
</code>```

Title: Python Snake Game snake does not follow

Body:
I am creating Snake game in pygame using Sprite logic

how do i chain the movement of the snake? another question on this has been answered here but i cant apply it to my code: see here

the minimal example above works. try it first and you will see my issue :)
the snake grows on collision with the red food... but its movement does not chain

thank you

import pygame
from random import randint
from sys import exit

pygame.init()
game_active = True #start the game on the Welcome Screen
clock = pygame.time.Clock() #an object to track time, for fps

def display_surface():
    """function to create the main window"""
    disp_surface = pygame.display.set_mode(size = (610, 700)) #creates a main display window
    pygame.display.set_caption("Snake")
    return disp_surface
disp_surface = display_surface() #MUST return this immediately so it can be pushed to pygame.display.update()

class snake(pygame.sprite.Sprite):
    def __init__(self, x_pos = 300, y_pos = 300):
        #Access the super class of Sprite
        super().__init__()
        image1 = pygame.image.load("square1.png").convert_alpha()
        self.x_pos = x_pos
        self.y_pos = y_pos

        self.image = image1
        self.rect = self.image.get_rect(x = x_pos, y = y_pos)

    def update(self, left, right, up, down):
        """defines the movement of the snake using arrow keys"""
        if left:
            self.rect.left -= 1
        if right:
            self.rect.right += 1
        if up:
            self.rect.top -= 1
        if down:
            self.rect.bottom += 1

snakegroup = pygame.sprite.Group()
original_snake = snake()
snakegroup.add(original_snake)

class food(pygame.sprite.Sprite):
    """class to control food action"""
    def __init__(self):
        super().__init__() #access the Sprite super class methods
        food1 = pygame.image.load("food1.png").convert_alpha()
        x_pos = randint(50,600)
        y_pos = randint(50,650)
        self.image = food1
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)

foods = pygame.sprite.GroupSingle()
foods.add(food())

multiplier_x_pos = 1
while True:
    """EVENT LOOP CODE"""
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            pygame.quit()
            exit()

        game_active = True
        if pygame.sprite.spritecollideany(foods.sprite, snakegroup):
            foods.empty()
            foods.add(food())
            foods.draw(disp_surface)

            snakegroup.add(snake(original_snake.rect.x-(25*multiplier_x_pos),original_snake.rect.y))
            multiplier_x_pos += 1
            snakegroup.update(left, right, up, down)

        keys = pygame.key.get_pressed()
        events = pygame.event.get()

        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]

        snakegroup.update(left,right,up,down)

    """PYGAME EVENT CODE"""
    if game_active:
        disp_surface = display_surface()

        snakegroup.draw(disp_surface)
        foods.draw(disp_surface)

    else:
        disp_surface.fill((64,64,64))

    pygame.display.update() #update all the surfaces on each frame
    clock.tick(120) #fps

Body:
See the answer referenced in your question How do I chain the movement of a snake's body?.

You need to use the 2nd solution and adjust the function that creates the snake body. The new function needs to update the positions of the Snakes body Sprites:

def update_body(track, distance):
    body = snakegroup.sprites()
    no_parts = len(body)
    body[0].update(*track[0])
    track_i = 1
    next_i = 1
    for i in range(1, no_parts):
        while track_i < len(track):
            pos = track[track_i]
            track_i += 1
            dx, dy = body[i-1].x_pos-pos[0], body[i-1].y_pos-pos[1]
            if math.sqrt(dx*dx + dy*dy) >= distance:
                body[i].update(*pos)
                next_i = i+1
                break
    while next_i < no_parts:
        body[next_i].update(*track[-1])
        next_i += 1
    del track[track_i:]
    return body

Example based on your (revised) code:

import pygame
import math
from random import randint
from sys import exit

pygame.init()
clock = pygame.time.Clock()
disp_surface = pygame.display.set_mode(size = (610, 700))

class Snake(pygame.sprite.Sprite):
    def __init__(self, x_pos = 300, y_pos = 300):
        #Access the super class of Sprite
        super().__init__()
        #self.image = pygame.image.load("square1.png").convert_alpha()
        self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (0, 255, 0), (10, 10), 10)
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.rect = self.image.get_rect(x = x_pos, y = y_pos)
    def update(self, x_pos, y_pos):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.rect = self.image.get_rect(center = (x_pos, y_pos))

class Food(pygame.sprite.Sprite):
    """class to control food action"""
    def __init__(self):
        super().__init__() #access the Sprite super class methods
        #self.image = pygame.image.load("food1.png").convert_alpha()
        self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (255, 0, 0), (10, 10), 10)
        x_pos = randint(50,600)
        y_pos = randint(50,650)
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)
    def update(self, pos):
        x_pos = randint(50,600)
        y_pos = randint(50,650)
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)

def update_body(track, distance):
    body = snakegroup.sprites()
    no_parts = len(body)
    body[0].update(*track[0])
    track_i = 1
    next_i = 1
    for i in range(1, no_parts):
        while track_i < len(track):
            pos = track[track_i]
            track_i += 1
            dx, dy = body[i-1].x_pos-pos[0], body[i-1].y_pos-pos[1]
            if math.sqrt(dx*dx + dy*dy) >= distance:
                body[i].update(*pos)
                next_i = i+1
                break
    while next_i < no_parts:
        body[next_i].update(*track[-1])
        next_i += 1
    del track[track_i:]
    return body

snakegroup = pygame.sprite.Group()
original_snake = Snake()
snakegroup.add(original_snake)
track = [(original_snake.x_pos, original_snake.y_pos)]

foods = pygame.sprite.GroupSingle()
foods.add(Food())

direction = (0, 0)
speed = 1
run = True
while run:
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            run = False
        if eachevent.type == pygame.KEYDOWN:
            if eachevent.key == pygame.K_LEFT and direction[0] != 1:
                direction = (-1, 0)
            if eachevent.key == pygame.K_RIGHT and direction[0] != -1:
                direction = (1, 0)
            if eachevent.key == pygame.K_UP and direction[1] != 1:
                direction = (0, -1)
            if eachevent.key == pygame.K_DOWN and direction[1] != -1:
                direction = (0, 1)

    track.insert(0, track[0][:])
    track[0] = (track[0][0] + direction[0] * speed) % disp_surface.get_width(), (track[0][1] + direction[1] * speed) % disp_surface.get_height()
    update_body(track, 20)

    if pygame.sprite.spritecollideany(foods.sprite, snakegroup):
        foods.empty()
        foods.add(Food())
        last_part = snakegroup.sprites()[-1]
        snakegroup.add(Snake(last_part.x_pos, last_part.y_pos))
        speed = min(10, speed + 1)

    disp_surface.fill((64,64,64))
    snakegroup.draw(disp_surface)
    foods.draw(disp_surface)
    pygame.display.update()
    clock.tick(120)


问:
Retrieve child entry from Firebase Realtime Database without []. - Swift 5
I'm a little stuck with something small but that is giving me some headaches! I have a Realtime Database and I am able to retrieve the information I need from it. My only problem is that instead of printing for example (ex.: 200) is printing (ex.: [200])!

This is my code:

```<code>func readData() {

  FirebaseDatabase.Database.database().reference().child("Available_Funds").observeSingleEvent(of: .value, with: { snapshot in
            guard let value = snapshot.value as? [String: Any] else {
                return
            }
            let amountWallet = value.values
            print(amountWallet)
            self.currentBalanceLabel.text = "$" + "\(amountWallet)"
            print("\(value)")
        })
    }
</code>```

Right now what I get printed with this code is $[200] for example, instead of just $200, which is what I intend to get.

Tried looking online, but no luck with this! Does someone know how to remove these square brackets from printing?

答:
You're calling it back as an array of strings [String: Any]

You can either change this (remove []) or access the first element in the array: amountWallet[0].

Body:
I'm a little stuck with something small but that is giving me some headaches! I have a Realtime Database and I am able to retrieve the information I need from it. My only problem is that instead of printing for example (ex.: 200) is printing (ex.: [200])!

This is my code:

func readData() {

  FirebaseDatabase.Database.database().reference().child("Available_Funds").observeSingleEvent(of: .value, with: { snapshot in
            guard let value = snapshot.value as? [String: Any] else {
                return
            }
            let amountWallet = value.values
            print(amountWallet)
            self.currentBalanceLabel.text = "$" + "\(amountWallet)"
            print("\(value)")
        })
    }

Right now what I get printed with this code is $[200] for example, instead of just $200, which is what I intend to get.

Tried looking online, but no luck with this! Does someone know how to remove these square brackets from printing?


问:
Python - How can I line up the equals sign of all my equations?
Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.

Here is the code I already wrote :

```<code>def div(n):
  return [x for x in range(1,n+1) if n%x==0]

def pgcd(x,y):
  a = x
  b = y

  while b > 0:
    reste = a % b
    print(a, "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
</code>```

And it ouputs this :

```<code>pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
</code>```

I want it to output that :

```<code>178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0
</code>```

I've read many articles online but I have no idea how to put that into my code.

Thanks in advance.

答:
See .format for strings. An example of right justifying would look something like print('{:>6}'.format(42))

You can also use rjust

Body:
Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.

Here is the code I already wrote :

def div(n):
  return [x for x in range(1,n+1) if n%x==0]

def pgcd(x,y):
  a = x
  b = y

  while b > 0:
    reste = a % b
    print(a, "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)

And it ouputs this :

pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0

I want it to output that :

178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0

I've read many articles online but I have no idea how to put that into my code.

Thanks in advance.


问:
loading multiple video players with youtube api
I need to load more than one video with youtube's API. This is my first time using it so I'm not sure what I'm doing wrong, but this is what I'm trying:</p>

```<code>  var player;
  var player2;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      videoId: 'hdy78ehsjdi'
    });
    player2 = new YT.Player('player', {
      videoId: '81hdjskilct'
    });
  }
</code>```

答:
```<code><iframe title="YouTube video player" src="https:YOUR CHANNEL Full Link" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</code>```

Body:
I need to load more than one video with youtube's API. This is my first time using it so I'm not sure what I'm doing wrong, but this is what I'm trying:

  var player;
  var player2;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      videoId: 'hdy78ehsjdi'
    });
    player2 = new YT.Player('player', {
      videoId: '81hdjskilct'
    });
  }


问:
Convert UTC datetime string to local datetime
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

```<code>datetime.utcfromtimestamp(timestamp)
</code>```

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

```<code>"2011-01-21 02:37:21"
</code>```

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

答:
Short and simple:</p>
```<code>from datetime import datetime

t = "2011-01-21 02:37:21"
datetime.fromisoformat(t) + (datetime.now() - datetime.utcnow())
</code>```

Body:
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

Body:
Short and simple:

from datetime import datetime

t = "2011-01-21 02:37:21"
datetime.fromisoformat(t) + (datetime.now() - datetime.utcnow())