问:
OperationalError, no such column. Django
I am going through the Django REST framework tutorial found at http://www.django-rest-framework.org/
I am almost finished with it and just added authentication. Now I am getting :

```<code>OperationalError at /snippets/
no such column: snippets_snippet.owner_id
Request Method: GET
Request URL:    http://localhost:8000/snippets/
Django Version: 1.7
Exception Type: OperationalError
Exception Value:
no such column: snippets_snippet.owner_id
Exception Location: /Users/taylorallred/Desktop/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 485
Python Executable:  /Users/taylorallred/Desktop/env/bin/python
Python Version: 2.7.5
Python Path:
['/Users/taylorallred/Desktop/tutorial',
 '/Users/taylorallred/Desktop/env/lib/python27.zip',
 '/Users/taylorallred/Desktop/env/lib/python2.7',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-darwin',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/taylorallred/Desktop/env/Extras/lib/python',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-tk',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-old',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/taylorallred/Desktop/env/lib/python2.7/site-packages']
Server time:    Sat, 11 Oct 2014 07:02:34 +0000
</code>```

I have looked in several places on the web, not just StackOverflow for the solution, it seems like in general that the problem is with my database and need to delete it then remake it, I have done this several times, the tutorial even has me delete the database and remake it at the point.
Here is my models.py:

```<code>from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())

class Snippet(models.Model):
    owner = models.ForeignKey('auth.User', related_name='snippets')
    highlighted = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                            default='python',
                                            max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                                     default='friendly',
                                     max_length=100)
    class Meta:
        ordering = ('created',)
def save(self, *args, **kwargs):
    """
    Use the 'pygments' library to create a highlighted HTML
    representation of the code snippet.
    """
    lexer = get_lexer_by_name(self.language)
    linenos = self.linenos and 'table' or False
    options = self.title and {'title': self.title} or {}
    formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                      full=true, **options)
    self.highlighted = highlight(self.code, lexer, formatter)
    super(Snippet, self).save(*args, **kwargs)
</code>```

My serializers.py:

```<code>from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User

class SnippetSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username')
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')
</code>```

My views.py:

```<code>from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from snippets.serializers import UserSerializer
from rest_framework import permissions

class SnippetList(generics.ListCreateAPIView):
    """
    List all snippets, or create a new snippet.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def pre_save(self, obj):
        obj.owner = self.request.user
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    Retrieve, update or delete a nippet instance.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def pre_save(self, obj):
        obj.owner = self.request.user
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
</code>```

And finally my urls.py

```<code>from django.conf.urls import include
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = patterns('',
    url(r'^snippets/$', views.SnippetList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
    url(r'^users/$', views.UserList.as_view()),
    url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
)

urlpatterns = format_suffix_patterns(urlpatterns)

urlpatterns += patterns('',
    url(r'^api-auth/', include('rest_framework.urls',
                                       namespace='rest_framework')),
)
</code>```

DB Schema:

```<code>CREATE TABLE "snippets_snippet" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"created" datetime NOT NULL, "title" varchar(100) NOT NULL, "code" text NOT NULL,
"linenos" bool NOT NULL, "language" varchar(100) NOT NULL, "style" varchar(100) NOT NULL);
</code>```

After doing some digging I found that when deleting and recreating the DB (as the tutorial says to) instead of using the make migrations command it would not only NOT add the columns but it would also not tell me something was wrong when running the make migrations command it tells me:

```<code>You are trying to add a non-nullable field 'highlighted' to snippet without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
</code>```

If I comment out the highlighted section in models.py it will post the same message above but for the owner line. So it wants a default for both highlighted and owner, but I am not sure what to use as it. As well as the tutorial isn't helping me either on it.

答:
Step 1: Delete the db.sqlite3 file.

Step 2 : $ python manage.py migrate

Step 3 : $ python manage.py makemigrations

Step 4:  Create the super user using $ python manage.py createsuperuser

new db.sqlite3 will generates automatically

Body:
I am going through the Django REST framework tutorial found at http://www.django-rest-framework.org/
I am almost finished with it and just added authentication. Now I am getting :

OperationalError at /snippets/
no such column: snippets_snippet.owner_id
Request Method: GET
Request URL:    http://localhost:8000/snippets/
Django Version: 1.7
Exception Type: OperationalError
Exception Value:
no such column: snippets_snippet.owner_id
Exception Location: /Users/taylorallred/Desktop/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 485
Python Executable:  /Users/taylorallred/Desktop/env/bin/python
Python Version: 2.7.5
Python Path:
['/Users/taylorallred/Desktop/tutorial',
 '/Users/taylorallred/Desktop/env/lib/python27.zip',
 '/Users/taylorallred/Desktop/env/lib/python2.7',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-darwin',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/taylorallred/Desktop/env/Extras/lib/python',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-tk',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-old',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/taylorallred/Desktop/env/lib/python2.7/site-packages']
Server time:    Sat, 11 Oct 2014 07:02:34 +0000

I have looked in several places on the web, not just StackOverflow for the solution, it seems like in general that the problem is with my database and need to delete it then remake it, I have done this several times, the tutorial even has me delete the database and remake it at the point.
Here is my models.py:

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())

class Snippet(models.Model):
    owner = models.ForeignKey('auth.User', related_name='snippets')
    highlighted = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                            default='python',
                                            max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                                     default='friendly',
                                     max_length=100)
    class Meta:
        ordering = ('created',)
def save(self, *args, **kwargs):
    """
    Use the 'pygments' library to create a highlighted HTML
    representation of the code snippet.
    """
    lexer = get_lexer_by_name(self.language)
    linenos = self.linenos and 'table' or False
    options = self.title and {'title': self.title} or {}
    formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                      full=true, **options)
    self.highlighted = highlight(self.code, lexer, formatter)
    super(Snippet, self).save(*args, **kwargs)

My serializers.py:

from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User

class SnippetSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username')
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')

My views.py:

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from snippets.serializers import UserSerializer
from rest_framework import permissions

class SnippetList(generics.ListCreateAPIView):
    """
    List all snippets, or create a new snippet.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def pre_save(self, obj):
        obj.owner = self.request.user
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    Retrieve, update or delete a nippet instance.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def pre_save(self, obj):
        obj.owner = self.request.user
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

And finally my urls.py

from django.conf.urls import include
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = patterns('',
    url(r'^snippets/$', views.SnippetList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
    url(r'^users/$', views.UserList.as_view()),
    url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
)

urlpatterns = format_suffix_patterns(urlpatterns)

urlpatterns += patterns('',
    url(r'^api-auth/', include('rest_framework.urls',
                                       namespace='rest_framework')),
)

DB Schema:

CREATE TABLE "snippets_snippet" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"created" datetime NOT NULL, "title" varchar(100) NOT NULL, "code" text NOT NULL,
"linenos" bool NOT NULL, "language" varchar(100) NOT NULL, "style" varchar(100) NOT NULL);

After doing some digging I found that when deleting and recreating the DB (as the tutorial says to) instead of using the make migrations command it would not only NOT add the columns but it would also not tell me something was wrong when running the make migrations command it tells me:

You are trying to add a non-nullable field 'highlighted' to snippet without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py

If I comment out the highlighted section in models.py it will post the same message above but for the owner line. So it wants a default for both highlighted and owner, but I am not sure what to use as it. As well as the tutorial isn't helping me either on it.


来源: stackexchange

问:
java.util.NoSuchElementException: No value present ; Apache cassandra - spring boot
I'm using the below dependency

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
</code>```

I need to query on users table which is present in myks keyspace

From my controller part I'm calling the service

```<code>userService.authenticateUser(username, password);
</code>```

And in the service method I have a call to repository

```<code>logger.info("Here : " + username);
boolean userExists = userRepository.existsById(username);
logger.info("userExists : " + userExists);
if (userExists) {
    User user = userRepository.findByusername(username).get();
    return user;
}
return null;
</code>```

and the below is my repository

```<code>@Repository
public interface UserRepository extends CrudRepository<User, String> {
    Optional<User> findByusername(final String username);
}
</code>```

Suppose in the table I don't have an entry with the user kri_test and user sends an input with the username kri_test then I'm facing the exception java.util.NoSuchElementException: No value present

Even it is not printing the log statements present in service class

答:
It has nothing to do with Cassandra configuration etc. You are getting Optional.empty() from userRepository.findByusername(username). And you call get() method on that without calling isPresent() first.

You can fix your problem with this one liner;

```<code>return userRepository.findByusername(username).orElse(null);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using the below dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>

I need to query on users table which is present in myks keyspace

From my controller part I'm calling the service

userService.authenticateUser(username, password);

And in the service method I have a call to repository

logger.info("Here : " + username);
boolean userExists = userRepository.existsById(username);
logger.info("userExists : " + userExists);
if (userExists) {
    User user = userRepository.findByusername(username).get();
    return user;
}
return null;

and the below is my repository

@Repository
public interface UserRepository extends CrudRepository<User, String> {
    Optional<User> findByusername(final String username);
}

Suppose in the table I don't have an entry with the user kri_test and user sends an input with the username kri_test then I'm facing the exception java.util.NoSuchElementException: No value present

Even it is not printing the log statements present in service class

Body:
It has nothing to do with Cassandra configuration etc. You are getting Optional.empty() from userRepository.findByusername(username). And you call get() method on that without calling isPresent() first.

You can fix your problem with this one liner;

return userRepository.findByusername(username).orElse(null);


问:
check if query exists using peewee
I am using the Peewee library in Python and I want to check if a query exists. I do not want to create a record if it doesn't exist, so I don't want to use get_or_create. There must be a better solution than to use try/except with get but I don't see anything. Please let me know if there is a better way. Thanks. </p>

答:
If you just need to check existence use the accepted answer.

If you are going to use the record if it exists you can make use of Model.get_or_none() as this removes the need to use a try/catch and will not create a record if the record doesn't exist.

class User(peewee.Model):
    username = peewee.CharField(unique=True)

user = User.get_or_none(username='charlie')
if user is not None:
    # found user, do something with it
    pass
```

ContentLicense: CC BY-SA 3.0

Title: check if query exists using peewee


问:
find row that has the most matching values compared to other row in my data
I have a dataset that looks like this:

```<code>Person A, Value 1, Value 2, Value 3, Value 4
Person B, Value 1, Value 2, Value 3, Value 4
</code>```

Now I would like to compare single rows of this dataset against the whole set with the criteria to show the row that has the most matching Values compared to the single row Im looking at.

For example. I have a new entry Person C. I want to be able to show (in an analysis tab) the other people that have the most common values with that person from the dataset.

答:
I don't know how is your data stored, but I made up a sample emulating what you said about how your data looks like. I hope you can adapt this to your needs.

I made this:

Left dataset would be your data with values, and right dataset would be your analysis. The formula I used to get this is:

```<code>=IF(J$1=$I2;"x";COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($B:$B;MATCH($I2;$A:$A;0)))+COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($C:$C;MATCH($I2;$A:$A;0)))+COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($D:$D;MATCH($I2;$A:$A;0)))+COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($E:$E;MATCH($I2;$A:$A;0))))
</code>```

It may looks complex but it's easier than it looks. This formula is composed of several parts:

INDEX($B:$B;MATCH($I2;$A:$A;0))) will return the criteria of the person in same row, but column B.

INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0)); will return as range the range of values from left dataset of the person you are matching up (header data) in the right dataset.

We can combine both of above with a COUNTIF to count how many times the value of the person in same row appears in the range of values of person in headers. We combine them as COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($B:$B;MATCH($I2;$A:$A;0))).

The above formula is just for 1 criteria, so you need to add extra COUNIF for each criteria you got (in this exampple, it would be 4 criterias, so 4 COUNIF).

The initial IF is useful just to show an X if the Intersection you are analyzing is same person in row and header.

After that, you can use conditional formatting in each row of right dataset to show max value.

The good thing of this method is that values on left dataset don't need to be in same column to be counted properly. If you look at image, Person 1 and PErson 2 matches perfectly, even if values are not in same order, because formula counts in whole range all the time.

I've uploaded a sample to my Gdrive in case you want to download and check the formulas properly (could be i made a translation error typing, because my excel is in spanish).

https://drive.google.com/open?id=1kPAARG8yAkXok7HxYkYswDiCAT37mmEz

With VBA probably you could do a macro that just shows the row number of person with better matches, but make sure you check ALL data, because maybe it could be that a person matches with 2 or more people, and all of them got max values. With this design, you could see that because both cell would be colored in green.

Hope you can adapt this to your needs.

Body:
I have a dataset that looks like this:

Person A, Value 1, Value 2, Value 3, Value 4
Person B, Value 1, Value 2, Value 3, Value 4

Now I would like to compare single rows of this dataset against the whole set with the criteria to show the row that has the most matching Values compared to the single row Im looking at.

For example. I have a new entry Person C. I want to be able to show (in an analysis tab) the other people that have the most common values with that person from the dataset.

Body:
I don't know how is your data stored, but I made up a sample emulating what you said about how your data looks like. I hope you can adapt this to your needs.

I made this:

Left dataset would be your data with values, and right dataset would be your analysis. The formula I used to get this is:

=IF(J$1=$I2;"x";COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($B:$B;MATCH($I2;$A:$A;0)))+COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($C:$C;MATCH($I2;$A:$A;0)))+COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($D:$D;MATCH($I2;$A:$A;0)))+COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($E:$E;MATCH($I2;$A:$A;0))))

It may looks complex but it's easier than it looks. This formula is composed of several parts:

INDEX($B:$B;MATCH($I2;$A:$A;0))) will return the criteria of the person in same row, but column B.

INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0)); will return as range the range of values from left dataset of the person you are matching up (header data) in the right dataset.

We can combine both of above with a COUNTIF to count how many times the value of the person in same row appears in the range of values of person in headers. We combine them as COUNTIF(INDIRECT("B" & MATCH(J$1;$A:$A;0) &":E"& MATCH(J$1;$A:$A;0));INDEX($B:$B;MATCH($I2;$A:$A;0))).

The above formula is just for 1 criteria, so you need to add extra COUNIF for each criteria you got (in this exampple, it would be 4 criterias, so 4 COUNIF).

The initial IF is useful just to show an X if the Intersection you are analyzing is same person in row and header.

After that, you can use conditional formatting in each row of right dataset to show max value.

The good thing of this method is that values on left dataset don't need to be in same column to be counted properly. If you look at image, Person 1 and PErson 2 matches perfectly, even if values are not in same order, because formula counts in whole range all the time.

I've uploaded a sample to my Gdrive in case you want to download and check the formulas properly (could be i made a translation error typing, because my excel is in spanish).

https://drive.google.com/open?id=1kPAARG8yAkXok7HxYkYswDiCAT37mmEz

With VBA probably you could do a macro that just shows the row number of person with better matches, but make sure you check ALL data, because maybe it could be that a person matches with 2 or more people, and all of them got max values. With this design, you could see that because both cell would be colored in green.

Hope you can adapt this to your needs.


问:
How to do integration testing in Flutter?
I want to do integration testing in Flutter. The tutorial I follow gives the following procedure:

Add the flutter_driver package to pubspec:

```<code>dev_dependencies:
flutter_driver:
sdk: flutter
</code>```

Enable the Flutter driver extension and add a call to
the enableFlutterDriverExtension() function in main.dart.

Run the integration test by using the flutter drive command:
flutter drive --target=my_app/test_driver/my_test.dart

My problem is with understanding step 2. It's not clear to me where in Android Studio do you enable the driver extension and where exactly in main.dart do you call the function enableFlutterDriveExtension().

I also have problems with the third step. After running the said command, it says in my terminal that

```<code>Error: The Flutter directory is not a clone of the GitHub project.
       The flutter tool requires Git in order to operate properly;
       to set up Flutter, run the following command:
       git clone -b stable https://github.com/flutter/flutter.git
</code>```

答:
You have to add this code inside the test_driver/app.dart file.

```<code>import 'package:flutter_driver/driver_extension.dart';
import 'package:[YOUR_APP]/main.dart' as app;

void main() {
  // This line enables the extension
  enableFlutterDriverExtension();

  // Call the `main()` function of your app or call `runApp` with any widget you
  // are interested in testing.
  app.main();
}
</code>```

You can find more info on the official Flutter documentation site (Steps 3 & 4):
https://flutter.dev/docs/cookbook/testing/integration/introduction

Good luck ;)

Body:
I want to do integration testing in Flutter. The tutorial I follow gives the following procedure:

Add the flutter_driver package to pubspec:

dev_dependencies:
flutter_driver:
sdk: flutter

Enable the Flutter driver extension and add a call to
the enableFlutterDriverExtension() function in main.dart.

Run the integration test by using the flutter drive command:
flutter drive --target=my_app/test_driver/my_test.dart

My problem is with understanding step 2. It's not clear to me where in Android Studio do you enable the driver extension and where exactly in main.dart do you call the function enableFlutterDriveExtension().

I also have problems with the third step. After running the said command, it says in my terminal that

Error: The Flutter directory is not a clone of the GitHub project.
       The flutter tool requires Git in order to operate properly;
       to set up Flutter, run the following command:
       git clone -b stable https://github.com/flutter/flutter.git

Body:
You have to add this code inside the test_driver/app.dart file.

import 'package:flutter_driver/driver_extension.dart';
import 'package:[YOUR_APP]/main.dart' as app;

void main() {
  // This line enables the extension
  enableFlutterDriverExtension();

  // Call the `main()` function of your app or call `runApp` with any widget you
  // are interested in testing.
  app.main();
}

You can find more info on the official Flutter documentation site (Steps 3 & 4):
https://flutter.dev/docs/cookbook/testing/integration/introduction

Good luck ;)


问:
Using RxJS observables to consider all input MIDI devices
I have a method that handles incoming MIDI messages just fine.

It listen on ALL input devices, and not just on the first one.

I would like to write it using RxJS observables.

Here is the working (non RxJS observables) one:

```<code>public initMidiInputBis() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    navigator.requestMIDIAccess().then(
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDISuccess(midiAccess),
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDIFailure(midiAccess)
    );
  } else {
    console.log('This browser does not support MIDI');
  }
}

private onMIDISuccess(midiAccess: WebMidi.MIDIAccess) {
  for (const inputDevice of Array.from(midiAccess.inputs)) {
    inputDevice[1].onmidimessage = (message: WebMidi.MIDIMessageEvent) => this.onMIDIMessage(message);
  }
}

private onMIDIFailure(error: any) {
  console.log('The browser could not access any MIDI device');
  console.log(error);
}
</code>```

This above method works fine, the VMPK virtual keyboard is seen as an input MIDI device and its MIDI messages are received.

Here is my attempt at writing it again using observables:

```<code>public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
    const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
      map((midiAccess: WebMidi.MIDIAccess) => {
        return midiAccess.inputs.values().next().value;
      })
    );
    midiInput$.pipe(
      flatMap((midiInput: WebMidi.MIDIInput) => this.midiMessageAsObservable(midiInput)),
    ).subscribe((message: WebMidi.MIDIMessageEvent) => {
      this.onMIDIMessage(message);
    });
    midiAccess$.subscribe(midiAccess => {
      this.logOutputDevices(midiAccess);
    });
  } else {
    console.log('This browser does not support MIDI');
  }
}
</code>```

With this above method, the VMPK virtual keyboard is NOT seen as an input MIDI device.

This method contains the following line of code midiAccess.inputs.values().next().value; which only retrieves the first input MIDI device.

How can I consider ALL input MIDI devices ?

UPDATE: After adding some logger I can see the VMPK virtual keyboard is listed as an input device:

```<code>MIDIInput {onmidimessage: null, connection: "closed", id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87", manufacturer: "", name: "VMPK Output", …}
connection: "closed"
id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87"
manufacturer: ""
name: "VMPK Output"
onmidimessage: null
onstatechange: null
state: "connected"
type: "input"
version: "ALSA library version 1.1.6"
</code>```

I find puzzling that its connection is closed while its state is connected.

Here is how I logged the above output:

```<code>const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
  map((midiAccess: WebMidi.MIDIAccess) => {
    Array.from(midiAccess.inputs.entries()).forEach(entry => {
      console.log('Key: ' + entry[0]);
      console.log(entry[1]);
    });
    return midiAccess.inputs.values().next().value;
  })
);
</code>```

答:
I could solve the issue with the following method:

```<code>public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
    midiAccess$.pipe(
      flatMap((midiAccess: WebMidi.MIDIAccess) => {
        return midiAccess.inputs;
      }),
      map((midiInput) => {
        return midiInput[1];
      }),
      filter((midiInput: WebMidi.MIDIInput) => midiInput !== undefined),
      flatMap((midiInput: WebMidi.MIDIInput) => this.midiMessageAsObservable(midiInput)),
    ).subscribe((message: WebMidi.MIDIMessageEvent) => {
      this.onMIDIMessage(message);
    });
    midiAccess$.subscribe(midiAccess => {
      this.logOutputDevices(midiAccess);
    });
  } else {
    console.log('This browser does not support MIDI');
  }
}

private midiMessageAsObservable(inputDevice: WebMidi.MIDIInput): Observable<WebMidi.MIDIMessageEvent> {
  const source: Subject<WebMidi.MIDIMessageEvent> = new Subject<WebMidi.MIDIMessageEvent>();
  inputDevice.onmidimessage = (note: WebMidi.MIDIMessageEvent) => source.next(note);
  return source.asObservable();
}
</code>```

I had to remove the call to the .next() method and return the value of the map.

Body:
I have a method that handles incoming MIDI messages just fine.

It listen on ALL input devices, and not just on the first one.

I would like to write it using RxJS observables.

Here is the working (non RxJS observables) one:

public initMidiInputBis() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    navigator.requestMIDIAccess().then(
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDISuccess(midiAccess),
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDIFailure(midiAccess)
    );
  } else {
    console.log('This browser does not support MIDI');
  }
}

private onMIDISuccess(midiAccess: WebMidi.MIDIAccess) {
  for (const inputDevice of Array.from(midiAccess.inputs)) {
    inputDevice[1].onmidimessage = (message: WebMidi.MIDIMessageEvent) => this.onMIDIMessage(message);
  }
}

private onMIDIFailure(error: any) {
  console.log('The browser could not access any MIDI device');
  console.log(error);
}

This above method works fine, the VMPK virtual keyboard is seen as an input MIDI device and its MIDI messages are received.

Here is my attempt at writing it again using observables:

public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
    const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
      map((midiAccess: WebMidi.MIDIAccess) => {
        return midiAccess.inputs.values().next().value;
      })
    );
    midiInput$.pipe(
      flatMap((midiInput: WebMidi.MIDIInput) => this.midiMessageAsObservable(midiInput)),
    ).subscribe((message: WebMidi.MIDIMessageEvent) => {
      this.onMIDIMessage(message);
    });
    midiAccess$.subscribe(midiAccess => {
      this.logOutputDevices(midiAccess);
    });
  } else {
    console.log('This browser does not support MIDI');
  }
}

With this above method, the VMPK virtual keyboard is NOT seen as an input MIDI device.

This method contains the following line of code midiAccess.inputs.values().next().value; which only retrieves the first input MIDI device.

How can I consider ALL input MIDI devices ?

UPDATE: After adding some logger I can see the VMPK virtual keyboard is listed as an input device:

MIDIInput {onmidimessage: null, connection: "closed", id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87", manufacturer: "", name: "VMPK Output", …}
connection: "closed"
id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87"
manufacturer: ""
name: "VMPK Output"
onmidimessage: null
onstatechange: null
state: "connected"
type: "input"
version: "ALSA library version 1.1.6"

I find puzzling that its connection is closed while its state is connected.

Here is how I logged the above output:

const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
  map((midiAccess: WebMidi.MIDIAccess) => {
    Array.from(midiAccess.inputs.entries()).forEach(entry => {
      console.log('Key: ' + entry[0]);
      console.log(entry[1]);
    });
    return midiAccess.inputs.values().next().value;
  })
);

Body:
I could solve the issue with the following method:

public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
    midiAccess$.pipe(
      flatMap((midiAccess: WebMidi.MIDIAccess) => {
        return midiAccess.inputs;
      }),
      map((midiInput) => {
        return midiInput[1];
      }),
      filter((midiInput: WebMidi.MIDIInput) => midiInput !== undefined),
      flatMap((midiInput: WebMidi.MIDIInput) => this.midiMessageAsObservable(midiInput)),
    ).subscribe((message: WebMidi.MIDIMessageEvent) => {
      this.onMIDIMessage(message);
    });
    midiAccess$.subscribe(midiAccess => {
      this.logOutputDevices(midiAccess);
    });
  } else {
    console.log('This browser does not support MIDI');
  }
}

private midiMessageAsObservable(inputDevice: WebMidi.MIDIInput): Observable<WebMidi.MIDIMessageEvent> {
  const source: Subject<WebMidi.MIDIMessageEvent> = new Subject<WebMidi.MIDIMessageEvent>();
  inputDevice.onmidimessage = (note: WebMidi.MIDIMessageEvent) => source.next(note);
  return source.asObservable();
}

I had to remove the call to the .next() method and return the value of the map.


问:
How to add dropdown list default value
I am using asp.net for fetching data from sql table to dropdown list. The problem is that, when I give default selection to the dropdown list. It does not take the default value.
Please see the code    </p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from States_agri", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        ddl_state.DataSource = dr;
        ddl_state.Items.Clear();
        ddl_state.Items.Add("--Please Select state--");
        ddl_state.DataTextField = "StateName";
        ddl_state.DataValueField = "StateID";
        ddl_state.DataBind();
        conn.Close();
    }
}
`
</code>```

<p>Also Please see the dropdown list aspx code for your reference.   </p>

```<code><asp:UpdatePanel ID="FormUpdate" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddl_state" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        <table>
            <tr>
                 <td>State*</td>
                 <td>
                     <asp:DropDownList ID="ddl_state" runat="server" CssClass="cbfld-popup1" AutoPostBack="true" OnSelectedIndexChanged="ddl_state_SelectedIndexChanged">
                     <asp:ListItem Enabled="true" Selected="True" Text="Please select State"></asp:ListItem>
                     </asp:DropDownList>
                 </td>

            </tr>
            <tr>
                 <td>District*</td>
                 <td>
                     <asp:DropDownList ID="ddl_district" CssClass="cbfld-popup1" runat="server">
                     <asp:ListItem Enabled="true" Selected="True" Text="Please select city"></asp:ListItem>
                                                                                </td>
            </tr>
         </table>
     </ContentTemplate>
</asp:UpdatePanel>
</code>```

答:
In this example the 3rd parameter is the default value :</p>

```<code>@Html.DropDownList("Items", new SelectList(ViewBag.Items), (string)ViewBag.MyFilter.ToString())
</code>```

Title: How to add dropdown list default value

Body:
I am using asp.net for fetching data from sql table to dropdown list. The problem is that, when I give default selection to the dropdown list. It does not take the default value.
Please see the code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from States_agri", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        ddl_state.DataSource = dr;
        ddl_state.Items.Clear();
        ddl_state.Items.Add("--Please Select state--");
        ddl_state.DataTextField = "StateName";
        ddl_state.DataValueField = "StateID";
        ddl_state.DataBind();
        conn.Close();
    }
}
`

Also Please see the dropdown list aspx code for your reference.

<asp:UpdatePanel ID="FormUpdate" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddl_state" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>

                 State*

                     <asp:DropDownList ID="ddl_state" runat="server" CssClass="cbfld-popup1" AutoPostBack="true" OnSelectedIndexChanged="ddl_state_SelectedIndexChanged">
                     <asp:ListItem Enabled="true" Selected="True" Text="Please select State"></asp:ListItem>
                     </asp:DropDownList>

                 District*

                     <asp:DropDownList ID="ddl_district" CssClass="cbfld-popup1" runat="server">
                     <asp:ListItem Enabled="true" Selected="True" Text="Please select city"></asp:ListItem>

     </ContentTemplate>
</asp:UpdatePanel>

Body:
In this example the 3rd parameter is the default value :

@Html.DropDownList("Items", new SelectList(ViewBag.Items), (string)ViewBag.MyFilter.ToString())


问:
Can I use @else/@elseif within @unless in Laravel blade?
I just found out about using @unless instead of if(!...) so I changed some of my clauses.

But I just realized that I had an if-else-statement, so I only changed it from this:

```<code>@if (!empty($data['note']))
  <p>{{ $data['note'] }}</p>
@else
  <p>no information given</p>
@endif
</code>```

to this:

```<code>@unless (empty($data['note']))
  <p>{{ $data['note'] }}</p>
@else
  <p>no information given</p>
@endunless
</code>```

But it didn't change anything and seems working correctly.

Is it okay/normal to use @elseand @elseif within @unless-statement?

答: It sure is okay. Unless is just an inverse of if, instead of using ! in the condition itself. So you can then chain as many else as you would with an if statement.

Body:
I just found out about using @unless instead of if(!...) so I changed some of my clauses.

But I just realized that I had an if-else-statement, so I only changed it from this:

@if (!empty($data['note']))

{{ $data['note'] }}

@else

no information given

@endif

to this:

@unless (empty($data['note']))

{{ $data['note'] }}

@else

no information given

@endunless

But it didn't change anything and seems working correctly.

Is it okay/normal to use @elseand @elseif within @unless-statement?


问:
Sporadic error downloading data from PHP application
A PHP application is offering binary data as a download:

```<code>header("Content-Type: application/octet-stream");
header("Pragma: public");
header("Cache-Control: private");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("expires: 0");
set_time_limit(0);
ob_clean();
flush();
@readfile($completefilename); exit;
</code>```

$completefilename is a stream like "ftp://user:pwd@..."

The size of the data can be several MByte. It works fine, but sporadically I get the following error:

答:
It's most likely that the remote stream is occasionally down, or times out.

Also as @fab says it could be that the file you are trying to load is larger than your script's memory.

You should start logging the errors readfile() returns, e.g. using the error_log php.ini directive.

If this needs to be completely foolproof, I think you'll have to use something more refined than readfile() that allows to set a timeout (like curl, or readfile with stream context options).

You could then catch any errors that occur while downloading, and serve a locally hosted fallback document instead. That document could e.g. be a text file containing the message "Resource xyz could not be loaded".

Body:
A PHP application is offering binary data as a download:

header("Content-Type: application/octet-stream");
header("Pragma: public");
header("Cache-Control: private");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("expires: 0");
set_time_limit(0);
ob_clean();
flush();
@readfile($completefilename); exit;

$completefilename is a stream like "ftp://user:pwd@..."

The size of the data can be several MByte. It works fine, but sporadically I get the following error:


问:
Is it possible to remote debug unit tests on the build server using Visual Studio
When unit tests are failing on the build server but not locally on my computer I would like to debug the code to find the problem. The build server runs Team City.</p>

答:
Here is one possible solution I used:

1. Within your test c#/vb code file, create a log file that would trace whatever you want to trace/print from the test you would debug. One possible location of that log file could be: %system.teamcity.build.checkoutDir%\LOG.TXT

2. After the test build step, create a PowerShell script that will copy the trace/log file onto a shared folder, that could be a shared folder on your machine (do not forget to give write/modify permissions to the build server user account on the share and folder security). If you don't know the builder user account, grant write/modify permissions to Everyone on that share (alert: this is unsafe from a security standpoint). Here is how that copy command could look like:
copy -Force %system.teamcity.build.checkoutDir%\LOG.TXT \MyMachineName\LogUnitTestsShare


问:
How to send an email when publish posts?
I wanted to send a email when publish post and i don't wanted to use plugin.
i add below  code to functions.php of my theme folder ,but it doesn't send any email to me. it goes to else part.</p>

```<code> function dothisfunction() {
     $sent = wp_mail("nadia.amoee@gmail.com","sms test", "message");
     if($sent) {
         echo "sent";
     }else {
         echo "failed";
     }

 }
 add_action( 'publish_post', 'dothisfunction' );
</code>```

答:
Use some SMTP server and you should solve.
are you sure your web hosting is supporting email sending? They are often blacklisted</p>

Body:
I wanted to send a email when publish post and i don't wanted to use plugin.
i add below  code to functions.php of my theme folder ,but it doesn't send any email to me. it goes to else part.

 function dothisfunction() {
     $sent = wp_mail("nadia.amoee@gmail.com","sms test", "message");
     if($sent) {
         echo "sent";
     }else {
         echo "failed";
     }

 }
 add_action( 'publish_post', 'dothisfunction' );


问:
DropDownListFor Not Selecting Value
I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.

```<code><%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%></code>```

I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.

答:
The issue at least for me was tied to the IEnumerable<T>.

Basically what happened was that the view and the model did not have the same reference for the same property.

If you do this

```<code>IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}
</code>```

Then bind this using the

```<code>@Html.DropDownListFor(model => model.Id, Model.CoolNames)
</code>```

The View loses track of the CoolNames property,
a simple fix is just to add .ToList() After dooing a projection  (.Select()) ;).

ContentLicense: CC BY-SA 2.5

Title: DropDownListFor Not Selecting Value

Body:
I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.

<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>

I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.

Body:
The issue at least for me was tied to the IEnumerable<T>.

Basically what happened was that the view and the model did not have the same reference for the same property.

If you do this

IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}

Then bind this using the

@Html.DropDownListFor(model => model.Id, Model.CoolNames)

The View loses track of the CoolNames property,
a simple fix is just to add .ToList() After dooing a projection  (.Select()) ;).


问:
Why the queue still joining after I called task_done()?
Python3.6

First I put some items in a queue, then start a thread and called join() of the queue in the main thread, then called get() in the thread loop, when the size of queue == 0, I called task_done() and break loop and exit from the thread. But the join() method still blocked in the main thread. I can not figure out what`s wrong.

Below is the code

Thanks

```<code>import queue
import threading

def worker(work_queue):
    while True:
        if work_queue.empty():
            print("Task 1 Over!")
            work_queue.task_done()
            break
        else:
            _ = work_queue.get()
            print(work_queue.qsize())
            # do actual work

def main():
    work_queue = queue.Queue()
    for i in range(10):
        work_queue.put("Item %d" % (i + 1))

    t = threading.Thread(target=worker, args=(work_queue, ))
    t.setDaemon(True)
    t.start()
    print("Main Thread 1")
    work_queue.join()
    print("Main Thread 2")
    t.join()
    print("Finish!")

if __name__ == "__main__":
    main()
</code>```

答:
task_done should be called for each work item which is dequeued and processed, not once the queue is entirely empty. (There'd be no reason for that-- the queue already knows when it's empty.) join() will block until task_done has been called as many times as put was called.

So:

```<code>def worker(work_queue):
    while True:
        if work_queue.empty():
            print("Task 1 Over!")
            break
        else:
            _ = work_queue.get()
            print(work_queue.qsize())
            # do actual work
</code>```

Note that it's weird for a worker to exit as soon as it sees an empty queue. Normally it would get() with blocking, and only exit when it got a "time to exit" work item out of the queue.

Body:
Python3.6

First I put some items in a queue, then start a thread and called join() of the queue in the main thread, then called get() in the thread loop, when the size of queue == 0, I called task_done() and break loop and exit from the thread. But the join() method still blocked in the main thread. I can not figure out what`s wrong.

Below is the code

Thanks

import queue
import threading

def worker(work_queue):
    while True:
        if work_queue.empty():
            print("Task 1 Over!")
            work_queue.task_done()
            break
        else:
            _ = work_queue.get()
            print(work_queue.qsize())
            # do actual work

def main():
    work_queue = queue.Queue()
    for i in range(10):
        work_queue.put("Item %d" % (i + 1))

    t = threading.Thread(target=worker, args=(work_queue, ))
    t.setDaemon(True)
    t.start()
    print("Main Thread 1")
    work_queue.join()
    print("Main Thread 2")
    t.join()
    print("Finish!")

if __name__ == "__main__":
    main()

Body:
task_done should be called for each work item which is dequeued and processed, not once the queue is entirely empty. (There'd be no reason for that-- the queue already knows when it's empty.) join() will block until task_done has been called as many times as put was called.

So:

def worker(work_queue):
    while True:
        if work_queue.empty():
            print("Task 1 Over!")
            break
        else:
            _ = work_queue.get()
            print(work_queue.qsize())
            # do actual work

Note that it's weird for a worker to exit as soon as it sees an empty queue. Normally it would get() with blocking, and only exit when it got a "time to exit" work item out of the queue.


问:
How to select the latest rows where each contains one value of all possible values found in a domain table?
```<code>ID Username City        RegisterYear
1  User1    New York    1990
2  User2    San Diego   2008
3  User3    Chicago     2009
4  User4    Los Angeles 1994
5  User5    San Diego   2004
</code>```

Domain Table

```<code>ID  City
1   New York
2   San Diego
3   Los Angeles
4   Chicago
</code>```

In this example the query would return:

```<code>User1
User2
User3
user4
</code>```

答:
Since the question doesn't provide an awful lot of detail, I have used some of the assumption that syrion made plus also decided that the city name will be unique to make things easier.</p>

```<code>select max(u.username) keep (dense_rank last order by registeryear) as username
from
  domain d
  left outer join users u on (d.city = u.city)
group by d.city
</code>```

Body:
ID Username City        RegisterYear
1  User1    New York    1990
2  User2    San Diego   2008
3  User3    Chicago     2009
4  User4    Los Angeles 1994
5  User5    San Diego   2004

Domain Table

ID  City
1   New York
2   San Diego
3   Los Angeles
4   Chicago

In this example the query would return:

User1
User2
User3
user4

Body:
Since the question doesn't provide an awful lot of detail, I have used some of the assumption that syrion made plus also decided that the city name will be unique to make things easier.

select max(u.username) keep (dense_rank last order by registeryear) as username
from
  domain d
  left outer join users u on (d.city = u.city)
group by d.city


问:
How to convert a codepoint to utf-8?
I have some code that reads in an a unicode codepoint (as escaped in a string 0xF00).

Since im using boost, I'm speculating if the following is best (and correct) approach:

```<code>unsigned int codepoint{0xF00};
boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint+1);
</code>```

?

答:
C++17 has deprecated number of convenience functions processing utf. Unfortunately, the last remaining ones will be deprecated in C++20 (*). That being said std::codecvt is still valid. From C++11 to C++17, you can use a std::codecvt<char32_t, char, mbstate_t>, starting with C++20 it will be std::codecvt<char32_t, char8_t, mbstate_t>.

Here is some code converting a code point (up to 0x10FFFF) in utf8:

```<code>// codepoint is the codepoint to convert
// buff is a char array of size sz (should be at least 4 to convert any code point)
// on return sz is the used size of buf for the utf8 converted string
// the return value is the return value of std::codecvt::out (0 for ok)
std::codecvt_base::result to_utf8(char32_t codepoint, char *buf, size_t& sz) {
    std::locale loc("");
    const std::codecvt<char32_t, char, std::mbstate_t> &cvt =
                   std::use_facet<std::codecvt<char32_t, char, std::mbstate_t>>(loc);

    std::mbstate_t state{{0}};

    const char32_t * last_in;
    char *last_out;
    std::codecvt_base::result res = cvt.out(state, &codepoint, 1+&codepoint, last_in,
                                            buf, buf+sz, last_out);
    sz = last_out - buf;
    return res;
}
</code>```

(*) std::codecvt will still exist in C++20. Simply the default instantiations will no longer be std::codecvt<char16_t, char, std::mbstate_t> and std::codecvt<char32_t, char, std::mbstate_t> but std::codecvt<char16_t, char8_t, std::mbstate_t> and std::codecvt<char32_t, char8_t, std::mbstate_t> (note char8_t instead of char)

Title: How to convert a codepoint to utf-8?

Body:
I have some code that reads in an a unicode codepoint (as escaped in a string 0xF00).

Since im using boost, I'm speculating if the following is best (and correct) approach:

unsigned int codepoint{0xF00};
boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint+1);

?

Body:
C++17 has deprecated number of convenience functions processing utf. Unfortunately, the last remaining ones will be deprecated in C++20 (*). That being said std::codecvt is still valid. From C++11 to C++17, you can use a std::codecvt<char32_t, char, mbstate_t>, starting with C++20 it will be std::codecvt<char32_t, char8_t, mbstate_t>.

Here is some code converting a code point (up to 0x10FFFF) in utf8:

// codepoint is the codepoint to convert
// buff is a char array of size sz (should be at least 4 to convert any code point)
// on return sz is the used size of buf for the utf8 converted string
// the return value is the return value of std::codecvt::out (0 for ok)
std::codecvt_base::result to_utf8(char32_t codepoint, char *buf, size_t& sz) {
    std::locale loc("");
    const std::codecvt<char32_t, char, std::mbstate_t> &cvt =
                   std::use_facet<std::codecvt<char32_t, char, std::mbstate_t>>(loc);

    std::mbstate_t state{{0}};

    const char32_t * last_in;
    char *last_out;
    std::codecvt_base::result res = cvt.out(state, &codepoint, 1+&codepoint, last_in,
                                            buf, buf+sz, last_out);
    sz = last_out - buf;
    return res;
}

(*) std::codecvt will still exist in C++20. Simply the default instantiations will no longer be std::codecvt<char16_t, char, std::mbstate_t> and std::codecvt<char32_t, char, std::mbstate_t> but std::codecvt<char16_t, char8_t, std::mbstate_t> and std::codecvt<char32_t, char8_t, std::mbstate_t> (note char8_t instead of char)


问:
Output to DataGridView is showing the amount of characters and not the string names
The DataGridView is displaying the number of characters in each string and not the names.

When I run the query in MySql workbench I get the correct output so I think the issue is where I am adding the query to the typesByMonth list.

I am getting the following output from the code provided:

Length 3 14

```<code>    private void TypesByMonthRadioButton_CheckedChanged(object sender, EventArgs e)
    {

        List<String> typesByMonth = new List<String>();

        string CS = ConfigurationManager.ConnectionStrings["U04i5a"].ConnectionString;

        using (MySqlConnection con = new MySqlConnection(CS))
        {
            con.Open();
            //string query = "SELECT DISTINCT type, COUNT(type) FROM appointment WHERE (start > @start && end < @end) GROUP BY type;";
            string query = "SELECT DISTINCT type FROM appointment;";

            using (MySqlCommand cmd = new MySqlCommand(query, con))
            {
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {

                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0))
                        {
                            typesByMonth.Add(reader["type"].ToString());
                        }
                    }
                }
            }
        }
        ReportsDataGridView.DataSource = typesByMonth;

    }
</code>```

The following is the output needed and what is given from the query in when tested in the workbench. "type" is the column.

Type xyz

General Doctor

答:
Issue is in datasource, not reading. If you want to keep list of strings, use ListBox instead of Grid.</p>

```<code>private void TypesByMonthRadioButton_CheckedChanged(object sender, EventArgs e)
{

    List<Source> typesByMonth = new List<String>();

    string CS = ConfigurationManager.ConnectionStrings["U04i5a"].ConnectionString;

    using (MySqlConnection con = new MySqlConnection(CS))
    {
        con.Open();
        //string query = "SELECT DISTINCT type, COUNT(type) FROM appointment WHERE (start > @start && end < @end) GROUP BY type;";
        string query = "SELECT DISTINCT type FROM appointment;";

        using (MySqlCommand cmd = new MySqlCommand(query, con))
        {
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {
                        typesByMonth.Add(new Source(reader["type"].ToString()));
                    }
                }
            }
        }
    }
    ReportsDataGridView.DataSource = typesByMonth;

}
</code>```

Body:
The DataGridView is displaying the number of characters in each string and not the names.

When I run the query in MySql workbench I get the correct output so I think the issue is where I am adding the query to the typesByMonth list.

I am getting the following output from the code provided:

Length 3 14

    private void TypesByMonthRadioButton_CheckedChanged(object sender, EventArgs e)
    {

        List<String> typesByMonth = new List<String>();

        string CS = ConfigurationManager.ConnectionStrings["U04i5a"].ConnectionString;

        using (MySqlConnection con = new MySqlConnection(CS))
        {
            con.Open();
            //string query = "SELECT DISTINCT type, COUNT(type) FROM appointment WHERE (start > @start && end < @end) GROUP BY type;";
            string query = "SELECT DISTINCT type FROM appointment;";

            using (MySqlCommand cmd = new MySqlCommand(query, con))
            {
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {

                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0))
                        {
                            typesByMonth.Add(reader["type"].ToString());
                        }
                    }
                }
            }
        }
        ReportsDataGridView.DataSource = typesByMonth;

    }

The following is the output needed and what is given from the query in when tested in the workbench. "type" is the column.

Type xyz

General Doctor

Body:
Issue is in datasource, not reading. If you want to keep list of strings, use ListBox instead of Grid.

private void TypesByMonthRadioButton_CheckedChanged(object sender, EventArgs e)
{

    List<Source> typesByMonth = new List<String>();

    string CS = ConfigurationManager.ConnectionStrings["U04i5a"].ConnectionString;

    using (MySqlConnection con = new MySqlConnection(CS))
    {
        con.Open();
        //string query = "SELECT DISTINCT type, COUNT(type) FROM appointment WHERE (start > @start && end < @end) GROUP BY type;";
        string query = "SELECT DISTINCT type FROM appointment;";

        using (MySqlCommand cmd = new MySqlCommand(query, con))
        {
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {
                        typesByMonth.Add(new Source(reader["type"].ToString()));
                    }
                }
            }
        }
    }
    ReportsDataGridView.DataSource = typesByMonth;

}


问:
How to configure annotations processing in IntelliJ IDEA 14 for current project work?
The structure of the project is:

Parent project

A project (Spring) have dependency of project B in pom.xml

B project (Spring MVC) have dependency of project A in pom.xml

After launching project B in Tomcat 7, I have an error:

Error:java: Annotation processing is not supported for module cycles.
  Please ensure that all modules from cycle [A,B] are excluded from
  annotation processing

How do I avoid this problem?

I use Java 8, Tomcat 7 and Intellij Idea 14.

答:
An alternative in order to solve this problem that worked for me (the above answers didn't).

Go to the pom.xml from the package / project that you have.
Delete the tag that is causing the issue.
You can find the dependecy with the issue in the console.

Hope it helps. :)


问:
In highcharts,tool-tip does not move when chart has high data unlike when it has low data
In highcharts, when I add data using addpoint() allowing 'shift' to 'true', the tool-tip does not move when it has large data just like how it moves when it has low data. the amount of data can be recognised by changing range of rangeSelector. Is there anything I can modify or should I include some extra code. I have reproduced the issue in below link.

https://jsfiddle.net/1y3gmkt5/

// Create the chart
Highcharts.stockChart('container', {
    chart: {
        events: {
            load: function () {

                // set up the updating of the chart each second
                var series1 = this.series[0];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 100);
                    series1.addPoint([x, y], true, true);
                }, 2000);
                var series2 = this.series[1];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 50);
                    series2.addPoint([x, y], true, true);
                }, 2000);
            }
        }
    },

    time: {
        useUTC: false
    },

    rangeSelector: {
        buttons: [{
            count: 1,
            type: 'minute',
            text: '1M'
        }, {
            count: 5,
            type: 'minute',
            text: '5M'
        }, {
            type: 'all',
            text: 'All'
        }],
        inputEnabled: false,
        selected: 0
    },

    title: {
        text: 'Live random data'
    },

    exporting: {
        enabled: false
    },
legend: {
                enabled: true
            },
plotOptions: {
        series: {
            marker: {
                states: {
                    hover: {
                        enabled: true,
                        animation: {duration: 100},
                        enableMouseTracking: true,
                        stickyTracking: true
                    }
                }
            }
        }
    },

tooltip:{
        shared: true,
                split: false,
         stickyTracking: true,
                enableMouseTracking: true,
                enabled: true,
                followPointer: true,
                followTouchMove: true,
          formatter: function(){
                var tooltip = "";
                var phaseNameList = "";

                //tooltip += "I-unit "+ "
"+ "x: "+this.x +"";
                tooltip += "I-unit "+ "
"+ "x: "+ new Date(this.x)+
                "";
                tooltip +=  "
"+ "y: "+this.y +"";
                tooltip +=  "
"+ this + "";
                return tooltip;
               }
},

    series: [{
        name: 'Random data1',
        data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -999; i <= 0; i += 1) {
                data.push([
                    time + i * 1000,
                    Math.round(Math.random() * 100)
                ]);
            }
            return data;
        }())
    },
    {
    name: 'Random data2',
        data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -999; i <= 0; i += 1) {
                data.push([
                    time + i * 1000,
                    Math.round(Math.random() * 50)
                ]);
            }
            return data;
        }())
    }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div></code>```

expected result: when mouse pointer is hovered over any marker and left as it is, then tool-tip should move behind as and when new data arrives. Currently works fine when range selector has low data but not when there is large data.

答:
The issue is caused by dataGrouping property that modifies the data. You can disable it by:

```<code>plotOptions: {
    series: {
        dataGrouping: {
            enabled: false
        },
        ...
    }
}
</code>```

Code snippet:

// Create the chart
Highcharts.stockChart('container', {
    chart: {
        events: {
            load: function() {

                // set up the updating of the chart each second
                var series1 = this.series[0];
                setInterval(function() {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 100);
                    series1.addPoint([x, y], true, true);
                }, 2000);
                var series2 = this.series[1];
                setInterval(function() {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 50);
                    series2.addPoint([x, y], true, true);
                }, 2000);
            }
        }
    },

    time: {
        useUTC: false
    },

    rangeSelector: {
        buttons: [{
            count: 1,
            type: 'minute',
            text: '1M'
        }, {
            count: 5,
            type: 'minute',
            text: '5M'
        }, {
            type: 'all',
            text: 'All'
        }],
        inputEnabled: false,
        selected: 0
    },

    title: {
        text: 'Live random data'
    },

    exporting: {
        enabled: false
    },
    legend: {
        enabled: true
    },
    plotOptions: {
        series: {
            dataGrouping: {
                enabled: false
            },
            marker: {
                states: {
                    hover: {
                        enabled: true,
                        animation: {
                            duration: 100
                        },
                        enableMouseTracking: true,
                        stickyTracking: true
                    }
                }
            }
        }
    },

    tooltip: {
        shared: true,
        split: false,
        stickyTracking: true,
        enableMouseTracking: true,
        enabled: true,
        followPointer: true,
        followTouchMove: true,
        formatter: function() {
            var tooltip = "";
            var phaseNameList = "";

            //tooltip += "I-unit "+ "
"+ "x: "+this.x +"";
            tooltip += "I-unit " + "
" + "x: " + new Date(this.x) +
                "";
            tooltip += "
" + "y: " + this.y + "";
            tooltip += "
" + this + "";
            return tooltip;
        }
    },

    series: [{
            name: 'Random data1',
            data: (function() {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -999; i <= 0; i += 1) {
                    data.push([
                        time + i * 1000,
                        Math.round(Math.random() * 100)
                    ]);
                }
                return data;
            }())
        },
        {
            name: 'Random data2',
            data: (function() {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -999; i <= 0; i += 1) {
                    data.push([
                        time + i * 1000,
                        Math.round(Math.random() * 50)
                    ]);
                }
                return data;
            }())
        }
    ]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div></code>```

Live demo: https://jsfiddle.net/BlackLabel/k52rnhya/

API Reference: https://api.highcharts.com/highstock/plotOptions.series.dataGrouping.enabled

Body:
In highcharts, when I add data using addpoint() allowing 'shift' to 'true', the tool-tip does not move when it has large data just like how it moves when it has low data. the amount of data can be recognised by changing range of rangeSelector. Is there anything I can modify or should I include some extra code. I have reproduced the issue in below link.

https://jsfiddle.net/1y3gmkt5/

// Create the chart
Highcharts.stockChart('container', {
    chart: {
        events: {
            load: function () {

                // set up the updating of the chart each second
                var series1 = this.series[0];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 100);
                    series1.addPoint([x, y], true, true);
                }, 2000);
                var series2 = this.series[1];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 50);
                    series2.addPoint([x, y], true, true);
                }, 2000);
            }
        }
    },

    time: {
        useUTC: false
    },

    rangeSelector: {
        buttons: [{
            count: 1,
            type: 'minute',
            text: '1M'
        }, {
            count: 5,
            type: 'minute',
            text: '5M'
        }, {
            type: 'all',
            text: 'All'
        }],
        inputEnabled: false,
        selected: 0
    },

    title: {
        text: 'Live random data'
    },

    exporting: {
        enabled: false
    },
legend: {
                enabled: true
            },
plotOptions: {
        series: {
            marker: {
                states: {
                    hover: {
                        enabled: true,
                        animation: {duration: 100},
                        enableMouseTracking: true,
                        stickyTracking: true
                    }
                }
            }
        }
    },

tooltip:{
        shared: true,
                split: false,
         stickyTracking: true,
                enableMouseTracking: true,
                enabled: true,
                followPointer: true,
                followTouchMove: true,
          formatter: function(){
                var tooltip = "";
                var phaseNameList = "";

                //tooltip += "I-unit "+ "
"+ "x: "+this.x +"";
                tooltip += "I-unit "+ "
"+ "x: "+ new Date(this.x)+
                "";
                tooltip +=  "
"+ "y: "+this.y +"";
                tooltip +=  "
"+ this + "";
                return tooltip;
               }
},

    series: [{
        name: 'Random data1',
        data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -999; i <= 0; i += 1) {
                data.push([
                    time + i * 1000,
                    Math.round(Math.random() * 100)
                ]);
            }
            return data;
        }())
    },
    {
    name: 'Random data2',
        data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -999; i <= 0; i += 1) {
                data.push([
                    time + i * 1000,
                    Math.round(Math.random() * 50)
                ]);
            }
            return data;
        }())
    }]
});

expected result: when mouse pointer is hovered over any marker and left as it is, then tool-tip should move behind as and when new data arrives. Currently works fine when range selector has low data but not when there is large data.

Body:
The issue is caused by dataGrouping property that modifies the data. You can disable it by:

plotOptions: {
    series: {
        dataGrouping: {
            enabled: false
        },
        ...
    }
}

Code snippet:

// Create the chart
Highcharts.stockChart('container', {
    chart: {
        events: {
            load: function() {

                // set up the updating of the chart each second
                var series1 = this.series[0];
                setInterval(function() {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 100);
                    series1.addPoint([x, y], true, true);
                }, 2000);
                var series2 = this.series[1];
                setInterval(function() {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 50);
                    series2.addPoint([x, y], true, true);
                }, 2000);
            }
        }
    },

    time: {
        useUTC: false
    },

    rangeSelector: {
        buttons: [{
            count: 1,
            type: 'minute',
            text: '1M'
        }, {
            count: 5,
            type: 'minute',
            text: '5M'
        }, {
            type: 'all',
            text: 'All'
        }],
        inputEnabled: false,
        selected: 0
    },

    title: {
        text: 'Live random data'
    },

    exporting: {
        enabled: false
    },
    legend: {
        enabled: true
    },
    plotOptions: {
        series: {
            dataGrouping: {
                enabled: false
            },
            marker: {
                states: {
                    hover: {
                        enabled: true,
                        animation: {
                            duration: 100
                        },
                        enableMouseTracking: true,
                        stickyTracking: true
                    }
                }
            }
        }
    },

    tooltip: {
        shared: true,
        split: false,
        stickyTracking: true,
        enableMouseTracking: true,
        enabled: true,
        followPointer: true,
        followTouchMove: true,
        formatter: function() {
            var tooltip = "";
            var phaseNameList = "";

            //tooltip += "<b>I-unit "+ "<br/>"+ "x: "+this.x +"</b>";
            tooltip += "<b>I-unit " + "<br/>" + "x: " + new Date(this.x) +
                "</b>";
            tooltip += "<br/>" + "y: " + this.y + "</b>";
            tooltip += "<br/>" + this + "</b>";
            return tooltip;
        }
    },

    series: [{
            name: 'Random data1',
            data: (function() {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -999; i <= 0; i += 1) {
                    data.push([
                        time + i * 1000,
                        Math.round(Math.random() * 100)
                    ]);
                }
                return data;
            }())
        },
        {
            name: 'Random data2',
            data: (function() {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -999; i <= 0; i += 1) {
                    data.push([
                        time + i * 1000,
                        Math.round(Math.random() * 50)
                    ]);
                }
                return data;
            }())
        }
    ]
});

<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div>

Live demo: https://jsfiddle.net/BlackLabel/k52rnhya/

API Reference: https://api.highcharts.com/highstock/plotOptions.series.dataGrouping.enabled


问:
Custom checkout billing field on email notifications
In WooCommerce, based on "Dynamic synched custom checkout select fields in WooCommerce" answer code, I am adding some custom fields on checkout which will be displayed under the billing section on the e-mail confirmation

Here is my actual code:

```<code>add_action( 'woocommerce_after_checkout_billing_form', 'add_checkout_custom_fields', 20, 1 );
function add_checkout_custom_fields( $checkout) {
    $domain = 'woocommerce'; // The domain slug

    // First Select field (Master)
    woocommerce_form_field( 'delivery_one', array(
        'type'          => 'select',
        'label'         => __( 'Art der Lieferung' , $domain),
        'class'         => array( 'form-row-first' ),
        'required'       => true,
        'options'       => array(
            ''  => __( 'Wählen Art der Lieferung.', $domain ),
            'A' => __( 'Hauszustellung', $domain ),
            'B' => __( 'Selbst Abholung', $domain ),

        ),
    ), $checkout->get_value( 'delivery_one' ) );

    // Default option value
    $default_option2 = __( 'Wählen Sie Zeitbereich.', $domain );

    // Dynamic select field options for Javascript/jQuery
    $options_0 = array( '' => $default_option2 );
    $options_a = array(
        ''  => $default_option2,
        '1' => __( '09:00-11:00', $domain ),
        '2' => __( '10:00-12:00', $domain ),
        '3' => __( '11:00-13:00', $domain ),
        '4' => __( '12:00-14:00', $domain ),
        '5' => __( '13:00-15:00', $domain ),
        '6' => __( '14:00-16:00', $domain ),
        '7' => __( '15:00-17:00', $domain ),
    );

    $options_b = array(
        ''  => $default_option2,
        '1' => __( '01:00', $domain ),
        '2' => __( '02:00', $domain ),
        '3' => __( '03:00', $domain ),
        '4' => __( '04:00', $domain ),
        '5' => __( '05:00', $domain ),
        '6' => __( '06:00', $domain ),
        '7' => __( '07:00', $domain ),
        '8' => __( '08:00', $domain ),
        '9' => __( '09:00', $domain ),
        '10' => __( '10:00', $domain ),
        '11' => __( '11:00', $domain ),
        '12' => __( '12:00', $domain ),
        '13' => __( '13:00', $domain ),
        '14' => __( '14:00', $domain ),
        '15' => __( '15:00', $domain ),
        '16' => __( '16:00', $domain ),
        '17' => __( '17:00', $domain ),
        '18' => __( '18:00', $domain ),
        '19' => __( '19:00', $domain ),
        '20' => __( '20:00', $domain ),
        '21' => __( '21:00', $domain ),
        '22' => __( '22:00', $domain ),
        '23' => __( '23:00', $domain ),
        '24' => __( '24:00', $domain ),
    );

    // Second Select field (Dynamic Slave)
    woocommerce_form_field( 'delivery_two', array(
        'type'          => 'select',
        'label'         => __( 'Zeitspanne', $domain ),
        'class'         => array( 'form-row-last' ),
        'required'       => true,
        'options'       => $options_0,
    ), $checkout->get_value( 'delivery_two' ) );

    $required = esc_attr__( 'required', 'woocommerce' );

    // jQuery code
    ?>
    <script>
    jQuery(function($){
        var op0 = <?php echo json_encode($options_0); ?>,
            opa = <?php echo json_encode($options_a); ?>,
            opb = <?php echo json_encode($options_b); ?>,

            select1 = 'select[name="delivery_one"]',
            select2 = 'select[name="delivery_two"]';

        // Utility function to fill dynamically the select field options
        function dynamicSelectOptions( opt ){
            var options = '';
            $.each( opt, function( key, value ){
                options += '<option value="'+key+'">'+value+'</option>';
            });
            $(select2).html(options);
        }

        // 1. When dom is loaded we add the select field option for "A" value
        // => Disabled (optional) — Uncomment below to enable
        // dynamicSelectOptions( opa );

        // 2. On live selection event on the first dropdown
        $(select1).change(function(){
            if( $(this).val() == 'A' )
                dynamicSelectOptions( opa );
            else if( $(this).val() == 'B' )
                dynamicSelectOptions( opb );

            else
                dynamicSelectOptions( op0 ); // Reset to default
        });
    });
    </script>
    <?php
}

// Check checkout custom fields
add_action( 'woocommerce_checkout_process', 'wps_check_checkout_custom_fields', 20 ) ;
function wps_check_checkout_custom_fields() {
    // if custom fields are empty stop checkout process displaying an error notice.
    if ( empty($_POST['delivery_one']) || empty($_POST['delivery_two']) ){
        $notice = __( 'Bitte wählen Sie die Versandart oder den Stundenbereich' );
        wc_add_notice( '<strong>' . $notice . '</strong>', 'error' );
    }
}
</code>```

My custom fields and their values, are shown on the checkout form and on the order pages on back end. So far everything works great.

But the problem is that the e-mail that I receive does not contain the custom fields and their values.

How can I display that custom checkout billing fields on email notifications?

Is this code correct?

```<code>add_filter( 'woocommerce_email_format_string' , 'add_custom_email_format_string', 20, 2 );
  function add_custom_email_format_string( $string, $email ) {
// The post meta key used to save the value in the order post meta data
$meta_key = '_delivery_one';

// Get the instance of the WC_Order object
$order    = $email->object;

// Get the value
$value = $order->get_meta($meta_key) ? $order->get_meta($meta_key) : '';

// Additional subject placeholder
$new_placeholders = array( '{delivery_one}' => $value );

return str_replace( array_keys( $additional_placeholders ), array_values( $additional_placeholders ), $string );
 }
</code>```

答:
You have to define a new placeholder that can be parsed.

```<code>add_filter( 'woocommerce_email_format_string' , 'add_custom_email_format_string', 20, 2 );
function add_custom_email_format_string( $string, $email ) {
    // The post meta key used to save the value in the order post meta data
    $meta_key = '_billing_field_newfield';

    // Get the instance of the WC_Order object
    $order    = $email->object;

    // Get the value
    $value = $order->get_meta($meta_key) ? $order->get_meta($meta_key) : '';

    // Additional subject placeholder
    $new_placeholders = array( '{billing_field_newfield}' => $value );

    // Return the clean replacement value string for "{billing_field_newfield}" placeholder
    return str_replace( array_keys( $additional_placeholders ), array_values( $additional_placeholders ), $string );
}
</code>```

Code goes in function.php file of your active child theme (or active theme). It will works.

Then in Woocommerce > Settings > Emails > "New Order" notification, you will be able to use the dynamic placeholder {billing_field_newfield}…

Body:
In WooCommerce, based on "Dynamic synched custom checkout select fields in WooCommerce" answer code, I am adding some custom fields on checkout which will be displayed under the billing section on the e-mail confirmation

Here is my actual code:

add_action( 'woocommerce_after_checkout_billing_form', 'add_checkout_custom_fields', 20, 1 );
function add_checkout_custom_fields( $checkout) {
    $domain = 'woocommerce'; // The domain slug

    // First Select field (Master)
    woocommerce_form_field( 'delivery_one', array(
        'type'          => 'select',
        'label'         => __( 'Art der Lieferung' , $domain),
        'class'         => array( 'form-row-first' ),
        'required'       => true,
        'options'       => array(
            ''  => __( 'Wählen Art der Lieferung.', $domain ),
            'A' => __( 'Hauszustellung', $domain ),
            'B' => __( 'Selbst Abholung', $domain ),

        ),
    ), $checkout->get_value( 'delivery_one' ) );

    // Default option value
    $default_option2 = __( 'Wählen Sie Zeitbereich.', $domain );

    // Dynamic select field options for Javascript/jQuery
    $options_0 = array( '' => $default_option2 );
    $options_a = array(
        ''  => $default_option2,
        '1' => __( '09:00-11:00', $domain ),
        '2' => __( '10:00-12:00', $domain ),
        '3' => __( '11:00-13:00', $domain ),
        '4' => __( '12:00-14:00', $domain ),
        '5' => __( '13:00-15:00', $domain ),
        '6' => __( '14:00-16:00', $domain ),
        '7' => __( '15:00-17:00', $domain ),
    );

    $options_b = array(
        ''  => $default_option2,
        '1' => __( '01:00', $domain ),
        '2' => __( '02:00', $domain ),
        '3' => __( '03:00', $domain ),
        '4' => __( '04:00', $domain ),
        '5' => __( '05:00', $domain ),
        '6' => __( '06:00', $domain ),
        '7' => __( '07:00', $domain ),
        '8' => __( '08:00', $domain ),
        '9' => __( '09:00', $domain ),
        '10' => __( '10:00', $domain ),
        '11' => __( '11:00', $domain ),
        '12' => __( '12:00', $domain ),
        '13' => __( '13:00', $domain ),
        '14' => __( '14:00', $domain ),
        '15' => __( '15:00', $domain ),
        '16' => __( '16:00', $domain ),
        '17' => __( '17:00', $domain ),
        '18' => __( '18:00', $domain ),
        '19' => __( '19:00', $domain ),
        '20' => __( '20:00', $domain ),
        '21' => __( '21:00', $domain ),
        '22' => __( '22:00', $domain ),
        '23' => __( '23:00', $domain ),
        '24' => __( '24:00', $domain ),
    );

    // Second Select field (Dynamic Slave)
    woocommerce_form_field( 'delivery_two', array(
        'type'          => 'select',
        'label'         => __( 'Zeitspanne', $domain ),
        'class'         => array( 'form-row-last' ),
        'required'       => true,
        'options'       => $options_0,
    ), $checkout->get_value( 'delivery_two' ) );

    $required = esc_attr__( 'required', 'woocommerce' );

    // jQuery code
    ?>

    <?php
}

// Check checkout custom fields
add_action( 'woocommerce_checkout_process', 'wps_check_checkout_custom_fields', 20 ) ;
function wps_check_checkout_custom_fields() {
    // if custom fields are empty stop checkout process displaying an error notice.
    if ( empty($_POST['delivery_one']) || empty($_POST['delivery_two']) ){
        $notice = __( 'Bitte wählen Sie die Versandart oder den Stundenbereich' );
        wc_add_notice( '' . $notice . '', 'error' );
    }
}

My custom fields and their values, are shown on the checkout form and on the order pages on back end. So far everything works great.

But the problem is that the e-mail that I receive does not contain the custom fields and their values.

How can I display that custom checkout billing fields on email notifications?

Is this code correct?

add_filter( 'woocommerce_email_format_string' , 'add_custom_email_format_string', 20, 2 );
  function add_custom_email_format_string( $string, $email ) {
// The post meta key used to save the value in the order post meta data
$meta_key = '_delivery_one';

// Get the instance of the WC_Order object
$order    = $email->object;

// Get the value
$value = $order->get_meta($meta_key) ? $order->get_meta($meta_key) : '';

// Additional subject placeholder
$new_placeholders = array( '{delivery_one}' => $value );

return str_replace( array_keys( $additional_placeholders ), array_values( $additional_placeholders ), $string );
 }

Body:
You have to define a new placeholder that can be parsed.

add_filter( 'woocommerce_email_format_string' , 'add_custom_email_format_string', 20, 2 );
function add_custom_email_format_string( $string, $email ) {
    // The post meta key used to save the value in the order post meta data
    $meta_key = '_billing_field_newfield';

    // Get the instance of the WC_Order object
    $order    = $email->object;

    // Get the value
    $value = $order->get_meta($meta_key) ? $order->get_meta($meta_key) : '';

    // Additional subject placeholder
    $new_placeholders = array( '{billing_field_newfield}' => $value );

    // Return the clean replacement value string for "{billing_field_newfield}" placeholder
    return str_replace( array_keys( $additional_placeholders ), array_values( $additional_placeholders ), $string );
}

Code goes in function.php file of your active child theme (or active theme). It will works.

Then in Woocommerce > Settings > Emails > "New Order" notification, you will be able to use the dynamic placeholder {billing_field_newfield}…


问:
How to apply dynamic controller name inside @Url.Action in MVC
In my DOT NET CORE MVC application i am using  Url Action inside a view to generate and redirect action link

@Url.Action ("Action Name","Controller Name")

Above synatax is working fine for me where i am passing static value of controller like

'@Url.Action(nameof(EmployeeController.Edit),"Employee")'

Here controller name is static and i want to avoid a situation like in future if i change controller name at that time i need to remember this changes in view so my requirement is Basically i want to pass controller name like below

'@Url.Action(nameof(EmployeeController.Edit),nameof(EmployeeController))'

Controller and Action method is

```<code>public class EmployeeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Edit()
        {
            return RedirectToAction("Index", "HotelList", new { area = "Hotel" });
        }
    }
</code>```

Suggest me best way to do this

Thanks in advance

答:
By convention controller classes end in the word Controller but references to them for URL purposes do not.  (Honestly this discrepency has never even occurred to me until now.)  It's probably best not to mess with that convention, as it could cascade into other problems.  Instead, maybe just modify the string being used in the result.

Something like this:

```<code>nameof(EmployeeController).Replace("Controller", string.Empty)
</code>```

If this is used a lot, perhaps encapsulate it into a helper or extension method somewhere for simplicity.

Body:
In my DOT NET CORE MVC application i am using  Url Action inside a view to generate and redirect action link

@Url.Action ("Action Name","Controller Name")

Above synatax is working fine for me where i am passing static value of controller like

'@Url.Action(nameof(EmployeeController.Edit),"Employee")'

Here controller name is static and i want to avoid a situation like in future if i change controller name at that time i need to remember this changes in view so my requirement is Basically i want to pass controller name like below

'@Url.Action(nameof(EmployeeController.Edit),nameof(EmployeeController))'

Controller and Action method is

public class EmployeeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Edit()
        {
            return RedirectToAction("Index", "HotelList", new { area = "Hotel" });
        }
    }

Suggest me best way to do this

Thanks in advance

Body:
By convention controller classes end in the word Controller but references to them for URL purposes do not.  (Honestly this discrepency has never even occurred to me until now.)  It's probably best not to mess with that convention, as it could cascade into other problems.  Instead, maybe just modify the string being used in the result.

Something like this:

nameof(EmployeeController).Replace("Controller", string.Empty)

If this is used a lot, perhaps encapsulate it into a helper or extension method somewhere for simplicity.