问:
Unable to join two tables with django rest framework
I am trying to join two tables and serialize them as an API. I have referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after trying so many times. I am trying to get a JSON file like

```<code>{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
    {'order': 1, 'title': 'Public Service Announcement'},
    {'order': 2, 'title': 'What More Can I Say'},
    {'order': 3, 'title': 'Encore'},
    ...
  ],
}
</code>```

But what I get is

```<code>{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
}
</code>```

This is the model file I am using

Model.py

```<code>from django.db import models
from django.contrib.auth.models import User

STATUS_CHOICE = (
    ('simple', 'simple'),
    ('intermediate', 'intermediate'),
)

class Quiz(models.Model):
    quiz_name = models.CharField(max_length=1000)
    video_id = models.ForeignKey("youtube.Youtube",  on_delete=models.CASCADE)
    questions_count = models.IntegerField(default=0)
    description = models.CharField(max_length=70, null=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField()
    pass_mark = models.IntegerField()
    class Meta:
        ordering = ['created']
    def __str__(self):
        return self.quiz_name

class Category(models.Model):
    category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple')
    quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    def __str__(self):
        return self.category

class Questions(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    question = models.CharField(max_length=1000)
    mark = models.IntegerField()
    def __str__(self):
        return self.question

class Choice(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    choice_1 = models.CharField(max_length=1000)
    choice_2 = models.CharField(max_length=1000)
    choice_3 = models.CharField(max_length=1000)
    choice_4 = models.CharField(max_length=1000)
    answer = models.CharField(max_length=1000, default=choice_1)

    def __str__(self):
        return self.answer
</code>```

Serializer.py

```<code>from rest_framework import  serializers
from rest_framework.permissions import IsAuthenticated
from .models import Category, Quiz, Questions, Choice
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

class QuizSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quiz
        fields = '__all__'

class QuestionsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questions
        fields = '__all__'

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):
    quiz_name =  QuizSerializer(read_only=True)
    class Meta:
        model = Category
        fields = ['id','category','quiz_name']
</code>```

View.py

```<code>from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from .serializer import CategorySerializer
from .models import Category

class ViewQuiz(generics.ListCreateAPIView):
    permission_classes = [
        permissions.AllowAny,
    ]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    def list(self, request):
        queryset = self.get_queryset()
        serializer = CategorySerializer(queryset, many=True)
        print(serializer.data)
        return Response(serializer.data)
</code>```

答:
Looks like you are trying to get questions serializes in quiz.
To do that you need to:
1. In Questions model include related_name in quiz field:

```<code>class Questions(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions")
    question = models.CharField(max_length=1000)
    mark = models.IntegerField()

    def __str__(self):
        return self.question
</code>```

In QuizSerializer include questions field and set many to True:

```<code>class QuizSerializer(serializers.ModelSerializer):
    questions = QuestionsSerializer(source="questions", many=True)

    class Meta:
        model = Quiz
        fields = ("questions", ... other needed fields)
</code>```

Include source attribute in QuizSerializer in CategorySerializer:

```<code>class CategorySerializer(serializers.ModelSerializer):
    quiz_name = QuizSerializer(read_only=True, source="quiz_id")

    class Meta:
        model = Category
        fields = ['id', 'category', 'quiz_name']
</code>```

Your Quiz was not serialized because the relation between Category and Quiz in tables are called quiz_id but your field is called quiz_name, so the framework did not know where it should take quiz, because it was looking at quiz_name relation which does not exist.

Body:
I am trying to join two tables and serialize them as an API. I have referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after trying so many times. I am trying to get a JSON file like

{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
    {'order': 1, 'title': 'Public Service Announcement'},
    {'order': 2, 'title': 'What More Can I Say'},
    {'order': 3, 'title': 'Encore'},
    ...
  ],
}

But what I get is

{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
}

This is the model file I am using

Model.py

from django.db import models
from django.contrib.auth.models import User

STATUS_CHOICE = (
    ('simple', 'simple'),
    ('intermediate', 'intermediate'),
)

class Quiz(models.Model):
    quiz_name = models.CharField(max_length=1000)
    video_id = models.ForeignKey("youtube.Youtube",  on_delete=models.CASCADE)
    questions_count = models.IntegerField(default=0)
    description = models.CharField(max_length=70, null=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField()
    pass_mark = models.IntegerField()
    class Meta:
        ordering = ['created']
    def __str__(self):
        return self.quiz_name

class Category(models.Model):
    category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple')
    quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    def __str__(self):
        return self.category

class Questions(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    question = models.CharField(max_length=1000)
    mark = models.IntegerField()
    def __str__(self):
        return self.question

class Choice(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    choice_1 = models.CharField(max_length=1000)
    choice_2 = models.CharField(max_length=1000)
    choice_3 = models.CharField(max_length=1000)
    choice_4 = models.CharField(max_length=1000)
    answer = models.CharField(max_length=1000, default=choice_1)

    def __str__(self):
        return self.answer

Serializer.py

from rest_framework import  serializers
from rest_framework.permissions import IsAuthenticated
from .models import Category, Quiz, Questions, Choice
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

class QuizSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quiz
        fields = '__all__'

class QuestionsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questions
        fields = '__all__'

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):
    quiz_name =  QuizSerializer(read_only=True)
    class Meta:
        model = Category
        fields = ['id','category','quiz_name']

View.py

from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from .serializer import CategorySerializer
from .models import Category

class ViewQuiz(generics.ListCreateAPIView):
    permission_classes = [
        permissions.AllowAny,
    ]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    def list(self, request):
        queryset = self.get_queryset()
        serializer = CategorySerializer(queryset, many=True)
        print(serializer.data)
        return Response(serializer.data)

Body:
Looks like you are trying to get questions serializes in quiz.
To do that you need to:
1. In Questions model include related_name in quiz field:

class Questions(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions")
    question = models.CharField(max_length=1000)
    mark = models.IntegerField()

    def __str__(self):
        return self.question

In QuizSerializer include questions field and set many to True:

class QuizSerializer(serializers.ModelSerializer):
    questions = QuestionsSerializer(source="questions", many=True)

    class Meta:
        model = Quiz
        fields = ("questions", ... other needed fields)

Include source attribute in QuizSerializer in CategorySerializer:

class CategorySerializer(serializers.ModelSerializer):
    quiz_name = QuizSerializer(read_only=True, source="quiz_id")

    class Meta:
        model = Category
        fields = ['id', 'category', 'quiz_name']

Your Quiz was not serialized because the relation between Category and Quiz in tables are called quiz_id but your field is called quiz_name, so the framework did not know where it should take quiz, because it was looking at quiz_name relation which does not exist.


来源: stackexchange

问:
How to comprehend that the type of `std::function` depends solely on its call signature?
As per the documentation(http://www.cplusplus.com/reference/functional/function/), which says that:

Class that can wrap any kind of callable element (such as functions
  and function objects) into a copyable object, and whose type depends
  solely on its call signature (and not on the callable element type
  itself).

How to comprehend that the type of std::function depends solely on its call signature(and not on the callable element type itself)? Could somebody make it clear by giving some simple examples?I would be greatful to have some help with this question.

答:
These two "callable elements" have the same call signatures (namely, int(float)), even though they have different types:

struct Functor {
  int operator()(float arg) {
    ...
  }
};

int function(float arg) {
  ...
}
```

<p>This means you can use the same <code>std::function</code> type to represent either of them:</p>

<pre class="lang-cpp prettyprint-override"><code>std::function<int(float)> f;
f = Functor();
f = function;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
These two "callable elements" have the same call signatures (namely, int(float)), even though they have different types:

struct Functor {
  int operator()(float arg) {
    ...
  }
};

int function(float arg) {
  ...
}

This means you can use the same std::function type to represent either of them:

std::function<int(float)> f;
f = Functor();
f = function;


问:
How do I do css transition delays in reverse other than for hover?
I've got a vue.js application in which I'm trying to figure out how to reverse a delayed css transition. I have a div whose width contracts when the user clicks the close button. Then the height contracts. The height has the delay on it because I want to wait for the width to contract before contracting the height.

BEFORE:

AFTER:

When the user clicks the question mark icon, I want the reverse to happen. The height should expand immediately and then the width expands after a delay.

All the examples of how to do this which I find on google deal with hover transitions. They say to put the reverse transitions in the hover class. All demos I've seen work. But there must be something different about how this works when it comes to transitions that are trigger by something other than hover. In my case, the trigger is a mouse click. And the online solutions don't work. What happens instead is that the reverse transition placed in transitioned-to class seems to override the original transition--which means the original transition contracts the height first (which looks terrible considering the content doesn't fit) then the width.

Here is my code:

```<code>.need-help-container {
    position: absolute;
    right: 0;
    height: 120px;
    ...
    transition: right .5s, height .5s .5s;
}

.need-help-container-closed {
    right: -360px;
    height: 50px;

    transition: right .5s .5s, height .5s; // <-- doesn't work
}
</code>```

```<code><!-- need help box -->
<div class="need-help-container" :class="{'need-help-container-closed': needHelpClosed}">
...
    <!-- close button -->
    <div ...>
        <v-icon @click="needHelpClosed = true" ...>close</v-icon>
    </div>
</div>
</code>```

Should the same solution to the examples involving hover work here? If so, why would it not be working for me? If no, what would be an alternate solution for my case?

Thanks.

答:
I figured out a solution. I created a separate class just for reversing the order of the delay:

```<code>.need-help-container-opening {
  trnasition: right .5s .5s, height .5s;
}
</code>```

Then I added the class based on a new variable:

```<code><div class="need-help-container"
  :class="{'need-help-container-closed': needHelpClosed, 'need-help-container-opening': needHelpOpening}"
  @transitionend="needHelpOpening = false">
    <div class="faq-icon-container need-help-item"
      :class="{'faq-icon-container-closed': needHelpClosed}"
      @click="needHelpOpening = true; needHelpClosed = false">
        // Question Mark icon... click to open
    </div>
...
</div>
</code>```

So I have a variable called needHelpOpening which I set to true when the user clicks the question mark to open the box. When this variable is true, the box gets the need-help-container-opening class which reverses the delay. Finally, when the transition ends, the transitionend event fires and I catch it in the main div for the box and set needHelpOpening to false so that the original delay order is reset.

Body:
I've got a vue.js application in which I'm trying to figure out how to reverse a delayed css transition. I have a div whose width contracts when the user clicks the close button. Then the height contracts. The height has the delay on it because I want to wait for the width to contract before contracting the height.

BEFORE:

AFTER:

When the user clicks the question mark icon, I want the reverse to happen. The height should expand immediately and then the width expands after a delay.

All the examples of how to do this which I find on google deal with hover transitions. They say to put the reverse transitions in the hover class. All demos I've seen work. But there must be something different about how this works when it comes to transitions that are trigger by something other than hover. In my case, the trigger is a mouse click. And the online solutions don't work. What happens instead is that the reverse transition placed in transitioned-to class seems to override the original transition--which means the original transition contracts the height first (which looks terrible considering the content doesn't fit) then the width.

Here is my code:

.need-help-container {
    position: absolute;
    right: 0;
    height: 120px;
    ...
    transition: right .5s, height .5s .5s;
}

.need-help-container-closed {
    right: -360px;
    height: 50px;

    transition: right .5s .5s, height .5s; // <-- doesn't work
}

...

        <v-icon @click="needHelpClosed = true" ...>close</v-icon>

Should the same solution to the examples involving hover work here? If so, why would it not be working for me? If no, what would be an alternate solution for my case?

Thanks.

Body:
I figured out a solution. I created a separate class just for reversing the order of the delay:

.need-help-container-opening {
  trnasition: right .5s .5s, height .5s;
}

Then I added the class based on a new variable:

<div class="need-help-container"
  :class="{'need-help-container-closed': needHelpClosed, 'need-help-container-opening': needHelpOpening}"
  @transitionend="needHelpOpening = false">
    <div class="faq-icon-container need-help-item"
      :class="{'faq-icon-container-closed': needHelpClosed}"
      @click="needHelpOpening = true; needHelpClosed = false">
        // Question Mark icon... click to open
    </div>
...
</div>

So I have a variable called needHelpOpening which I set to true when the user clicks the question mark to open the box. When this variable is true, the box gets the need-help-container-opening class which reverses the delay. Finally, when the transition ends, the transitionend event fires and I catch it in the main div for the box and set needHelpOpening to false so that the original delay order is reset.


问:
Marie JS to the power of
I need to write a code for raising x to the power of y in Marie.js. That's what I have for now, however it spits out an error SyntaxError:L41 - Unknown label Loop.

```<code>Input
Subt One
Store Count

Input
Store x
Store y
Jns Exp

Load Wyn
Output
End, Halt

Exp, Hex 0
Loop2, Load Count
    Skipcond 800
    JumpI Exp
    JnS Multi
    Load Wyn
    Store x
    Load Count
    Subt One
    Store Count
    Jump Loop2

Multi, Hex 0
    Load Zero
    Store Wyn
    Loop, Load x
    Skipcond 800
    JumpI Multi
    Load Wyn
    Add y
    Store Wyn
    Load x
    Subt One
    Store x
    Jump Loop

x, Dec 2
y, Dec 3
Zero, Dec 0
One, Dec 1
Wyn, Dec 0
Count, Dec 0
</code>```

I understand the necessity for 2 loops, which execute y-1 times, however Im completely clueless what I'm doing wrong.

答: You have to define a label before you can Jump to it; you have not defined the label Loop.  You have defined a label named Loop2.

Title: Marie JS to the power of

Body:
I need to write a code for raising x to the power of y in Marie.js. That's what I have for now, however it spits out an error SyntaxError:L41 - Unknown label Loop.

Input
Subt One
Store Count

Input
Store x
Store y
Jns Exp

Load Wyn
Output
End, Halt

Exp, Hex 0
Loop2, Load Count
    Skipcond 800
    JumpI Exp
    JnS Multi
    Load Wyn
    Store x
    Load Count
    Subt One
    Store Count
    Jump Loop2

Multi, Hex 0
    Load Zero
    Store Wyn
    Loop, Load x
    Skipcond 800
    JumpI Multi
    Load Wyn
    Add y
    Store Wyn
    Load x
    Subt One
    Store x
    Jump Loop

x, Dec 2
y, Dec 3
Zero, Dec 0
One, Dec 1
Wyn, Dec 0
Count, Dec 0

I understand the necessity for 2 loops, which execute y-1 times, however Im completely clueless what I'm doing wrong.


问:
Remove rows in pandas df with index values within a range
I would like to remove all rows in a pandas df that have an index value within 4 counts of the index value of the previous row.

In the pandas df below,

```<code>    A   B
0   1   1
5   5   5
8   9   9
9   10  10
</code>```

Only the row with index value 0 should remain.

Thanks!

答:
get the differences between the current and previous row as a list and pass to loc. Chose to get it as a list so i could return a dataframe as a final output.

```<code>ind = [ a for a,b in zip(df.index,df.index[1:]) if b-a > 4]
df.loc[ind]

    A   B
0   1   1
</code>```

Body:
I would like to remove all rows in a pandas df that have an index value within 4 counts of the index value of the previous row.

In the pandas df below,

    A   B
0   1   1
5   5   5
8   9   9
9   10  10

Only the row with index value 0 should remain.

Thanks!

Body:
get the differences between the current and previous row as a list and pass to loc. Chose to get it as a list so i could return a dataframe as a final output.

ind = [ a for a,b in zip(df.index,df.index[1:]) if b-a > 4]
df.loc[ind]

    A   B
0   1   1


问:
Conditionally incude ansible role's variable files
Ordinarily I would dump variables in roles/myrole/defaults/main.yml. I don't need to explicitly include them - that's done for me automatically.

But let's say I need to support Debian and CentOS and have identical variables with different values. The common advice is:

```<code>roles/myrole/defaults/main.yml       # common defaults
roles/myrole/vars/debian.yml         # debian overrides
roles/myrole/vars/centos.yml         # centos overrides
</code>```

And then we're supposed to "conditionally include" the correct set of variables.

But where exactly? In the main task, or a "main" variables file, or somewhere else?

答:
Q: "But where exactly? In the main task, or a "main" variables file, or somewhere else?"

In the main task, I'd say. For example

- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"
```

<hr>

<p>A user can keep customized variables in <code>vars</code>. Put the defaults into the directory <code>vars/defaults</code>. This way the customized variables will survive potential updates of the role.</p>

<pre class="lang-yaml prettyprint-override"><code># Default variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars/defaults"

# Custom variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"
</code>```

available at GitHub

Body:
Ordinarily I would dump variables in roles/myrole/defaults/main.yml. I don't need to explicitly include them - that's done for me automatically.

But let's say I need to support Debian and CentOS and have identical variables with different values. The common advice is:

roles/myrole/defaults/main.yml       # common defaults
roles/myrole/vars/debian.yml         # debian overrides
roles/myrole/vars/centos.yml         # centos overrides

And then we're supposed to "conditionally include" the correct set of variables.

But where exactly? In the main task, or a "main" variables file, or somewhere else?

Body:
Q: "But where exactly? In the main task, or a "main" variables file, or somewhere else?"

In the main task, I'd say. For example

- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"

A user can keep customized variables in vars. Put the defaults into the directory vars/defaults. This way the customized variables will survive potential updates of the role.

# Default variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars/defaults"

# Custom variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"

available at GitHub


问:
How to avoid parallel class hierarchy in python
I've been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concocted:

```<code>class DogHabits:
    def __init__(self):
        self.habits = ['lick butt']

class GermanShepherdHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['herd sheep'])

class LabradorHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['hunt', 'pee on owner'])

class Dog:
    def __init__(self):
        self.type = 'generic_dog'
        self.my_habits = DogHabits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):
    def __init__(self):
        self.type = 'german shepherd'
        self.my_habits = GermanShepherdHabits()

class Labrador(Dog):
    def __init__(self):
        self.type = 'labrador'
        self.my_habits = LabradorHabits()

if __name__ == "__main__":
    german_shepherd = GermanShepherd()
    print('\n{}'.format(german_shepherd.type))
    german_shepherd.do_stuff()

    labrador = Labrador()
    print('\n{}'.format(labrador.type))
    labrador.do_stuff()
</code>```

I have a generic dog class from which concrete dog implementations inherit. Every dog class (including the generic/abstract one) has a set of habits, itself represented by another class hierarchy for the habits.

I am annoyed by the fact that I have to have both hierarchies exactly the same at all times. Furthermore the inheritance between the DogHabits is useful within the habits hierarchy, but it is not useful within the dogs hierarchy, as I need to instantiate a separate habits object for each class in the dog hierarchy.

What is the antidote to this? I may want to add many implementations of the dog class, and updating the corresponding habits hierarchy sounds tedious and smells bad...

答:
This might be going too far afield, but I don't see the need for a separate DogHabits class. habits should be a class attribute, not an instance attribute, and could be set by __init_subclass__.

```<code>class Dog:
    habits = ['lick butts']

    def __init_subclass__(cls, habits=None, **kwargs):
        super().__init_subclass__(**kwargs)
        if habits is not None:
            cls.habits = cls.habits + habits

class GermanShepherd(Dog, habits=['herd sheep']):
    def __init__(self):
        self.type = 'german shepherd'

class Labrador(Dog, habits=['pee on owner']):
    def __init__(self):
        self.type = 'labrador'
</code>```

type itself is also more of a class attribute than an instance attribute, as it's simply an (alternate) string representation of information already encoded by the class itself. Since you wouldn't append to an existing value, it's easier to just set the class attribute where necessary rather than going through __init_subclass:

```<code>class Dog:
    habits = ['lick butts']
    type = 'generic_dog'

    def __init_subclass__(cls, habits=None, **kwargs):
        super().__init_subclass__(**kwargs)
        if habits is not None:
            cls.habits = cls.habits + habits

class GermanShepherd(Dog, habits=['herd sheep']):
    type = 'german shepard'

class Labrador(Dog, habits=['pee on owner']):
    type = 'labrador'

class BlackLabrador(Labrador):
    pass  # E.g. if you are happy with inheriting Labrador.type
</code>```

Body:
I've been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concocted:

class DogHabits:
    def __init__(self):
        self.habits = ['lick butt']

class GermanShepherdHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['herd sheep'])

class LabradorHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['hunt', 'pee on owner'])

class Dog:
    def __init__(self):
        self.type = 'generic_dog'
        self.my_habits = DogHabits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):
    def __init__(self):
        self.type = 'german shepherd'
        self.my_habits = GermanShepherdHabits()

class Labrador(Dog):
    def __init__(self):
        self.type = 'labrador'
        self.my_habits = LabradorHabits()

if __name__ == "__main__":
    german_shepherd = GermanShepherd()
    print('\n{}'.format(german_shepherd.type))
    german_shepherd.do_stuff()

    labrador = Labrador()
    print('\n{}'.format(labrador.type))
    labrador.do_stuff()

I have a generic dog class from which concrete dog implementations inherit. Every dog class (including the generic/abstract one) has a set of habits, itself represented by another class hierarchy for the habits.

I am annoyed by the fact that I have to have both hierarchies exactly the same at all times. Furthermore the inheritance between the DogHabits is useful within the habits hierarchy, but it is not useful within the dogs hierarchy, as I need to instantiate a separate habits object for each class in the dog hierarchy.

What is the antidote to this? I may want to add many implementations of the dog class, and updating the corresponding habits hierarchy sounds tedious and smells bad...

Body:
This might be going too far afield, but I don't see the need for a separate DogHabits class. habits should be a class attribute, not an instance attribute, and could be set by __init_subclass__.

class Dog:
    habits = ['lick butts']

    def __init_subclass__(cls, habits=None, **kwargs):
        super().__init_subclass__(**kwargs)
        if habits is not None:
            cls.habits = cls.habits + habits

class GermanShepherd(Dog, habits=['herd sheep']):
    def __init__(self):
        self.type = 'german shepherd'

class Labrador(Dog, habits=['pee on owner']):
    def __init__(self):
        self.type = 'labrador'

type itself is also more of a class attribute than an instance attribute, as it's simply an (alternate) string representation of information already encoded by the class itself. Since you wouldn't append to an existing value, it's easier to just set the class attribute where necessary rather than going through __init_subclass:

class Dog:
    habits = ['lick butts']
    type = 'generic_dog'

    def __init_subclass__(cls, habits=None, **kwargs):
        super().__init_subclass__(**kwargs)
        if habits is not None:
            cls.habits = cls.habits + habits

class GermanShepherd(Dog, habits=['herd sheep']):
    type = 'german shepard'

class Labrador(Dog, habits=['pee on owner']):
    type = 'labrador'

class BlackLabrador(Labrador):
    pass  # E.g. if you are happy with inheriting Labrador.type


问:
How to find the source video size using VMR9 renderless mode
My application uses VMR9 Renderless mode to play a WMV file.  I build a filter graph with IGraphBuilder::RenderFile and control playback with IMediaControl.  Everything plays okay, but I can't figure out how to determine the source video size.  Any ideas?

Note: This question was asked before in How can I adjust the video to a specified size in VMR9 renderless mode?. But the solution was to use Windowless mode instead of Renderless mode, which would require rewriting my code.

答: Firstly you want the Video renderer.  You can do this by using EnumFilters on the IGraphBuilder interface.  Then call EnumPins on that filter to find the input pin.  You can then call ConnectionMediaType to get the media type being fed into that filter.  Now depending what formattype is set to you can cast the pbFormat pointer to the relevant structure and from there find out what the video size is.  If you want the size before that (to see if some scaling is going on) you can work your way back across the pin using "ConnectedTo" to get the next filter back.  You can then find its input pins and repeat the ConnectionMediaType call.  Repeat until you get to the filter's pin that you want.</p>

ContentLicense: CC BY-SA 3.0


答:
There are different kinds of callable's, namely functions and functors.  std::function was designed to not mater which of those you give to it, for example, lets consider a std::function <void()>.  Here we say the function is one that return nothing and takes nothing, which means that

```<code>void foo() {}
auto bar = []{};
struct { void operator()(){} } baz;
</code>```

are all things that can be assigned to it, even though they are all different types.

Title: How to comprehend that the type of `std::function` depends solely on its call signature?

Body:
As per the documentation(http://www.cplusplus.com/reference/functional/function/), which says that:

Class that can wrap any kind of callable element (such as functions
  and function objects) into a copyable object, and whose type depends
  solely on its call signature (and not on the callable element type
  itself).

How to comprehend that the type of std::function depends solely on its call signature(and not on the callable element type itself)? Could somebody make it clear by giving some simple examples?I would be greatful to have some help with this question.

Body:
There are different kinds of callable's, namely functions and functors.  std::function was designed to not mater which of those you give to it, for example, lets consider a std::function <void()>.  Here we say the function is one that return nothing and takes nothing, which means that

void foo() {}
auto bar = []{};
struct { void operator()(){} } baz;

are all things that can be assigned to it, even though they are all different types.


问:
Pip cannot find a specific version of VTK package although it is in PyPI
I accidentally installed VTK 9.0.0, but want to downgrade to 8.1.2.

I uninstalled VTK 9.0.0 using pip uninstall but now I cannot install 8.1.2 for a weird unknown reason:

```<code>$ pip install "vtk==8.1"
ERROR: Could not find a version that satisfies the requirement vtk==8.1 (from versions: 9.0.0)
ERROR: No matching distribution found for vtk==8.1
</code>```

The version 8.1 is definitely in PyPI. Why pip complaints and does not the needed operation?

答:
This answer is based on @metatoaster's comment.

In this case, pip could not find VTK 8.1 because the package VTK is not available for Python 3.8 for versions < 9.0, while I used Python 3.8.

Body:
I accidentally installed VTK 9.0.0, but want to downgrade to 8.1.2.

I uninstalled VTK 9.0.0 using pip uninstall but now I cannot install 8.1.2 for a weird unknown reason:

$ pip install "vtk==8.1"
ERROR: Could not find a version that satisfies the requirement vtk==8.1 (from versions: 9.0.0)
ERROR: No matching distribution found for vtk==8.1

The version 8.1 is definitely in PyPI. Why pip complaints and does not the needed operation?


问:
Localized routes in koa
I'm developing a site with multiple languages. Some routes will therefore also have to be localized and I'm not sure how to do this properly.

I'm using @koa/router for routing.

For this example it's only English and Swedish but the site will handle more languages.

I can setup routes to match words in different languages like

```<code>router.get('/(create-account|skapa-konto)/', (ctx, next) => {
  ctx.body = translate('signup_welcome');
  await next();
});
</code>```

But, I want the English site to only respond to '/sign-up' and send 404 for '/skapa-konto' (and vice versa).

In the real world the route would point to some controller function. So if I set up individual routes for each language I would have to change all localized routes manually should the controller function change in the future. That's something I would like to avoid ;)

Any suggestions?

答:
I ended up solving this by extending the Router like this:

```<code>const LocalizedRouter = class extends Router {
    /**
     * Set up route mapping
     * @param {object} options
     */
    constructor(options) {
        if (!Array.isArray(options.languages)) {
            throw new TypeError('Languages must be of type Array');
        }

        super(options);
        this.languages = options.languages;
    }

    /**
     * Router function for GET method
     * @param {string | Object<string, string>} RouteCollection
     */
    get(routes, func) {
        if (typeof(routes) === 'string') {
            super.get(routes, func);
            return;
        }
        if (typeof(routes) === 'object') {
            for(const key in routes) {
                if(!this.languages.includes(key)) {
                    continue;
                }
                if(typeof(func) !== 'function') {
                    throw new TypeError('Middleware must be a function');
                }
                const checkLanguageAndMount = async (ctx, next) => {
                    if(ctx.state.lang !== key) {
                        return next();
                    }
                    return func(ctx, next);
                };

                super.get(routes[key], checkLanguageAndMount);
            }
            return;
        }
        throw new TypeError('"Routes" must be a string or an object');
    }
};

</code>```

I can then set up my routes like this:

```<code>const myRouter = new LocalizedRouter({
    languages: ['en', 'sv']
});

myRouter.get({
    'en': '/create-account',
    'sv': '/skapa-konto'
}, (ctx, next) => {
  ctx.body = translate('signup_welcome');
  await next();
};
</code>```

This can probably be cleaned up but it does solve what I wanted to do.

EDIT: Fixed bug that caused 404 if two languages had identical paths

Title: Localized routes in koa

Body:
I'm developing a site with multiple languages. Some routes will therefore also have to be localized and I'm not sure how to do this properly.

I'm using @koa/router for routing.

For this example it's only English and Swedish but the site will handle more languages.

I can setup routes to match words in different languages like

router.get('/(create-account|skapa-konto)/', (ctx, next) => {
  ctx.body = translate('signup_welcome');
  await next();
});

But, I want the English site to only respond to '/sign-up' and send 404 for '/skapa-konto' (and vice versa).

In the real world the route would point to some controller function. So if I set up individual routes for each language I would have to change all localized routes manually should the controller function change in the future. That's something I would like to avoid ;)

Any suggestions?

Body:
I ended up solving this by extending the Router like this:

const LocalizedRouter = class extends Router {
    /**
     * Set up route mapping
     * @param {object} options
     */
    constructor(options) {
        if (!Array.isArray(options.languages)) {
            throw new TypeError('Languages must be of type Array');
        }

        super(options);
        this.languages = options.languages;
    }

    /**
     * Router function for GET method
     * @param {string | Object<string, string>} RouteCollection
     */
    get(routes, func) {
        if (typeof(routes) === 'string') {
            super.get(routes, func);
            return;
        }
        if (typeof(routes) === 'object') {
            for(const key in routes) {
                if(!this.languages.includes(key)) {
                    continue;
                }
                if(typeof(func) !== 'function') {
                    throw new TypeError('Middleware must be a function');
                }
                const checkLanguageAndMount = async (ctx, next) => {
                    if(ctx.state.lang !== key) {
                        return next();
                    }
                    return func(ctx, next);
                };

                super.get(routes[key], checkLanguageAndMount);
            }
            return;
        }
        throw new TypeError('"Routes" must be a string or an object');
    }
};

I can then set up my routes like this:

const myRouter = new LocalizedRouter({
    languages: ['en', 'sv']
});

myRouter.get({
    'en': '/create-account',
    'sv': '/skapa-konto'
}, (ctx, next) => {
  ctx.body = translate('signup_welcome');
  await next();
};

This can probably be cleaned up but it does solve what I wanted to do.

EDIT: Fixed bug that caused 404 if two languages had identical paths


问:
MOUSEOVER: How to start a function and let it play until the end without start it over and over?
I want to start a function when I over mouse an ID #show-details.
But I need it to start only one until it ends, not to start over and over again ...

With my code below It starts when I mouseover it but starts over and over even if it doesn't finish.
I need some help :)

```<code>function showDetails() {

  var details = document.getElementById('show-details');

  details.addEventListener('mouseover', initDetailsLetters);

}
</code>```

答: i think you need a flag, if the flag doesnt exist then create it and start over, if it does exist then dont run the code</p>

Body:
I want to start a function when I over mouse an ID #show-details.
But I need it to start only one until it ends, not to start over and over again ...

With my code below It starts when I mouseover it but starts over and over even if it doesn't finish.
I need some help :)

function showDetails() {

  var details = document.getElementById('show-details');

  details.addEventListener('mouseover', initDetailsLetters);

}


问:
editor component like RichEdit that supports embedding photos?
can anyone suggest an editor component like RichEdit that supports embedding photos in a delphi app?  RichEdit doesn't seem to support this.

am not considering embedding MS Word since not everyone would have that.

than you for your help!

答: AFAIR the TrxRichEdit from rxlib supported embedding pictures. Since rxlib was incorporated into the jvcl, I guess TJvRichEdit should as well.</p>

OwnerDisplayName: X-Ray

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dummzeuch


问:
How do I properly cancel a Boost deadline_timer from a destructor (in a multithreaded environment)?
I have a class called Timer that exposes two methods called start and stop.

void Timer::start() {
    _enabled.store(true, std::memory_order::memory_order_release);
    _timer.expires_from_now(_delay);
    _timer.async_wait(
        std::bind(
            &Timer::tick,
            this,
            std::placeholders::_1
        ));
}

void Timer::stop() {
    _enabled.store(false, std::memory_order::memory_order_release);
    _timer.cancel();
}

void Timer::tick(const boost::system::error_code& error) {
    if (error) return;
    if (!_enabled.load(std::memory_order::memory_order_acquire)) return;
    try {
        _task();
    } catch (...) {}
    if (_enabled.load(std::memory_order::memory_order_acquire)) {
        _timer.expires_from_now(_delay);
        _timer.async_wait(
            std::bind(
                &Timer::tick,
                this,
                std::placeholders::_1
            ));
    }
}
```

<p>Another class that uses an instance of <code>Timer</code> (handler is executed on some other thread in a ThreadPool instance) calls <code>stop</code> in its destructor. From the Boost Documentation, it is now possible that the handler will be invoked and these two functions will be executed concurrently and the handler may try to access freed resources.</p>

<pre class="lang-cpp prettyprint-override"><code>SomeOtherClass::~SomeOtherClass() {
    _timer.stop();
    // somehow wait for _timer handler to execute
    // delete[] some_thing;
    // other destructive things
}
</code>```

Is there anyway to wait for the handler to finish execution? I've been scratching my head all day, I am quite new to Boost, so perhaps I made a design flaw. Any help would be greatly appreciated, thanks.

答:
A pattern is to have a shared_ptr to your Timer (by using std::enable_shared_from_this).

That way you can keep the timer alive as long as the handler hasn't been executed (by keeping a copy of the shared pointer bound to the handler).

Other solutions could be:

having externally allocated timers (e.g. in a container with reference stability, like a std::list) where you delete them manually when they're no longer needed

running a dedicated io_service on your own thread, so you can join the thread to await the work on the io_service.

Depending on your use cases/load patterns, one approach will be better than the others.

Samples:

using a std::list to manage the lifetime of objects with service objects that participate in async operations (in this case a Session: How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server

using shared_from_this instead: Simple server using Boost.Asio throws an exception

Wrapping a timer for recurring callbacks and using local variables for lifetime management: C++ boost asynchronous timer to run in parallel with program

I picked answers that have some contrasting approaches (some not using Boost Asio) so you can see the trade-offs and what changes between approaches.

Body:
I have a class called Timer that exposes two methods called start and stop.

void Timer::start() {
    _enabled.store(true, std::memory_order::memory_order_release);
    _timer.expires_from_now(_delay);
    _timer.async_wait(
        std::bind(
            &Timer::tick,
            this,
            std::placeholders::_1
        ));
}

void Timer::stop() {
    _enabled.store(false, std::memory_order::memory_order_release);
    _timer.cancel();
}

void Timer::tick(const boost::system::error_code& error) {
    if (error) return;
    if (!_enabled.load(std::memory_order::memory_order_acquire)) return;
    try {
        _task();
    } catch (...) {}
    if (_enabled.load(std::memory_order::memory_order_acquire)) {
        _timer.expires_from_now(_delay);
        _timer.async_wait(
            std::bind(
                &Timer::tick,
                this,
                std::placeholders::_1
            ));
    }
}

Another class that uses an instance of Timer (handler is executed on some other thread in a ThreadPool instance) calls stop in its destructor. From the Boost Documentation, it is now possible that the handler will be invoked and these two functions will be executed concurrently and the handler may try to access freed resources.

SomeOtherClass::~SomeOtherClass() {
    _timer.stop();
    // somehow wait for _timer handler to execute
    // delete[] some_thing;
    // other destructive things
}

Is there anyway to wait for the handler to finish execution? I've been scratching my head all day, I am quite new to Boost, so perhaps I made a design flaw. Any help would be greatly appreciated, thanks.


答:
Try a callback function, I have found this example to help you: Proper way to wait for one function to finish before continuing?

This looks similar to your problem

Title: MOUSEOVER: How to start a function and let it play until the end without start it over and over?


问:
Best way to create Python function with multiple options?
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:

```<code>def func1(a, b, c):
    some_identical_code
    some_similar_code
    more_identical_code
    some_unique_code
    final_similar_code

# similarly for func2, func3...
</code>```

I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:

```<code>def func(a, b, c, setting):
    # setting = '1', '2', etc.

    some identical code

    if setting == '1':
        similar_code_1
    elif setting == '2':
        similar_code_2
    # etc. for other settings options

    more_identical_code

    if setting == '1':
        unique_code_1
        final_similar_code_1
    elif setting == '2':
        unique_code_2
        final_similar_code_2
    # etc. for other settings options
</code>```

How can I do something like this more elegantly? Is there a standard way to do it?

One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:

```<code>def func(a, b, c, setting):
    # setting = '1', '2', etc.
    simdict = {'1': '_1', '2': '_2' ...}

    some identical code
    similar_code(simdict[setting])
    more_identical_code

    if setting == '1':
        unique_code_1
    elif setting == '2':
        unique_code_2
    # etc. for other settings options

    final_similar_code(simdict[setting])
</code>```

This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.

答:
Abstract!

identical code should be a function;

similar code should be a function with a parameter;

unique code should be one function for each;

object oriented code can help here.

To get the idea:

```<code>def identical_code():
    lorem ipsum

def similar_code(parameter):
    lorem ipsum

class Base:
    def __call__(self, a, b, c):
        identical_code()
        similar_code(self.parameter())
        unique_code()
    def unique_code(self):
        NotImplemented
    def parameter(self):
        NotImplemented

class Func_1(Base):
    def unique_code(self):
        do_it_1()
    def parameter(self):
        return 1

class Func_2(Base):
    def unique_code(self):
        do_it_2()
    def parameter(self):
        return 2
</code>```

You can then call Func1()(a, b, c) or Func_2()(a, b, c).

Here the NotImplemented methods are there to show that the base class is just there to define the common behavior, but can't really do anything if you don't specify those two methods.

Some maybe more pythonic way would be to just duck type and remove inheritance:

```<code>def func(a, b, c, setting):
    identical_code()
    similar_code(setting.parameter())
    setting.unique_code()

class Func_1:
    def unique_code(self):
        do_it_1()
    def parameter(self):
        return 1

class Func_2:
    def unique_code(self):
        do_it_2()
    def parameter(self):
        return 2

def func1(a, b, c):
    return func(a, b, c, Func_1)

def func2(a, b, c):
    return func(a, b, c, Func_2)
</code>```

Body:
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:

def func1(a, b, c):
    some_identical_code
    some_similar_code
    more_identical_code
    some_unique_code
    final_similar_code

# similarly for func2, func3...

I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:

def func(a, b, c, setting):
    # setting = '1', '2', etc.

    some identical code

    if setting == '1':
        similar_code_1
    elif setting == '2':
        similar_code_2
    # etc. for other settings options

    more_identical_code

    if setting == '1':
        unique_code_1
        final_similar_code_1
    elif setting == '2':
        unique_code_2
        final_similar_code_2
    # etc. for other settings options

How can I do something like this more elegantly? Is there a standard way to do it?

One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:

def func(a, b, c, setting):
    # setting = '1', '2', etc.
    simdict = {'1': '_1', '2': '_2' ...}

    some identical code
    similar_code(simdict[setting])
    more_identical_code

    if setting == '1':
        unique_code_1
    elif setting == '2':
        unique_code_2
    # etc. for other settings options

    final_similar_code(simdict[setting])

This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.

Body:
Abstract!

identical code should be a function;

similar code should be a function with a parameter;

unique code should be one function for each;

object oriented code can help here.

To get the idea:

def identical_code():
    lorem ipsum

def similar_code(parameter):
    lorem ipsum

class Base:
    def __call__(self, a, b, c):
        identical_code()
        similar_code(self.parameter())
        unique_code()
    def unique_code(self):
        NotImplemented
    def parameter(self):
        NotImplemented

class Func_1(Base):
    def unique_code(self):
        do_it_1()
    def parameter(self):
        return 1

class Func_2(Base):
    def unique_code(self):
        do_it_2()
    def parameter(self):
        return 2

You can then call Func1()(a, b, c) or Func_2()(a, b, c).

Here the NotImplemented methods are there to show that the base class is just there to define the common behavior, but can't really do anything if you don't specify those two methods.

Some maybe more pythonic way would be to just duck type and remove inheritance:

def func(a, b, c, setting):
    identical_code()
    similar_code(setting.parameter())
    setting.unique_code()

class Func_1:
    def unique_code(self):
        do_it_1()
    def parameter(self):
        return 1

class Func_2:
    def unique_code(self):
        do_it_2()
    def parameter(self):
        return 2

def func1(a, b, c):
    return func(a, b, c, Func_1)

def func2(a, b, c):
    return func(a, b, c, Func_2)


问:
How can i align (center) row data in Python PyQt5 QTableView?
I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

Re:I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

```<code>class App(Ui_MainWindow):
    def __init__(self, window):
        self.setupUi(window)
        # code...
        numbers = [["Thomas","17776661122",❌],["Parker","1777666331",❌],["Michael","17775553322",❌]]
        CreateTable()
    def CreateTable(self,fromlist):
        for i in range(0,len(fromlist)):
            self.model.addCustomer(Customer(fromlist[i][0],fromlist[i][1],fromlist[i][2]))
            ### align code
        # code...

</code>```

This is my QtTableView Model.

```<code>class Customer(object):
    def __init__(self,name,number,status):
        self.name = name
        self.number = number
        self.status = status

class CustomerTableModel(QtCore.QAbstractTableModel):

    ROW_BATCH_COUNT = 15

    def __init__(self):
        super(CustomerTableModel,self).__init__()
        self.headers = ['               İsim                     ','  Telefon No (Örn 9053xx..)   ','   Mesaj Durumu   ']
        self.customers  = []
        self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT

    def rowCount(self,index=QtCore.QModelIndex()):
        if not self.customers:
            return 0

        if len(self.customers) <= self.rowsLoaded:
            return len(self.customers)
        else:
            return self.rowsLoaded

    def canFetchMore(self,index=QtCore.QModelIndex()):
        if len(self.customers) > self.rowsLoaded:
            return True
        else:
            return False

    def fetchMore(self,index=QtCore.QModelIndex()):
        reminder = len(self.customers) - self.rowsLoaded
        itemsToFetch = min(reminder,CustomerTableModel.ROW_BATCH_COUNT)
        self.beginInsertRows(QtCore.QModelIndex(),self.rowsLoaded,self.rowsLoaded+itemsToFetch-1)
        self.rowsLoaded += itemsToFetch
        self.endInsertRows()

    def addCustomer(self,customer):
        self.beginResetModel()
        self.customers.append(customer)
        self.endResetModel()

    def columnCount(self,index=QtCore.QModelIndex()):
        return len(self.headers)

    def data(self,index,role=QtCore.Qt.DisplayRole):
        col = index.column()
        customer = self.customers[index.row()]
        if role == QtCore.Qt.DisplayRole:
            if col == 0:
                return QtCore.QVariant(customer.name)
            elif col == 1:
                return QtCore.QVariant(customer.number)
            elif col == 2:
                return QtCore.QVariant(customer.status)
            return QtCore.QVariant()

    def headerData(self,section,orientation,role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            return QtCore.QVariant(self.headers[section])
        return QtCore.QVariant(int(section + 1))
</code>```

P.S. : Sorry for my English :-)

答:
did not get your way to create a table on QTableView, but for each item setting this code works to align ;</p>

```<code>data = QTableWidget(["17776661122"])
table.setItem(x,y,data).setTextAlignment(Qt.AlignHCenter)
</code>```

Body:
I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

Re:I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

class App(Ui_MainWindow):
    def __init__(self, window):
        self.setupUi(window)
        # code...
        numbers = [["Thomas","17776661122",❌],["Parker","1777666331",❌],["Michael","17775553322",❌]]
        CreateTable()
    def CreateTable(self,fromlist):
        for i in range(0,len(fromlist)):
            self.model.addCustomer(Customer(fromlist[i][0],fromlist[i][1],fromlist[i][2]))
            ### align code
        # code...

This is my QtTableView Model.

class Customer(object):
    def __init__(self,name,number,status):
        self.name = name
        self.number = number
        self.status = status

class CustomerTableModel(QtCore.QAbstractTableModel):

    ROW_BATCH_COUNT = 15

    def __init__(self):
        super(CustomerTableModel,self).__init__()
        self.headers = ['               İsim                     ','  Telefon No (Örn 9053xx..)   ','   Mesaj Durumu   ']
        self.customers  = []
        self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT

    def rowCount(self,index=QtCore.QModelIndex()):
        if not self.customers:
            return 0

        if len(self.customers) <= self.rowsLoaded:
            return len(self.customers)
        else:
            return self.rowsLoaded

    def canFetchMore(self,index=QtCore.QModelIndex()):
        if len(self.customers) > self.rowsLoaded:
            return True
        else:
            return False

    def fetchMore(self,index=QtCore.QModelIndex()):
        reminder = len(self.customers) - self.rowsLoaded
        itemsToFetch = min(reminder,CustomerTableModel.ROW_BATCH_COUNT)
        self.beginInsertRows(QtCore.QModelIndex(),self.rowsLoaded,self.rowsLoaded+itemsToFetch-1)
        self.rowsLoaded += itemsToFetch
        self.endInsertRows()

    def addCustomer(self,customer):
        self.beginResetModel()
        self.customers.append(customer)
        self.endResetModel()

    def columnCount(self,index=QtCore.QModelIndex()):
        return len(self.headers)

    def data(self,index,role=QtCore.Qt.DisplayRole):
        col = index.column()
        customer = self.customers[index.row()]
        if role == QtCore.Qt.DisplayRole:
            if col == 0:
                return QtCore.QVariant(customer.name)
            elif col == 1:
                return QtCore.QVariant(customer.number)
            elif col == 2:
                return QtCore.QVariant(customer.status)
            return QtCore.QVariant()

    def headerData(self,section,orientation,role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            return QtCore.QVariant(self.headers[section])
        return QtCore.QVariant(int(section + 1))

P.S. : Sorry for my English :-)

Body:
did not get your way to create a table on QTableView, but for each item setting this code works to align ;

data = QTableWidget(["17776661122"])
table.setItem(x,y,data).setTextAlignment(Qt.AlignHCenter)


问:
checkboxes in php - problem with access
i need to reproduce with the code below something like:

```<code>myformdata[languages1]
myformdata[languages2]
myformdata[languages3]
</code>```

But with this code only reproduce myformdata[languages

```<code>    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
    }
    ?>
</code>```

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

答:
```<code><?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages".$i++."]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
    }
    ?>
</code>```

Try this.

Title: checkboxes in php - problem with access

Body:
i need to reproduce with the code below something like:

myformdata[languages1]
myformdata[languages2]
myformdata[languages3]

But with this code only reproduce myformdata[languages

    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data  \n");
    }
    ?>

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

Body:
<?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages".$i++."]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
    }
    ?>

Try this.


问:
What does ( [ ]( ){ output;}); mean?
Currently using the ESP8266ServerSecure.h library , HelloServerBearSSL example.

What does this mean? Is the output server.send being initialize as an array? I'm really confused.

```<code>server.on("/inline", [](){ server.send(200, "text/plain" , "this works as well"); } );
</code>```

答:
This is a lambda: https://en.cppreference.com/w/cpp/language/lambda

Equivalent of:

```<code>struct Callback
{
  void operator()() {
    server.send(200, "text/plain" , "this works as well");
  }
};

server.on("/inline", Callback{});
</code>```

Title: What does ( [ ]( ){ output;}); mean?

Body:
Currently using the ESP8266ServerSecure.h library , HelloServerBearSSL example.

What does this mean? Is the output server.send being initialize as an array? I'm really confused.

server.on("/inline", [](){ server.send(200, "text/plain" , "this works as well"); } );

Body:
This is a lambda: https://en.cppreference.com/w/cpp/language/lambda

Equivalent of:

struct Callback
{
  void operator()() {
    server.send(200, "text/plain" , "this works as well");
  }
};

server.on("/inline", Callback{});


问:
How to make my react app run permanently in ec2?
I made a portfolio website with create react app and I opened an ec2 instance to run my website, when I'm using the ssh command "sudo npm start" afterward the site is running, but when I close down the ssh my website is not online anymore, How can I make my site run indefinitely? </p>

答:
You want to run this as a background service using systemd.

Try taking a look at: https://medium.com/@benmorel/creating-a-linux-service-with-systemd-611b5c8b91d6.


问:
Is there away to start a phones native Navigation tool from Flex 4.5?
I am building a mobile application in Flex 4.5 and from this app I would like to start the device's native navigation tool, like Google Navigation for example.

Is there a way to open the Navigation App using Flex 4.5?

答: You can try using StageWebView to open up google maps or something.  I don't think there's a way to open the native navigation app because it might not be there and they're different for each device.</p>


问:
java spingboot microservice deployment on aks throws UnsupportedClassVersionError
While trying to deploy java springboot microservice on aks continuously gives me UnsupportedClassVersionError. I am using "kubectl apply -f file.yaml" command to apply the deployment. Even after compiling to correct compiler version now, it still complains the same. Not sure where I am missing.

First Attempt

 - compiled with oracle openjdk 11

 - checked compiled class version using javap -verbose MyApplication | findstr "major"
  console output - major version: 55

 - Deployment to aks failed

Second Attempt

 - compiled with oracle jdk 1.8

 - checked compiled class version using ' javap -verbose MyApplication | findstr "major" '
  console output - major version: 52

 - Deployment to aks fails

Common to both deployment

 - Used command "kubectl apply -f myapp.yaml" to deploy on aks cluster

 - Receiving same error, which is,

```<code>> Exception in thread "main" java.lang.UnsupportedClassVersionError:
> MyApplication has been compiled by a more recent version of the Java
> Runtime (class file version 55.0), this version of the Java Runtime
> only recognizes class file versions up to 52.0
>         at java.lang.ClassLoader.defineClass1(Native Method)
>         at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
>         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
>         at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
>         at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
>         at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
>         at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
>         at java.security.AccessController.doPrivileged(Native Method)
>         at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
>         at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:92)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
>         at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
>         at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
>         at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
>         at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
</code>```

 Request kind help

Regards

答:
Default pull policy is set to IfNotPresent which tells Kubelet to skip pulling an image if it already exists on a node where pod is being scheduled.
If you want to force image to always be pulled you could do following:

set the  imagePullPolicy  of the container to  Always.

omit the  imagePullPolicy  and use  :latest  as the tag for the image to use.

omit the  imagePullPolicy  and the tag for the image to use.

enable the  AlwaysPullImages  admission controller.

Note that you should avoid using  :latest  tag, see  Best Practices for Configuration  for more information.

Body:
While trying to deploy java springboot microservice on aks continuously gives me UnsupportedClassVersionError. I am using "kubectl apply -f file.yaml" command to apply the deployment. Even after compiling to correct compiler version now, it still complains the same. Not sure where I am missing.

First Attempt

 - compiled with oracle openjdk 11

 - checked compiled class version using javap -verbose MyApplication | findstr "major"
  console output - major version: 55

 - Deployment to aks failed

Second Attempt

 - compiled with oracle jdk 1.8

 - checked compiled class version using ' javap -verbose MyApplication | findstr "major" '
  console output - major version: 52

 - Deployment to aks fails

Common to both deployment

 - Used command "kubectl apply -f myapp.yaml" to deploy on aks cluster

 - Receiving same error, which is,

> Exception in thread "main" java.lang.UnsupportedClassVersionError:
> MyApplication has been compiled by a more recent version of the Java
> Runtime (class file version 55.0), this version of the Java Runtime
> only recognizes class file versions up to 52.0
>         at java.lang.ClassLoader.defineClass1(Native Method)
>         at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
>         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
>         at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
>         at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
>         at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
>         at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
>         at java.security.AccessController.doPrivileged(Native Method)
>         at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
>         at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:92)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
>         at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
>         at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
>         at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
>         at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)

 Request kind help

Regards


问:
installing pyimagesearch on python3
I am working with python3 and Ubuntu 18.04 and trying to install a python package named "pyimagesearch". it is not possible to install using pip command or apt-get install. I Googled to see how to install it but all the hits showed this link:

https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv/

I followed all the steps without any error. to test that as mentioned in this link, I did :

```<code>import cv2
</code>```

and it worked. then I tried:

```<code>import pyimagesearch
</code>```

but still I am getting this error:

```<code>>>> import pyimagesearch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pyimagesearch'
</code>```

Do you know how to install this package?

答:
"pyimagesearch" is not any package that you can import. It's a folder in the source code (you need to download the source code from pyimageseach's tutorial page). That folder has a file.py which contains a well-defined class of your interest.

from pyimageseach.file import class

"import pyimagesearch" won't work.

Importing class from another file

Title: installing pyimagesearch on python3

Body:
I am working with python3 and Ubuntu 18.04 and trying to install a python package named "pyimagesearch". it is not possible to install using pip command or apt-get install. I Googled to see how to install it but all the hits showed this link:

https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv/

I followed all the steps without any error. to test that as mentioned in this link, I did :

import cv2

and it worked. then I tried:

import pyimagesearch

but still I am getting this error:

>>> import pyimagesearch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pyimagesearch'

Do you know how to install this package?


问:
Global function code does not work in Python
This is the code on the book I`m reading:

```<code>>>> var=99
>>> def funct1():
    global var
    var+=1

>>> var
100
</code>```

but when I try to run this code on my pc this happens:

```<code>>>> var=99
>>> def funct1():
    global var
    var+=1

>>> var
99
</code>```

Does anyone know why this happens? My book is about Python 3.3 and after and I`m using Python version 3.8.3 so it should be ok...

答:
I am not sure about the context of the book. But you should first call the function for var to change.

Like this:

```<code>var=99
>>> def funct1():
    global var
    var+=1

>>> funct1()
>>> var
100
</code>```

Body:
This is the code on the book I`m reading:

>>> var=99
>>> def funct1():
    global var
    var+=1

>>> var
100

but when I try to run this code on my pc this happens:

>>> var=99
>>> def funct1():
    global var
    var+=1

>>> var
99

Does anyone know why this happens? My book is about Python 3.3 and after and I`m using Python version 3.8.3 so it should be ok...

Body:
I am not sure about the context of the book. But you should first call the function for var to change.

Like this:

var=99
>>> def funct1():
    global var
    var+=1

>>> funct1()
>>> var
100


问:
AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context
I want to create a many-to-many relationship where one person can be in many clubs and one club can have many persons. I added the models.py and serializers.py for the following logic but when I try to serialize it in the command prompt, I get the following error - What am I doing wrong here? I don't even have a HyperlinkedIdentityField

```<code>Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 503, in data
ret = super(Serializer, self).data
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 472, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\user\corr\lib\site-packages\rest_framework\relations.py", line 320, in to_representation"the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
</code>```

models.py

```<code>class Club(models.Model):
    club_name = models.CharField(default='',blank=False,max_length=100)

class Person(models.Model):
    person_name = models.CharField(default='',blank=False,max_length=200)
    clubs = models.ManyToManyField(Club)
</code>```

serializers.py

```<code>class ClubSerializer(serializers.ModelSerializer):
    class Meta:
        model = Club
        fields = ('url','id','club_name','person')

class PersonSerializer(serializers.ModelSerializer):
    clubs = ClubSerializer()
    class Meta:
        model = Person
        fields = ('url','id','person_name','clubs')
</code>```

views.py

```<code>class ClubDetail(generics.ListCreateAPIView):
serializer_class = ClubSerializer

def get_queryset(self):
     club = Clubs.objects.get(pk=self.kwargs.get('pk',None))
     persons = Person.objects.filter(club=club)
     return persons

class ClubList(generics.ListCreateAPIView):
    queryset = Club.objects.all()
    serializer_class = ClubSerializer

class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = PersonSerializer

def get_object(self):
    person_id = self.kwargs.get('pk',None)
    return Person.objects.get(pk=person_id)
</code>```

Inspecting the created serializer gives me this -

```<code>PersonSerializer(<Person: fd>):
url = HyperlinkedIdentityField(view_name='person-detail')
id = IntegerField(label='ID', read_only=True)
person_name = CharField(max_length=200, required=False)
clubs = ClubSerializer():
    url = HyperlinkedIdentityField(view_name='club-detail')
    id = IntegerField(label='ID', read_only=True)
    club_name = CharField(max_length=100, required=False)
</code>```

but serializer.data gives me the error

Edit

I realized the error could be because of url patterns, so I added the following url patterns but I still get the error -

```<code>urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^clubs/$',
    views.ClubList.as_view(),
    name='club-list'),
 url(r'^clubs/(?P<pk>[0-9]+)/persons/$',
    views.ClubDetail.as_view(),
    name='club-detail'),
url(r'^person/(?P<pk>[0-9]+)/$',
    views.PersonDetail.as_view(),
    name='person-detail'),
])
</code>```

答:
You may simply solve it by  changing the instantiation (in views.py) to thing like this:</p>

```<code>your_serializer = YourModelSerializer(YourQuerySet_or_object, many=True,context={'request':request})
</code>```

Body:
I want to create a many-to-many relationship where one person can be in many clubs and one club can have many persons. I added the models.py and serializers.py for the following logic but when I try to serialize it in the command prompt, I get the following error - What am I doing wrong here? I don't even have a HyperlinkedIdentityField

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 503, in data
ret = super(Serializer, self).data
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 472, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\user\corr\lib\site-packages\rest_framework\relations.py", line 320, in to_representation"the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.

models.py

class Club(models.Model):
    club_name = models.CharField(default='',blank=False,max_length=100)

class Person(models.Model):
    person_name = models.CharField(default='',blank=False,max_length=200)
    clubs = models.ManyToManyField(Club)

serializers.py

class ClubSerializer(serializers.ModelSerializer):
    class Meta:
        model = Club
        fields = ('url','id','club_name','person')

class PersonSerializer(serializers.ModelSerializer):
    clubs = ClubSerializer()
    class Meta:
        model = Person
        fields = ('url','id','person_name','clubs')

views.py

class ClubDetail(generics.ListCreateAPIView):
serializer_class = ClubSerializer

def get_queryset(self):
     club = Clubs.objects.get(pk=self.kwargs.get('pk',None))
     persons = Person.objects.filter(club=club)
     return persons

class ClubList(generics.ListCreateAPIView):
    queryset = Club.objects.all()
    serializer_class = ClubSerializer

class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = PersonSerializer

def get_object(self):
    person_id = self.kwargs.get('pk',None)
    return Person.objects.get(pk=person_id)

Inspecting the created serializer gives me this -

PersonSerializer(<Person: fd>):
url = HyperlinkedIdentityField(view_name='person-detail')
id = IntegerField(label='ID', read_only=True)
person_name = CharField(max_length=200, required=False)
clubs = ClubSerializer():
    url = HyperlinkedIdentityField(view_name='club-detail')
    id = IntegerField(label='ID', read_only=True)
    club_name = CharField(max_length=100, required=False)

but serializer.data gives me the error

Edit

I realized the error could be because of url patterns, so I added the following url patterns but I still get the error -

urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^clubs/$',
    views.ClubList.as_view(),
    name='club-list'),
 url(r'^clubs/(?P<pk>[0-9]+)/persons/$',
    views.ClubDetail.as_view(),
    name='club-detail'),
url(r'^person/(?P<pk>[0-9]+)/$',
    views.PersonDetail.as_view(),
    name='person-detail'),
])

Body:
You may simply solve it by  changing the instantiation (in views.py) to thing like this:

your_serializer = YourModelSerializer(YourQuerySet_or_object, many=True,context={'request':request})


问:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

```<code>function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}
</code>```

答:
```<code>function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}
</code>```

it will also check white spaces ('    ') along with following:

null ,undefined ,NaN ,empty ,string ("") ,0 ,false

Body:
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

Body:
function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

it will also check white spaces ('    ') along with following:

null ,undefined ,NaN ,empty ,string ("") ,0 ,false


问:
Material UI Multiple Select | How to use Multiple Select with arrays
I'm using material-ui multiple select and I've created an example based on the documentation provided from Multiple Select.

My example here: codesandbox

In my example, I want to use 2 arrays for multiple select dropdowns, 1 for each. I tried to achieve this by updating the handleChange event from:

```<code>const handleChange = (event) => {
    setState(event.target.value);
  };
</code>```

to:

```<code>const handleChange = event => {
    setState({ ...state, [event.target.name]: event.target.value });
  };
</code>```

When I test this update, I click on any name from the drop-down and I get this error: state.indexOf is not a function

I want to be able to use the handleChange event to work for all of the multiple select drop-downs for my example. Any help or suggestions are much appreciated.

答:
In your codesandbox, you have used only one array as state which should be changed to two

```<code>  const [state, setState] = React.useState({ first: [], second: [] });
</code>```

For each select we have to give the name

```<code><Select
      labelId="demo-mutiple-checkbox-label"
      id="demo-mutiple-checkbox"
      multiple
      value={state.first}
      name="first"
      onChange={handleChange}
      input={<Input />}
      renderValue={selected => selected.join(", ")}
    >
</code>```

this is the working csb link https://codesandbox.io/s/material-demo-s1g4h?file=/demo.js:1322-1618

Body:
I'm using material-ui multiple select and I've created an example based on the documentation provided from Multiple Select.

My example here: codesandbox

In my example, I want to use 2 arrays for multiple select dropdowns, 1 for each. I tried to achieve this by updating the handleChange event from:

const handleChange = (event) => {
    setState(event.target.value);
  };

to:

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

When I test this update, I click on any name from the drop-down and I get this error: state.indexOf is not a function

I want to be able to use the handleChange event to work for all of the multiple select drop-downs for my example. Any help or suggestions are much appreciated.

Body:
In your codesandbox, you have used only one array as state which should be changed to two

  const [state, setState] = React.useState({ first: [], second: [] });

For each select we have to give the name

<Select
      labelId="demo-mutiple-checkbox-label"
      id="demo-mutiple-checkbox"
      multiple
      value={state.first}
      name="first"
      onChange={handleChange}
      input={<Input />}
      renderValue={selected => selected.join(", ")}
    >

this is the working csb link https://codesandbox.io/s/material-demo-s1g4h?file=/demo.js:1322-1618


问:
SharedArrayBuffer and SharedWorker
In the features of ECMAScript 2017 there is Shared memory and atomics.
I try test it in Google Chrome 59.0.3071.109 (Experimental SharedArrayBuffer flag is enabled).
When I try post SharedArrayBuffer in simple Worker it's works. But when I try post SharedArrayBuffer in SharedWorker, in event parament of onmessage event handler I get event.data is null. Why is this so? Here is an example of my code:

index.html:

```<code><!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Web Workers</title>
    <script src="main.js"></script>
</head>

<body>

<button onclick="post()">Post</button>
<button onclick="get()">Get</button>

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

main.js:

```<code>var worker = new SharedWorker('worker.js');
var buffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
new Int32Array(buffer)[0] = 12;

function post() {
    worker.port.postMessage({buffer});
}

function get() {
    console.log(new Int32Array(buffer)[0]);
}
</code>```

worker.js:

```<code>self.onconnect = function (e) {
    var [port] = e.ports;

    port.onmessage = function (e) {
        console.log(e.data);// null
    };
};
</code>```

Thank you.

答:
According Chromium Blink Workers Documention: Shared Worker is Out-of-process.

It run on another system process different to document process(which contain JS mainthread).

Operation System process deny memory access from other process.

SharedArraybuffer work by share(access) memory. So SharedArraybuffer create(access) by JS mainthread(document process) can't access by Shared Worker(Out-of-process).

Title: SharedArrayBuffer and SharedWorker

Body:
In the features of ECMAScript 2017 there is Shared memory and atomics.
I try test it in Google Chrome 59.0.3071.109 (Experimental SharedArrayBuffer flag is enabled).
When I try post SharedArrayBuffer in simple Worker it's works. But when I try post SharedArrayBuffer in SharedWorker, in event parament of onmessage event handler I get event.data is null. Why is this so? Here is an example of my code:

index.html:

<!doctype html>

    <meta charset="utf-8">
    <title>Web Workers</title>

<button onclick="post()">Post</button>
<button onclick="get()">Get</button>

main.js:

var worker = new SharedWorker('worker.js');
var buffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
new Int32Array(buffer)[0] = 12;

function post() {
    worker.port.postMessage({buffer});
}

function get() {
    console.log(new Int32Array(buffer)[0]);
}

worker.js:

self.onconnect = function (e) {
    var [port] = e.ports;

    port.onmessage = function (e) {
        console.log(e.data);// null
    };
};

Thank you.


问:
How to deploy NextJS application to Linux Server (CentOS 7) - VPS
I've got a question regarding building applications. I'm using simple VPS with node.js support. Now I do not know how to build my next.js application to production.

I want to deploy my application as static files.

I thought that I should use next build && next export then copy out dir to the server but during this process, I faced some issues - when I change route - everything is okay, but if I refresh the page - the page is not found because the server is looking for this file in directories. So how can I deploy my nextjs application in production mode with VPS server and static files?

I tried one thing which is not working fine probably or I did something wrong.
I added nodejs express server with

```<code>const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';

const app = next({dev});
const router = express.Router();
const handle = app.getRequestHandler();

app.prepare()
    .then(() => {

        const server = express();

        server.get('*', (req, res) => {
            return handle(req, res);
        });

        server.listen(3000, (err) => {
            if (err) throw err;
            console.log('> Ready on http://localhost:3000');
        });
    });

</code>```

and start server with forever library NODE_ENV=production node server.js and it's working fine, but seems this is working in a wrong way - seems it's normal server like in dev mode - so it shouldn't be like that. (I see thunder icon on the right-bottom corner and I see all files which are same as in dev mode).

I want to deploy everything as static files.

Thank you for your help!

答:
After you build and export you need to serve those files somehow. The reason the Express server works is because you are starting a HTTP server to serve the files.

So you need to serve those files either by using a static hosting provider (i.e. Vercel or Amazon S3). Otherwise you should start a server on your linux machine using something like serve to serve it at a port, similar to your Express server serving it as localhost:3000 which is then exposed on your VPS.

Body:
I've got a question regarding building applications. I'm using simple VPS with node.js support. Now I do not know how to build my next.js application to production.

I want to deploy my application as static files.

I thought that I should use next build && next export then copy out dir to the server but during this process, I faced some issues - when I change route - everything is okay, but if I refresh the page - the page is not found because the server is looking for this file in directories. So how can I deploy my nextjs application in production mode with VPS server and static files?

I tried one thing which is not working fine probably or I did something wrong.
I added nodejs express server with

const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';

const app = next({dev});
const router = express.Router();
const handle = app.getRequestHandler();

app.prepare()
    .then(() => {

        const server = express();

        server.get('*', (req, res) => {
            return handle(req, res);
        });

        server.listen(3000, (err) => {
            if (err) throw err;
            console.log('> Ready on http://localhost:3000');
        });
    });

and start server with forever library NODE_ENV=production node server.js and it's working fine, but seems this is working in a wrong way - seems it's normal server like in dev mode - so it shouldn't be like that. (I see thunder icon on the right-bottom corner and I see all files which are same as in dev mode).

I want to deploy everything as static files.

Thank you for your help!


答:
It looks like your output string may be incorrect. Try this one:

```<code>echo nl2br ("<input type='checkbox' name='myformdata[languages".$i++."]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
</code>```

I replaced the two instance of single quotes before and after the increment output with double quotes.

Also note, there is no need to increment in PHP. All you need to add is two empty brackets [] and PHP will take care of the incrementing itself. So if you'd like to access the input with $_POST["languages"][1] you can do so by generating the following: name='languages[]'.

Title: checkboxes in php - problem with access

Body:
It looks like your output string may be incorrect. Try this one:

echo nl2br ("<input type='checkbox' name='myformdata[languages".$i++."]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");

I replaced the two instance of single quotes before and after the increment output with double quotes.

Also note, there is no need to increment in PHP. All you need to add is two empty brackets [] and PHP will take care of the incrementing itself. So if you'd like to access the input with $_POST["languages"][1] you can do so by generating the following: name='languages[]'.


问:
How can I remove a buggy service worker, or implement a "kill switch"?
I'm playing with the service worker API in my computer so I can grasp how can I benefit from it in my real world apps.

I came across a weird situation where I registered a service worker which intercepts fetch event so it can check its cache for requested content before sending a request to the origin.
The problem is that this code has an error which prevented the function from making the request, so my page is left blank; nothing happens.
As the service worker has been registered, the second time I load the page it intercepts the very first request (the one which loads the HTML). Because I have this bug, that fetch event fails, it never requests the HTML and all I see its a blank page.

In this situation, the only way I know to remove the bad service worker script is through chrome://serviceworker-internals/ console.
If this error gets to a live website, which is the best way to solve it?

Thanks!

答:
We had moved a site from godaddy.com to a regular WordPress install. Client (not us) had a serviceworker file (sw.js) cached into all their browsers which completely messed things up. Our site, a normal WordPress site, has no service workers.

It's like a virus, in that it's on every page, it does not come from our server and there is no way to get rid of it easily.

We made a new empty file called sw.js on the root of the server, then added the following to every page on the site.

```<code><script>
if (navigator && navigator.serviceWorker && navigator.serviceWorker.getRegistration) {

    navigator.serviceWorker.getRegistration('/').then(function(registration) {
        if (registration) {
              registration.update();
              registration.unregister();
        }
});

}
</script>
</code>```

Body:
We had moved a site from godaddy.com to a regular WordPress install. Client (not us) had a serviceworker file (sw.js) cached into all their browsers which completely messed things up. Our site, a normal WordPress site, has no service workers.

It's like a virus, in that it's on every page, it does not come from our server and there is no way to get rid of it easily.

We made a new empty file called sw.js on the root of the server, then added the following to every page on the site.

<script>
if (navigator && navigator.serviceWorker && navigator.serviceWorker.getRegistration) {

    navigator.serviceWorker.getRegistration('/').then(function(registration) {
        if (registration) {
              registration.update();
              registration.unregister();
        }
});

}
</script>


问:
How to prevent mutation of private structures returned by reference
I have following code:

```<code>struct MyStruct {
    int a;
    int b;
};

class Foo {
public:
    MyStruct const &getValue() {
        return value;
    }

private:
    MyStruct value{10, 20};
};

int main() {
    Foo foo{};
    auto v = foo.getValue();
    v.a = 42; // compiles! it shouldn't!
}
</code>```

I want to return a reference to private member, but don't allow caller to mutate contents of this reference. Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to. Though, declaring return type as MyStruct& const fails with "'const' qualifier may not be applied to a reference". I believe I might be missing something here.

I could have solved that with declaring MyStruct with all const fields, but I want to mutate it myself inside my class — only disallow caller to do so.

How is it possible to do so?

答:
Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to.

That's wrong. References can't ever be reassigned anyway. This is the correct way to return a reference to an immutable object. However you actually copy the returned object:

```<code>auto v = foo.getValue();
</code>```

and then modify the copy, which is a valid operation. You can declare v as reference

```<code>auto &v = foo.getValue();
</code>```

to get the expected compiler error. Demo

Body:
I have following code:

struct MyStruct {
    int a;
    int b;
};

class Foo {
public:
    MyStruct const &getValue() {
        return value;
    }

private:
    MyStruct value{10, 20};
};

int main() {
    Foo foo{};
    auto v = foo.getValue();
    v.a = 42; // compiles! it shouldn't!
}

I want to return a reference to private member, but don't allow caller to mutate contents of this reference. Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to. Though, declaring return type as MyStruct& const fails with "'const' qualifier may not be applied to a reference". I believe I might be missing something here.

I could have solved that with declaring MyStruct with all const fields, but I want to mutate it myself inside my class — only disallow caller to do so.

How is it possible to do so?

Body:
Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to.

That's wrong. References can't ever be reassigned anyway. This is the correct way to return a reference to an immutable object. However you actually copy the returned object:

auto v = foo.getValue();

and then modify the copy, which is a valid operation. You can declare v as reference

auto &v = foo.getValue();

to get the expected compiler error. Demo