问:
How to make queries from multiple models in a single view
I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.

I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.

Here is my student model.

```<code>class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

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

This is my result upload model

```<code>class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)
</code>```

This is my school selection model.

NB: I removed the multiple school models and put everything in one model.

```<code>class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)
</code>```

And this is my views.py for placement.

```<code>def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")
</code>```

Here is my placement.html file

```<code><div class="container">
<p id="success">
    Placement Here.
</p>
{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}<br>
    Stdudent username: {{ placement.student.user }}<br>
    Stdudent gender: {{ placement.student.gender }}<br>
    School: {{ placement.school }}<br><br>

{% endfor %}
</div>
</code>```

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

答:
place is a queryset. so must be iterate it.

try this code:

```<code>def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:
            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):
                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)

                    if raw_score >= 480:
                        place_me = school_one
                    elif raw_score >= 420:
                        place_me = school_two
                    elif raw_score >= 360:
                        place_me = school_three
                    elif raw_score >= 300:
                        place_me = school_four
                    else:
                        place_me = school_five

                    placements.append({'student': candidate, 'school': place_me})
    return render(request, 'schools/placement.html', {'place_me': placements})
</code>```

placement.html:

```<code><div class="container">
    <p id="success">
        Placement Here.
    </p>
    {% for placement in place_me %}
        Stdudent Id: {{ placement.student.student_ID }}
        Stdudent middle name: {{ placement.student.middle_Name }}
        Stdudent gender: {{ placement.student.gender }}

        Placements:
            {% for school in placement.school %}
                {{ school }}
            {% endfor %}
    {% endfor %}
</div>
</code>```

Body:
I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.

I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.

Here is my student model.

class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

    def __str__(self):
        return self.user.username

This is my result upload model

class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

This is my school selection model.

NB: I removed the multiple school models and put everything in one model.

class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

And this is my views.py for placement.

def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")

Here is my placement.html file

    Placement Here.

{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}

    Stdudent username: {{ placement.student.user }}

    Stdudent gender: {{ placement.student.gender }}

    School: {{ placement.school }}

{% endfor %}

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

Body:
place is a queryset. so must be iterate it.

try this code:

def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:
            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):
                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)

                    if raw_score >= 480:
                        place_me = school_one
                    elif raw_score >= 420:
                        place_me = school_two
                    elif raw_score >= 360:
                        place_me = school_three
                    elif raw_score >= 300:
                        place_me = school_four
                    else:
                        place_me = school_five

                    placements.append({'student': candidate, 'school': place_me})
    return render(request, 'schools/placement.html', {'place_me': placements})

placement.html:

<div class="container">
    <p id="success">
        Placement Here.
    </p>
    {% for placement in place_me %}
        Stdudent Id: {{ placement.student.student_ID }}
        Stdudent middle name: {{ placement.student.middle_Name }}
        Stdudent gender: {{ placement.student.gender }}

        Placements:
            {% for school in placement.school %}
                {{ school }}
            {% endfor %}
    {% endfor %}
</div>


来源: stackexchange

问:
conditional formatting for a full column based on the average value in that row?
I'm going through a sheet with multiple different data points across different rows (for different versions of the same action each on their own row).

In order to easily compare from one row to the next, I would like to use conditional formatting to on a simple level as follows: - highlight cell green if a value in that cell is equal to or greater than average for that column - highlight cell red if a value is less than average for that column

So for example, I need all cells in column F to be green if the value in each cell is equal to or greater than the average of all values in that column or red if it's less than the average of all values in that column.

But I'm struggling to get that working.

Does anyone have any ideas?

I tried in 2 ways, trying to get a custom formula that calculates this average and merely doing greater than or less than in reference to a specific cell in another column (I have a separate column where I only have the average of each column calculated as follows: =Average(E3:E18) but neither is working consistently, it's highlighting some cells green that should be red and vice versa.

答:
green color:

```<code>=IF(AVERAGE(F:F)<=F2, 1)
</code>```

red color:

```<code>=IF(AND(AVERAGE(F:F)>F2, F2<>""), 1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
green color:

=IF(AVERAGE(F:F)<=F2, 1)

red color:

=IF(AND(AVERAGE(F:F)>F2, F2<>""), 1)


问:
Hibernate query for Entities having oneToMany relation (using sub-query in select statement)
I am new to hibernate and I want to create the following query using hibernate

working sql:

```<code>select * , (select count(*) from likes as li where q.ques_id= li.ques_id) as likes_Count from question as q where q.subcategory_id =1)
</code>```

but can't get around for hibernate.

I have written a method in my DAOImpl class but not working when I use the subquery for COUNT.

```<code>public List<Question> mcqsListByPage(int subCatId, int pagenumber, int pagesize) {

      String query = "select * , (select count(*) from mc.userLikes as l where qs.qs_id= l.qs_id) as count1 FROM Question qs JOIN qs.userLikes AND qs.subCategory = :catId";
        try {
            return sessionFactory.getCurrentSession().createQuery(query, Question.class)
                    .setParameter("catId", subCatId)
                    .setFirstResult((pagenumber - 1) * pagesize)
                    .setMaxResults(pagesize)
                    .getResultList();

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
</code>```

I have two entity with onetomany releation

```<code>public class Question{

       @Column(name = "subcategory_id")
    private int subCategory;

        @OneToMany(mappedBy = "qs_id", fetch = FetchType.EAGER)
    private List<Likes> userLikes = new ArrayList<Likes>();
    }

public class Likes{

        @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private int id;

        @ManyToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "QS_ID")
    private Question qs   ;
}
</code>```

I want to return a list of question along with the number of likes
 for every question in a List<> using hibernate.

答:
First off, when writing queries with Hibernate, you need to forget the concepts of your database, like columns, and *. With Hibernate, you query your entities (Java classes).

Since your list of Likes is fetch eagerly, you can do something as simple as:

```<code>public List<Question> getQuestionsForSubcategory(final int subcategory) {
    final TypedQuery<Question> query =
        em.createQuery("select q from Question q where q.subCategory = :subcategory", Question.class);
    query.setParameter("subcategory", subcategory);
    return query.getResultList();
}
</code>```

Then, you can use this list to create a structure containing the number of likes:

```<code>public Map<Question, Integer> getLikesPerQuestion() {
    final List<Question> questions = getQuestionsForSubcategory(1);
    return questions.stream()
                    .collect(Collectors.toMap(q -> q, q -> q.getUserLikes().size()));
</code>```

If the list of Likes was lazy fetched this would decrease performance though, and a speicific query would be better.

If you want to do this with a single database-query, it is quite difficult (impossible?) to combine a query for an entity with a custom column. But you could do something like this:

```<code>public Map<Integer, Long> getQuestionIdToNumberOfLikes() {
    TypedQuery<Object[]> query =
         em.createQuery("SELECT q.id, count(ul) FROM Question q JOIN t.userLikes ul GROUP BY q.id", Object[].class);
         return query.getResultList()
                     .stream()
                     .collect(Collectors.toMap(o -> (Integer) o[0], o -> (Long) o[1]));

}
</code>```

Body:
I am new to hibernate and I want to create the following query using hibernate

working sql:

select * , (select count(*) from likes as li where q.ques_id= li.ques_id) as likes_Count from question as q where q.subcategory_id =1)

but can't get around for hibernate.

I have written a method in my DAOImpl class but not working when I use the subquery for COUNT.

public List<Question> mcqsListByPage(int subCatId, int pagenumber, int pagesize) {

      String query = "select * , (select count(*) from mc.userLikes as l where qs.qs_id= l.qs_id) as count1 FROM Question qs JOIN qs.userLikes AND qs.subCategory = :catId";
        try {
            return sessionFactory.getCurrentSession().createQuery(query, Question.class)
                    .setParameter("catId", subCatId)
                    .setFirstResult((pagenumber - 1) * pagesize)
                    .setMaxResults(pagesize)
                    .getResultList();

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

I have two entity with onetomany releation

public class Question{

       @Column(name = "subcategory_id")
    private int subCategory;

        @OneToMany(mappedBy = "qs_id", fetch = FetchType.EAGER)
    private List<Likes> userLikes = new ArrayList<Likes>();
    }

public class Likes{

        @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private int id;

        @ManyToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "QS_ID")
    private Question qs   ;
}

I want to return a list of question along with the number of likes
 for every question in a List<> using hibernate.

Body:
First off, when writing queries with Hibernate, you need to forget the concepts of your database, like columns, and *. With Hibernate, you query your entities (Java classes).

Since your list of Likes is fetch eagerly, you can do something as simple as:

public List<Question> getQuestionsForSubcategory(final int subcategory) {
    final TypedQuery<Question> query =
        em.createQuery("select q from Question q where q.subCategory = :subcategory", Question.class);
    query.setParameter("subcategory", subcategory);
    return query.getResultList();
}

Then, you can use this list to create a structure containing the number of likes:

public Map<Question, Integer> getLikesPerQuestion() {
    final List<Question> questions = getQuestionsForSubcategory(1);
    return questions.stream()
                    .collect(Collectors.toMap(q -> q, q -> q.getUserLikes().size()));

If the list of Likes was lazy fetched this would decrease performance though, and a speicific query would be better.

If you want to do this with a single database-query, it is quite difficult (impossible?) to combine a query for an entity with a custom column. But you could do something like this:

public Map<Integer, Long> getQuestionIdToNumberOfLikes() {
    TypedQuery<Object[]> query =
         em.createQuery("SELECT q.id, count(ul) FROM Question q JOIN t.userLikes ul GROUP BY q.id", Object[].class);
         return query.getResultList()
                     .stream()
                     .collect(Collectors.toMap(o -> (Integer) o[0], o -> (Long) o[1]));

}


问:
OnOptionsItemSelected not called in Xamarin.Forms
I am newbie to Xamarin.Forms. I am trying to show a DisplayAlert() when NavigationBar back button is clicked. I have tried implementing according to this article. The problem is when I click on the button the popup doesn't come. I placed a breakpoint on OnOptionsItemSelected() method to see if its getting called or not, it doesn't. This is my MainActivity.cs

```<code>protected override void OnCreate(Bundle bundle)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(bundle);

    global::Xamarin.Forms.Forms.Init(this, bundle);
    global::Xamarin.FormsMaps.Init(this, bundle);
    LoadApplication(new App());

    Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
    SetSupportActionBar(toolbar);

}

public override bool OnOptionsItemSelected(IMenuItem item)
{
    //Placed a debugger here
    // check if the current item id is equals to the back button id
    if (item.ItemId == 16908332)
    {
        // retrieve the current xamarin forms page instance
        var currentpage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault() as NavBackButtonContentPage;

        // check if the page has subscribed to the custom back button event
        if (currentpage?.CustomBackButtonAction != null)
        {
            // invoke the Custom back button action
            currentpage?.CustomBackButtonAction.Invoke();
            // and disable the default back button action
            return false;
        }

        // if its not subscribed then go ahead with the default back button action
        return base.OnOptionsItemSelected(item);
    }
    else
    {
        // since its not the back button click, pass the event to the base
        return base.OnOptionsItemSelected(item);
    }
}
</code>```

I am using it inside MasterDetailPage.

答:
I also had the same issue and found the solution. The issue is MainActivity was sub-classing from the FormsAppCompactActivity instead of old FormsApplicationActivity which was the previous parent class for MainActivity. So assume bug on new FormsAppCompactActivity

The issue will be fixed when you add following lines to MainActivity OnCreate method (after the  LoadApplication(new App()); line)

```<code>Android.Support.V7.Widget.Toolbar toolbar
                = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);
</code>```

Referenced URL and thread as follows
https://forums.xamarin.com/discussion/comment/218663

https://theconfuzedsourcecode.wordpress.com/2017/03/02/formsappcompatactivity-is-not-calling-onoptionsitemselected-xamarin-android/

Body:
I am newbie to Xamarin.Forms. I am trying to show a DisplayAlert() when NavigationBar back button is clicked. I have tried implementing according to this article. The problem is when I click on the button the popup doesn't come. I placed a breakpoint on OnOptionsItemSelected() method to see if its getting called or not, it doesn't. This is my MainActivity.cs

protected override void OnCreate(Bundle bundle)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(bundle);

    global::Xamarin.Forms.Forms.Init(this, bundle);
    global::Xamarin.FormsMaps.Init(this, bundle);
    LoadApplication(new App());

    Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
    SetSupportActionBar(toolbar);

}

public override bool OnOptionsItemSelected(IMenuItem item)
{
    //Placed a debugger here
    // check if the current item id is equals to the back button id
    if (item.ItemId == 16908332)
    {
        // retrieve the current xamarin forms page instance
        var currentpage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault() as NavBackButtonContentPage;

        // check if the page has subscribed to the custom back button event
        if (currentpage?.CustomBackButtonAction != null)
        {
            // invoke the Custom back button action
            currentpage?.CustomBackButtonAction.Invoke();
            // and disable the default back button action
            return false;
        }

        // if its not subscribed then go ahead with the default back button action
        return base.OnOptionsItemSelected(item);
    }
    else
    {
        // since its not the back button click, pass the event to the base
        return base.OnOptionsItemSelected(item);
    }
}

I am using it inside MasterDetailPage.

Body:
I also had the same issue and found the solution. The issue is MainActivity was sub-classing from the FormsAppCompactActivity instead of old FormsApplicationActivity which was the previous parent class for MainActivity. So assume bug on new FormsAppCompactActivity

The issue will be fixed when you add following lines to MainActivity OnCreate method (after the  LoadApplication(new App()); line)

Android.Support.V7.Widget.Toolbar toolbar
                = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

Referenced URL and thread as follows
https://forums.xamarin.com/discussion/comment/218663

https://theconfuzedsourcecode.wordpress.com/2017/03/02/formsappcompatactivity-is-not-calling-onoptionsitemselected-xamarin-android/


问:
"contains" keyword with bracketed if-statement
```<code>if clip contains Cho,oos,ose,wor,ord
          ...
</code>```

How do I convert the above legacy style to non-legacy style:

```<code>if(...)
{
      ...
}
</code>```

For example:

```<code>clip = %clipboard%
</code>```

can be converted to non-legacy

```<code>clip := clipboard
</code>```

I tried

```<code>if (clip contains "Cho","oos","ose","wor","ord")
</code>```

but it doesn't seem to work.

答:
This seems to work fine:</p>

```<code>var := "schwurtzen"
if var contains % "wurt"
    MsgBox true
else
    MsgBox false
</code>```

Body:
if clip contains Cho,oos,ose,wor,ord
          ...

How do I convert the above legacy style to non-legacy style:

if(...)
{
      ...
}

For example:

clip = %clipboard%

can be converted to non-legacy

clip := clipboard

I tried

if (clip contains "Cho","oos","ose","wor","ord")

but it doesn't seem to work.

Body:
This seems to work fine:

var := "schwurtzen"
if var contains % "wurt"
    MsgBox true
else
    MsgBox false


问:
what is the postgresql query to find the timestamp without time zone

select now();
               now
----------------------------------
 2019-06-01 16:10:19.893354+05:30
```

I want only date and time without timezone.What is the query to get today's date and time.eg: 2019-06-01 16:10:19

答:
You can cast the value:

```<code>select CAST(now() as timestamp without time zone)
</code>```

If you don't want the milliseconds, you can use to_char():

```<code>select to_char(CAST(now() as timestamp without time zone), 'YYYY-MM-DD HH24:MI:SS')
</code>```

Body:
select now();
               now
----------------------------------
 2019-06-01 16:10:19.893354+05:30

I want only date and time without timezone.What is the query to get today's date and time.eg: 2019-06-01 16:10:19

Body:
You can cast the value:

select CAST(now() as timestamp without time zone)

If you don't want the milliseconds, you can use to_char():

select to_char(CAST(now() as timestamp without time zone), 'YYYY-MM-DD HH24:MI:SS')


问:
Mapping a 'fake' object in SQLAlchemy
I'm not sure what this is called since it is new to me, but here is what I want to do:

I have two tables in my database: TableA and TableB.  TableA has pk a_id and another field called a_code.  TableB has pk b_id and another field called b_code.

I have these tables mapped in my sqlalchemy code and they work fine.  I want to create a third object called TableC that doesn't actually exist in my database, but that contains combinations of a_code and b_code, something like this:

```<code>class TableC:
  a_code = String
  b_code = String
</code>```

Then I'd like to query TableC like:

```<code>TableC.query.filter(and_(
        TableC.a_code == x,
        TableC.b_code == y)).all()
</code>```

Question 1) Does this type of thing have a name? 2) How do I do the mapping (using declarative would be nice)?

答:
There isn't really a concept of 'virtual tables', but it is possible to send a single query that 'joins' the data from multiple tables.  This is probably as close as you can get to what you want.

For example, one way to do this in sqlalchemy/elixir would be (and this isn't far off from what you've shown, we're just not querying a 'virtual' table):

```<code>result = session.query(TableA, TableB).filter(TableA.a_code==x).filter(TableB.b_code==y).all()
</code>```

This is similar to an SQL inner join, with some qualifying conditions in the filter statements. This isn't going to give you an sqlalchemy table object, but will give you a list of objects from each real table.

ContentLicense: CC BY-SA 3.0

Title: Mapping a 'fake' object in SQLAlchemy

Body:
I'm not sure what this is called since it is new to me, but here is what I want to do:

I have two tables in my database: TableA and TableB.  TableA has pk a_id and another field called a_code.  TableB has pk b_id and another field called b_code.

I have these tables mapped in my sqlalchemy code and they work fine.  I want to create a third object called TableC that doesn't actually exist in my database, but that contains combinations of a_code and b_code, something like this:

class TableC:
  a_code = String
  b_code = String

Then I'd like to query TableC like:

TableC.query.filter(and_(
        TableC.a_code == x,
        TableC.b_code == y)).all()

Question 1) Does this type of thing have a name? 2) How do I do the mapping (using declarative would be nice)?

Body:
There isn't really a concept of 'virtual tables', but it is possible to send a single query that 'joins' the data from multiple tables.  This is probably as close as you can get to what you want.

For example, one way to do this in sqlalchemy/elixir would be (and this isn't far off from what you've shown, we're just not querying a 'virtual' table):

result = session.query(TableA, TableB).filter(TableA.a_code==x).filter(TableB.b_code==y).all()

This is similar to an SQL inner join, with some qualifying conditions in the filter statements. This isn't going to give you an sqlalchemy table object, but will give you a list of objects from each real table.


问:
Access spaCy Masked Language Model
As of v2.1, spaCy has a BERT-style language model (LM). It predicts word-vectors instead of words, so I am going to use "words" and "word vectors" interchangeably here.

I need to take a sentence with a word masked, and a list of words, and rank the words by how likely they are to appear in the masked slot. Currently I am using BERT for this (similar to bert-syntax). I would like to see if spaCy's performance on this task is acceptable. Between this file and this one I'm pretty sure it's possible to build something. However, it feels like reaching deeper into the internals of the library than I'd like.

Is there a straightforward way to interact with spaCy's masked language model?

答:
This is basically the disadvantage of the LMAO approximation. I actually hadn't realised this until it was pointed out to me by someone on the /r/machinelearning subreddit.

Because we're predicting a vector, we really only get to predict one point in the vector-space. This is really different from predicting a distribution over the words. Imagine we had a gap like The __ of corn. Let's say a good distribution of fillers for that would be {kernel, ear, piece}. The vectors for these words aren't especially close, as the word2vec algorithm is constructing a vector space based on all contexts of the words, and the words are only interchangeable in this context. In the vast majority of uses of piece, the word ear would be a really bad substitution.

If the likely fillers aren't close together in the vector-space, there will be no way for the LMAO model to return you an answer that corresponds to that set of words.

If you only need the 1-best answer, the algorithm in spacy pretrain has a good chance of giving it to you. But if you need the distribution, the approximation breaks down, and you should use something like BERT.

Title: Access spaCy Masked Language Model


问:
Flutter - Sorting Cloud Firestore
I am trying to sort the listview that is coming in. Since this listview is images, I added a number to the firestore object so I can sort ascending.

I cannot seem to get the items to sort, and I am sure its how I built the app.

I tried to add the .orderBy() to the collection, however its says Query is not a type of CollectionReference.

Here is my page

```<code>import 'package:flutter/material.dart';
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';

class Events extends StatefulWidget {
  @override
  _EventsState createState() => _EventsState();
}

class _EventsState extends State<Events> {
  StreamSubscription<QuerySnapshot> subscription;

  List<DocumentSnapshot> snapshot;

  CollectionReference collectionReference =
  Firestore.instance.collection("Events");

  @override

  void initState() {
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        snapshot = datasnapshot.documents;
      });
    });
    super.initState();
  }

//  passData(DocumentSnapshot snap) {
//    Navigator.of(context).push(
//        MaterialPageRoute(builder: (context) => EventPage(snapshot: snap,)));
//  }

  Widget build(BuildContext context) {
    return Scaffold(
         backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            height: 200,
            decoration: BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage("assets/images/events.jpg"),
              ),
            ),
          ),
          Divider(
            color: Colors.black,
          ),
          Expanded(
            child: ListView.separated(separatorBuilder: (context, index) => Divider(color: Colors.black12,
    ), itemCount: snapshot.length,
    itemBuilder: (context, index){
              return Card(
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 210,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      fit: BoxFit.fill,
                      image: NetworkImage(snapshot[index].data["image"]),
                    ),
                  ),
                ),

              );
    }

          ))
        ],
      ),
    );
  }
}
</code>```

I really would like to sort these images by predetermined numbers in teh database.

答:
I think it's just a type error you introduces by a simple oversight. (Please, next time append the error case for you app, I am guessing here.)

You have:

CollectionReference collectionReference = Firestore.instance.collection("Events");
```

<p>With <code>orderBy</code>, you should have:</p>

<pre class="lang-dart prettyprint-override"><code>Query collectionReference = Firestore.instance.collection("Events").orderBy('field');
</code>```

orderBy should returns a Query, you can no longer store it as a CollectionReference.

Title: Flutter - Sorting Cloud Firestore

Body:
I am trying to sort the listview that is coming in. Since this listview is images, I added a number to the firestore object so I can sort ascending.

I cannot seem to get the items to sort, and I am sure its how I built the app.

I tried to add the .orderBy() to the collection, however its says Query is not a type of CollectionReference.

Here is my page

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';

class Events extends StatefulWidget {
  @override
  _EventsState createState() => _EventsState();
}

class _EventsState extends State<Events> {
  StreamSubscription<QuerySnapshot> subscription;

  List<DocumentSnapshot> snapshot;

  CollectionReference collectionReference =
  Firestore.instance.collection("Events");

  @override

  void initState() {
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        snapshot = datasnapshot.documents;
      });
    });
    super.initState();
  }

//  passData(DocumentSnapshot snap) {
//    Navigator.of(context).push(
//        MaterialPageRoute(builder: (context) => EventPage(snapshot: snap,)));
//  }

  Widget build(BuildContext context) {
    return Scaffold(
         backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            height: 200,
            decoration: BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage("assets/images/events.jpg"),
              ),
            ),
          ),
          Divider(
            color: Colors.black,
          ),
          Expanded(
            child: ListView.separated(separatorBuilder: (context, index) => Divider(color: Colors.black12,
    ), itemCount: snapshot.length,
    itemBuilder: (context, index){
              return Card(
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 210,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      fit: BoxFit.fill,
                      image: NetworkImage(snapshot[index].data["image"]),
                    ),
                  ),
                ),

              );
    }

          ))
        ],
      ),
    );
  }
}

I really would like to sort these images by predetermined numbers in teh database.

Body:
I think it's just a type error you introduces by a simple oversight. (Please, next time append the error case for you app, I am guessing here.)

You have:

CollectionReference collectionReference = Firestore.instance.collection("Events");

With orderBy, you should have:

Query collectionReference = Firestore.instance.collection("Events").orderBy('field');

orderBy should returns a Query, you can no longer store it as a CollectionReference.


问:
How to pass vuejs html template as slot and access from data or method
I have a component like this:

<my-dropzone value:"....">

upload

your files

</my-dropzone>

```

<p>and my vuejs component is:</p>

```<template>

        <slot></slot>

</template>

```

Now I want to get slot html data and assign to some local variable of component and also use in method. Is it possible? Is there any better solution to pass html to data variable

答:
You can use Vue.js vm.$slots to access the slot children as HTML nodes. It is the only recommended way. Official Vue.js docs really explain it well.

You can use render() function for your components instead of template. Slots are designed to be used effectively with a render function. Without render function, using vm.$slots is not really that useful.

Long explanation:

Vue slots are not designed to work the way you need. Imagine slots as a rendering area. Also, a slot doesn't really contain HTML as a string. It is already passed from virtual-dom and rendered as HTMLElements on screen. By the time code is processed, html as a string has transformed into a render function.

Alternately, If you need to really access the underlying HTML nodes, then consider using plain DOM API like querySelector(), etc. As far as the $refs is concerned, Content within the slot is owned by the parent component and thus you cannot use it.

Body:
I have a component like this:

<my-dropzone value:"....">

upload

your files

</my-dropzone>

and my vuejs component is:

<template>

        <slot></slot>

</template>

Now I want to get slot html data and assign to some local variable of component and also use in method. Is it possible? Is there any better solution to pass html to data variable


问:
How should I be assigning names to sprites from a sprite sheet?
I know how to load a sprite sheet, clip the images and return a list of those images, but I like to refer to my sprites by name rather than index, to keep the code readable and manageable, but it's sometimes long and tedious writing out lists of sprite names.

I usually create a dictionary, and refer to the sprite I need by name, but I wondered if I should be hard-coding the names?

This is what I usually do:

sprites = load_spritesheet('spr_buttons.png', (64, 64))
BUTTON_NAMES = ['start', 'start_hover', 'start_click', 'back', 'back_hover',
                'back_click', 'skip', 'skip_hover', 'skip_click', 'exit',
                'exit_hover', 'exit_click', 'check', 'check_hover',
                'check_click', 'blank']
spr_buttons = {}
for index, sprite in enumerate(sprites):
    spr_buttons[BUTTON_NAMES[index]] = sprite
```

<p>Using these button sprites as the example, I also have a button class and create a new instance for each button, passing in the name of the sprite.</p>

<p>This works fine, but I want to find a better way. Do I create a .txt file to accompany my sprite sheets and get the names from that? Or do I use a keyword + index number assigned to each sprite (e.g. <code>button_1</code>, <code>button_2</code> etc.)?</p>

<p>Here is my <code>NewButton</code> class:</p>

```import pygame

class NewButton:
    """Create and maintain a new button."""`

    def __init__(self, name, sprites, x_pos, y_pos, size):
        """Initialise a new button instance.

        :param name:    The name of the button from the dictionary.
        :param sprites: A dictionary of button sprite images.
        :param x_pos:   The x position of the button image.
        :param y_pos:   The y position of the button image.
        :param size:    The squared size of the button image.
        """
        self.img_normal = sprites[name]
        self.img_hover = sprites[name + '_hover']
        self.img_click = sprites[name + '_click']
        self.rect = pygame.Rect(x_pos, y_pos, size, size)
        self.image = self.img_normal
        self.hover = False
        self.clicked = False
        self.execute = False
        self.max_timer = 20
        self.click_timer = 0

    def update(self, delta):
        """Update the button instance.

        :param delta: A multiplier based on real time between updates.
        """
        if self.clicked:
            self.click_timer += delta
            if self.click_timer < self.max_timer / 2:
                self.image = self.img_click
            elif self.click_timer >= self.max_timer:
                self.clicked = False
                self.click_timer = 0
                self.image = self.img_normal
                self.execute = True
            else:
                self.image = self.img_normal
        else:
            mx, my = pygame.mouse.get_pos()
            if self.rect.collidepoint(mx, my):
                self.image = self.img_hover
                self.hover = True
            else:
                self.image = self.img_normal
                self.hover = False

    def click(self):
        """Set the button as being clicked."""
        self.clicked = True

    def reset(self):
        """Reset the execute status of the button."""
        self.execute = False
```

答:
You can do it in a simpler way using the zip() function to create the dictionary:

```<code>sprites = load_spritesheet('spr_buttons.png', (64, 64))

BUTTON_NAMES = ['start', 'start_hover', 'start_click',
                'back', 'back_hover', 'back_click',
                'skip', 'skip_hover', 'skip_click',
                'exit', 'exit_hover', 'exit_click',
                'check', 'check_hover', 'check_click',
                'blank']

spr_buttons = dict(zip(BUTTON_NAMES, sprites))
</code>```

Body:
I know how to load a sprite sheet, clip the images and return a list of those images, but I like to refer to my sprites by name rather than index, to keep the code readable and manageable, but it's sometimes long and tedious writing out lists of sprite names.

I usually create a dictionary, and refer to the sprite I need by name, but I wondered if I should be hard-coding the names?

This is what I usually do:

sprites = load_spritesheet('spr_buttons.png', (64, 64))
BUTTON_NAMES = ['start', 'start_hover', 'start_click', 'back', 'back_hover',
                'back_click', 'skip', 'skip_hover', 'skip_click', 'exit',
                'exit_hover', 'exit_click', 'check', 'check_hover',
                'check_click', 'blank']
spr_buttons = {}
for index, sprite in enumerate(sprites):
    spr_buttons[BUTTON_NAMES[index]] = sprite

Using these button sprites as the example, I also have a button class and create a new instance for each button, passing in the name of the sprite.

This works fine, but I want to find a better way. Do I create a .txt file to accompany my sprite sheets and get the names from that? Or do I use a keyword + index number assigned to each sprite (e.g. button_1, button_2 etc.)?

Here is my NewButton class:

import pygame

class NewButton:
    """Create and maintain a new button."""`

    def __init__(self, name, sprites, x_pos, y_pos, size):
        """Initialise a new button instance.

        :param name:    The name of the button from the dictionary.
        :param sprites: A dictionary of button sprite images.
        :param x_pos:   The x position of the button image.
        :param y_pos:   The y position of the button image.
        :param size:    The squared size of the button image.
        """
        self.img_normal = sprites[name]
        self.img_hover = sprites[name + '_hover']
        self.img_click = sprites[name + '_click']
        self.rect = pygame.Rect(x_pos, y_pos, size, size)
        self.image = self.img_normal
        self.hover = False
        self.clicked = False
        self.execute = False
        self.max_timer = 20
        self.click_timer = 0

    def update(self, delta):
        """Update the button instance.

        :param delta: A multiplier based on real time between updates.
        """
        if self.clicked:
            self.click_timer += delta
            if self.click_timer < self.max_timer / 2:
                self.image = self.img_click
            elif self.click_timer >= self.max_timer:
                self.clicked = False
                self.click_timer = 0
                self.image = self.img_normal
                self.execute = True
            else:
                self.image = self.img_normal
        else:
            mx, my = pygame.mouse.get_pos()
            if self.rect.collidepoint(mx, my):
                self.image = self.img_hover
                self.hover = True
            else:
                self.image = self.img_normal
                self.hover = False

    def click(self):
        """Set the button as being clicked."""
        self.clicked = True

    def reset(self):
        """Reset the execute status of the button."""
        self.execute = False

Body:
You can do it in a simpler way using the zip() function to create the dictionary:

sprites = load_spritesheet('spr_buttons.png', (64, 64))

BUTTON_NAMES = ['start', 'start_hover', 'start_click',
                'back', 'back_hover', 'back_click',
                'skip', 'skip_hover', 'skip_click',
                'exit', 'exit_hover', 'exit_click',
                'check', 'check_hover', 'check_click',
                'blank']

spr_buttons = dict(zip(BUTTON_NAMES, sprites))


问:
UIScrollView not scrolling in Swift
My UIScrollView won't scroll down. I don't know why. I already followed Apple documentation regarding to this issue.</p>

```<code>@IBOutlet weak var scroller: UIScrollView!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

}

override func viewDidLayoutSubviews() {
    scroller.scrollEnabled = true
    // Do any additional setup after loading the view
    scroller.contentSize = CGSizeMake(400, 2300)
}
</code>```

答:
FWIW, I found that I needed to use sathish's solution from above, though it was insufficient to effect the intervention in viewDidAppear alone. I had to instead make the adjustment for every new content assignment:

```<code>func display(pattern: Pattern) {
    let text : NSAttributedString = pattern.body()
    patternTextView.attributedText = text

    // Set the size of the view. Autolayout seems to get in the way of
    // a correct size calculation
    patternTextView.contentSize = CGSize(width: 348, height: 620)
}
</code>```

The manifest constants (yeah, I know, yuk, but it makes it easier to understand here) are from the autolayout spec.

Title: UIScrollView not scrolling in Swift

Body:
My UIScrollView won't scroll down. I don't know why. I already followed Apple documentation regarding to this issue.

@IBOutlet weak var scroller: UIScrollView!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

}

override func viewDidLayoutSubviews() {
    scroller.scrollEnabled = true
    // Do any additional setup after loading the view
    scroller.contentSize = CGSizeMake(400, 2300)
}

Body:
FWIW, I found that I needed to use sathish's solution from above, though it was insufficient to effect the intervention in viewDidAppear alone. I had to instead make the adjustment for every new content assignment:

func display(pattern: Pattern) {
    let text : NSAttributedString = pattern.body()
    patternTextView.attributedText = text

    // Set the size of the view. Autolayout seems to get in the way of
    // a correct size calculation
    patternTextView.contentSize = CGSize(width: 348, height: 620)
}

The manifest constants (yeah, I know, yuk, but it makes it easier to understand here) are from the autolayout spec.


问:
Explanation of Pkg's colors and symbols
I've looked through the docs for the Julia Pkg manager, but I couldn't see on flipping through any examples or explanations of the symbols and colors.

I may be feeling more stupid than usual this morning, but...

Does the yellow up arrow say that there is an upgrade available, or that it has been upgraded, or could be upgraded, or should be upgraded? up doesn't change anything, and st gives the same information each time I run it.

The green + sign suggest that the package has been added, but why green not white? Or is it saying the package can be added? Or that the package should be added? add changes nothing, neither does st.

The red minus sign says to me "you should delete this package". Or does it mean "it has been deleted", or that "it doesn't work"?

The only part of this output I really understand is that the BenchmarkTools package is installed and has the version v0.4.2 (and same for the other ordinary-looking entries).

Is there an explanation somewhere?

答:
A light yellow entry with an upward arrow ↑ means the package has been upgraded.

```<code>[31c24e10] ↑ Distributions v0.18.0 ⇒ v0.20.0
</code>```

A light magenta entry with an downward arrow ↓ means the package has been downgraded.

```<code>[033835bb] ↓ JLD2 v0.1.2 ⇒ v0.1.1
</code>```

A light green entry with a plus sign means the package has been added.

```<code>[c145ed77] + GenericSchur v0.2.3
</code>```

A light red entry with a minus sign means the package has been removed.

```<code>[54eb57ff] - InteractiveCodeSearch v0.3.1
</code>```

There are also light yellow entries with a tilde ~. They appear if the version of the package does not change but you pin/unpin a package (with a pin indicator), or there are changes in the package path, or in the package repo (for example when you add a package from a branch like add WebIO#master and there is a new commit to the master branch).

```<code>[033835bb] ~ JLD2 v0.1.2 ⇒ v0.1.2 ⚲
</code>```

You may also see red (not light red) entries with ? sign. Such entries implies that an unknown operation has occurred. These probably indicate an error or a case which is not handled by Pkg.

You can see how these lines are produced here.

These outputs can appear both under Updating .../Project.toml and Updating .../Manifest.toml.

Project file: a file in the root directory of a project, named
  Project.toml (or JuliaProject.toml) describing metadata about the
  project, including its name, UUID (for packages), authors, license,
  and the names and UUIDs of packages and libraries that it depends on.

Manifest file: a file in the root directory of a project, named
  Manifest.toml (or JuliaManifest.toml) describing a complete dependency
  graph and exact versions of each package and library used by a
  project.

When you add or update a package, Julia will install or update not only the package itself but also its dependencies (also considering the dependencies of other packages).

When these lines may appear below .../Project.toml and indicate changes directly to your project and when under .../Manifest.toml these indicate change in your project manifest or your Pkg dependency graph.

The st or status Pkg commands will also show the changes to your project file since the last commit (if you are in a git repo). They do not show the available updates or such.

why green not white?

Well, colors add distinction and the default terminal color is used for packages with no change in status and other things.

Title: Explanation of Pkg's colors and symbols

Body:
A light yellow entry with an upward arrow ↑ means the package has been upgraded.

[31c24e10] ↑ Distributions v0.18.0 ⇒ v0.20.0

A light magenta entry with an downward arrow ↓ means the package has been downgraded.

[033835bb] ↓ JLD2 v0.1.2 ⇒ v0.1.1

A light green entry with a plus sign means the package has been added.

[c145ed77] + GenericSchur v0.2.3

A light red entry with a minus sign means the package has been removed.

[54eb57ff] - InteractiveCodeSearch v0.3.1

There are also light yellow entries with a tilde ~. They appear if the version of the package does not change but you pin/unpin a package (with a pin indicator), or there are changes in the package path, or in the package repo (for example when you add a package from a branch like add WebIO#master and there is a new commit to the master branch).

[033835bb] ~ JLD2 v0.1.2 ⇒ v0.1.2 ⚲

You may also see red (not light red) entries with ? sign. Such entries implies that an unknown operation has occurred. These probably indicate an error or a case which is not handled by Pkg.

You can see how these lines are produced here.

These outputs can appear both under Updating .../Project.toml and Updating .../Manifest.toml.

Project file: a file in the root directory of a project, named
  Project.toml (or JuliaProject.toml) describing metadata about the
  project, including its name, UUID (for packages), authors, license,
  and the names and UUIDs of packages and libraries that it depends on.

Manifest file: a file in the root directory of a project, named
  Manifest.toml (or JuliaManifest.toml) describing a complete dependency
  graph and exact versions of each package and library used by a
  project.

When you add or update a package, Julia will install or update not only the package itself but also its dependencies (also considering the dependencies of other packages).

When these lines may appear below .../Project.toml and indicate changes directly to your project and when under .../Manifest.toml these indicate change in your project manifest or your Pkg dependency graph.

The st or status Pkg commands will also show the changes to your project file since the last commit (if you are in a git repo). They do not show the available updates or such.

why green not white?

Well, colors add distinction and the default terminal color is used for packages with no change in status and other things.


问:
Matplotlib: Update positions and velocities in quiver()
I have a large number of files that contain data from a simulation. I want to use each file to save an image of a vector field using quiver(). Unfortunately, my method is really slow.

Here is a minimal working example of my code:

```<code>import time
import numpy as np
import matplotlib.pyplot as plt

# Number of files
N = 100000

n_points = 10000

for k in range(N):
    t0 = time.time()

    fig, ax = plt.subplots(1,1, figsize=(5,5))
    ax.axis("off")

    # Get data
    data = np.random.uniform(-1,1,size=(n_points, 4))
    x,y,vx,vy = data[:,0], data[:,1], data[:,2], data[:,3]

    # Normalize and scale velocities
    norm = np.hypot(vx,vy)
    vx = vx / norm
    vy = vy / norm
    vx *= 0.05
    vy *= 0.05

    # Plot vectorfield
    ax.quiver(x, y, vx, vy, scale=1., width=0.001, units="xy")

    plt.subplots_adjust(bottom=0, right=1, top=1, left=0)
    plt.savefig("image_" + str(k) + ".png", dpi=300)
    plt.close()

    print("%.2f" % (100.*(k+1.)/N) + " %" + " %.2f" % (time.time()-t0) + " images/s", end="\r")
</code>```

Any ideas how I can speed things up? Right now I can save about one image every second. Given the large amount of data files, this takes several hours on my machine to complete.

Thank you!

EDIT

I modified the code above according to the recommendations of @ImportanceOfBeingErnest. However, the code is still really slow.

```<code>import time
import numpy as np
import matplotlib.pyplot as plt

# Number of files
N = 20

n_points = 20000

fig, ax = plt.subplots(1,1, figsize=(5,5))
ax.axis("off")
plt.subplots_adjust(bottom=0, right=1, top=1, left=0)

for k in range(N):
    t0 = time.time()

    # Get data
    data = np.random.uniform(-1,1,size=(n_points, 4))
    x,y,vx,vy = data[:,0], data[:,1], data[:,2], data[:,3]

    # Normalize and scale velocities
    norm = np.hypot(vx,vy)
    vx = vx / norm
    vy = vy / norm
    vx *= 0.05
    vy *= 0.05

    # Plot vectorfield
    q = ax.quiver(x, y, vx, vy, scale=1., width=0.001, units="xy")
    plt.savefig("image_" + str(k) + ".png", dpi=300)
    #q.remove()
    ax.clear()

    #plt.close()
    t.append(time.time()-t0)
    print("%.2f" % (100.*(k+1.)/N) + " %" + " %.2f" % (time.time()-t0) + " s/images", end="\r")
</code>```

Before any improvements it took about 1.71 seconds for one image on average. Using ax.clear() is even slower with 1.81 seconds per image. Using q.remove() is a little bit faster and results in 1.61 seconds per image. Any further suggestions?

答:
Change dpi to None that will speed up image creating by 2.</p>

```<code>plt.savefig("image_" + str(k) + ".png", dpi=None)
</code>```

Body:
I have a large number of files that contain data from a simulation. I want to use each file to save an image of a vector field using quiver(). Unfortunately, my method is really slow.

Here is a minimal working example of my code:

import time
import numpy as np
import matplotlib.pyplot as plt

# Number of files
N = 100000

n_points = 10000

for k in range(N):
    t0 = time.time()

    fig, ax = plt.subplots(1,1, figsize=(5,5))
    ax.axis("off")

    # Get data
    data = np.random.uniform(-1,1,size=(n_points, 4))
    x,y,vx,vy = data[:,0], data[:,1], data[:,2], data[:,3]

    # Normalize and scale velocities
    norm = np.hypot(vx,vy)
    vx = vx / norm
    vy = vy / norm
    vx *= 0.05
    vy *= 0.05

    # Plot vectorfield
    ax.quiver(x, y, vx, vy, scale=1., width=0.001, units="xy")

    plt.subplots_adjust(bottom=0, right=1, top=1, left=0)
    plt.savefig("image_" + str(k) + ".png", dpi=300)
    plt.close()

    print("%.2f" % (100.*(k+1.)/N) + " %" + " %.2f" % (time.time()-t0) + " images/s", end="\r")

Any ideas how I can speed things up? Right now I can save about one image every second. Given the large amount of data files, this takes several hours on my machine to complete.

Thank you!

EDIT

I modified the code above according to the recommendations of @ImportanceOfBeingErnest. However, the code is still really slow.

import time
import numpy as np
import matplotlib.pyplot as plt

# Number of files
N = 20

n_points = 20000

fig, ax = plt.subplots(1,1, figsize=(5,5))
ax.axis("off")
plt.subplots_adjust(bottom=0, right=1, top=1, left=0)

for k in range(N):
    t0 = time.time()

    # Get data
    data = np.random.uniform(-1,1,size=(n_points, 4))
    x,y,vx,vy = data[:,0], data[:,1], data[:,2], data[:,3]

    # Normalize and scale velocities
    norm = np.hypot(vx,vy)
    vx = vx / norm
    vy = vy / norm
    vx *= 0.05
    vy *= 0.05

    # Plot vectorfield
    q = ax.quiver(x, y, vx, vy, scale=1., width=0.001, units="xy")
    plt.savefig("image_" + str(k) + ".png", dpi=300)
    #q.remove()
    ax.clear()

    #plt.close()
    t.append(time.time()-t0)
    print("%.2f" % (100.*(k+1.)/N) + " %" + " %.2f" % (time.time()-t0) + " s/images", end="\r")

Before any improvements it took about 1.71 seconds for one image on average. Using ax.clear() is even slower with 1.81 seconds per image. Using q.remove() is a little bit faster and results in 1.61 seconds per image. Any further suggestions?

Body:
Change dpi to None that will speed up image creating by 2.

plt.savefig("image_" + str(k) + ".png", dpi=None)


问:
How to use another event loop in win32 gui application
I am new to win32 api progamming, and I am tring writing a xmpp client for windows platform, using win32 api and gloox xmpp library. gloox has its own event loop, while windows GUI has message loop too. I am not very clear how to use these two loops together.

From the gloox document:

Blocking vs. Non-blocking Connections
For some kind of bots a blocking connection (the default behaviour) is ideal. All the bot does is react to events coming from the server. However, for end user clients or anything with a GUI this is far from perfect.

In these cases non-blocking connections can be used. If ClientBase::connect( false ) is called, the function returnes immediately after the connection has been established. It is then the resposibility of the programmer to initiate receiving of data from the socket.

The easiest way is to call ClientBase::recv() periodically with the desired timeout (in microseconds) as parameter. The default value of -1 means the call blocks until any data was received, which is then parsed automatically.

Window message loop:

   while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
```
<p>Window proc:</p>
<pre class="lang-c prettyprint-override"><code>LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    TCHAR str[100];
    StringCbPrintf(str, _countof(str), TEXT("Message ID:%-6x:%s"), msg, GetStringMessage(msg));
    OutputDebugString(str);
    HDC hdc;
    PAINTSTRUCT ps;
    RECT rect;
    switch (msg)
    {
    case  WM_CREATE:
        return 0;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        GetClientRect(hWnd, &rect);
        DrawText(hdc, TEXT("DRAW TEXT ON CLIENT AREA"), -1, &rect, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
        EndPaint(hWnd, &ps);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    default:
        break;
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}
</code>```

gloox blocking connection

  JID jid( "jid@server/resource" );
  Client* client = new Client( jid, "password" );
  client->registerConnectionListener( this );
  client->registerPresenceHandler( this );
  client->connect();// here will enter event loop
```
<p>gloox non-blocking connection</p>
<pre class="lang-c prettyprint-override"><code>Client* client = new Client( ... );
ConnectionTCPClient* conn = new ConnectionTCPClient( client, client->logInstance(), server, port );
client->setConnectionImpl( conn );
client->connect( false );
int sock = conn->socket();
[...]
</code>```

I am not very clear how can I

call ClientBase::recv() periodically with the desired timeout (in microseconds) as parameter

With a timer ? or multi thread programming ? or there is a better solution ?

Any suggestions appreciated

Thank you

答:
The best IO strategy for that is overlapped IO. Unfortunately, the method is windows only, not supported by the cross-platform library you’ve picked.

You can use SetTimer() API, and periodically call recv() method of the library with zero timeout, in WM_TIMER handler. This will introduce extra latency (your PC receives a message but it has to wait for the next timer event to handle it), or if you’ll use small intervals like 20 ms, will consume battery on laptops or tablets.

You can use blocking API with a separate thread. More efficient performance-wise, but harder to implement, you’ll have to marshal messages and other events to the GUI thread. WM_USER+n custom windows messages is usually the best way to do that, BTW.

Body:
I am new to win32 api progamming, and I am tring writing a xmpp client for windows platform, using win32 api and gloox xmpp library. gloox has its own event loop, while windows GUI has message loop too. I am not very clear how to use these two loops together.

From the gloox document:

Blocking vs. Non-blocking Connections
For some kind of bots a blocking connection (the default behaviour) is ideal. All the bot does is react to events coming from the server. However, for end user clients or anything with a GUI this is far from perfect.

In these cases non-blocking connections can be used. If ClientBase::connect( false ) is called, the function returnes immediately after the connection has been established. It is then the resposibility of the programmer to initiate receiving of data from the socket.

The easiest way is to call ClientBase::recv() periodically with the desired timeout (in microseconds) as parameter. The default value of -1 means the call blocks until any data was received, which is then parsed automatically.

Window message loop:

   while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;

Window proc:

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    TCHAR str[100];
    StringCbPrintf(str, _countof(str), TEXT("Message ID:%-6x:%s"), msg, GetStringMessage(msg));
    OutputDebugString(str);
    HDC hdc;
    PAINTSTRUCT ps;
    RECT rect;
    switch (msg)
    {
    case  WM_CREATE:
        return 0;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        GetClientRect(hWnd, &rect);
        DrawText(hdc, TEXT("DRAW TEXT ON CLIENT AREA"), -1, &rect, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
        EndPaint(hWnd, &ps);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    default:
        break;
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

gloox blocking connection

  JID jid( "jid@server/resource" );
  Client* client = new Client( jid, "password" );
  client->registerConnectionListener( this );
  client->registerPresenceHandler( this );
  client->connect();// here will enter event loop

gloox non-blocking connection

Client* client = new Client( ... );
ConnectionTCPClient* conn = new ConnectionTCPClient( client, client->logInstance(), server, port );
client->setConnectionImpl( conn );
client->connect( false );
int sock = conn->socket();
[...]

I am not very clear how can I

call ClientBase::recv() periodically with the desired timeout (in microseconds) as parameter

With a timer ? or multi thread programming ? or there is a better solution ?

Any suggestions appreciated

Thank you


问:
Node.js error now occurs after upgrading Ubuntu
I'm building Ubuntu's virtual environment on Windows 10 using VirtualBox and Vagrant.

After updating from Ubuntu 14.04 to Ubuntu 16.04.6 LTS yesterday, an error occurred when running node.js.

I get an error when I try to launch a web application as follows:

```<code>$ PORT=8000 npm start

/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57
log.progressEnabled = log.gauge.isEnabled()
                                ^

TypeError: log.gauge.isEnabled is not a function
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57:33)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:22:13
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:152:3)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
</code>```

This error did not occur before the Ubuntu version upgrade.

How can I solve this error?

I tried the following, but it did not work well.

```<code>$ rm -rf node_modules
$ npm install --reset-cache
/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57
log.progressEnabled = log.gauge.isEnabled()
                                ^

TypeError: log.gauge.isEnabled is not a function
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57:33)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:22:13
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:152:3)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
</code>```

答: try removing node_modules and run npm install --reset-cache hope that helps

Body:
I'm building Ubuntu's virtual environment on Windows 10 using VirtualBox and Vagrant.

After updating from Ubuntu 14.04 to Ubuntu 16.04.6 LTS yesterday, an error occurred when running node.js.

I get an error when I try to launch a web application as follows:

$ PORT=8000 npm start

/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57
log.progressEnabled = log.gauge.isEnabled()
                                ^

TypeError: log.gauge.isEnabled is not a function
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57:33)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:22:13
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:152:3)
    at Module._compile (internal/modules/cjs/loader.js:774:30)

This error did not occur before the Ubuntu version upgrade.

How can I solve this error?

I tried the following, but it did not work well.

$ rm -rf node_modules
$ npm install --reset-cache
/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57
log.progressEnabled = log.gauge.isEnabled()
                                ^

TypeError: log.gauge.isEnabled is not a function
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npmlog/log.js:57:33)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:22:13
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:152:3)
    at Module._compile (internal/modules/cjs/loader.js:774:30)


问:
I can't get infinite nested loop within onCreate() method
I'm new to Android Studio programming and I'd like to know what is the substitute for code below..
I'm trying to iterate an infinite loop that has a nested one and it seem to not work. The application still crushes when it comes to that loop.

I also tried to use non-infinite loop without nesting another inside of it.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);

    while (state) {
        int i = 0;

        while (i < person[i].length) {
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    someTextView.setText(person[i].getName());
                }
            });
        }
        i++;
    }
}
</code>```

This Logcat below just represents the nested while loop without
the onClickListener unlike shown in code.

```<code>2019-06-01 11:59:10.695 19529-19529/com.example.app2 I/Timeline: Timeline: Activity_launch_request id:com.example.app2 time:120814793
2019-06-01 11:59:10.771 19529-19543/com.example.app2 I/art: Enter while loop.
2019-06-01 11:59:10.789 19529-19543/com.example.app2 I/art: Enter while loop.
</code>```

After entering while loop all I'm getting is a black screen on my device.

How do I  use these loops within onCreate() method?

答:
Assuming your goal is to do something repeatedly, e.g. every 1 second, you could use postDelayed(...)

```<code>// Java
Handler handler = new Handler();
int delay = 1000; // milliseconds

handler.postDelayed(new Runnable() {
    public void run() {
        // do something
        handler.postDelayed(this, delay);
    }
}, delay);
</code>```

Source: How to run a method every X seconds

Body:
I'm new to Android Studio programming and I'd like to know what is the substitute for code below..
I'm trying to iterate an infinite loop that has a nested one and it seem to not work. The application still crushes when it comes to that loop.

I also tried to use non-infinite loop without nesting another inside of it.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);

    while (state) {
        int i = 0;

        while (i < person[i].length) {
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    someTextView.setText(person[i].getName());
                }
            });
        }
        i++;
    }
}

This Logcat below just represents the nested while loop without
the onClickListener unlike shown in code.

2019-06-01 11:59:10.695 19529-19529/com.example.app2 I/Timeline: Timeline: Activity_launch_request id:com.example.app2 time:120814793
2019-06-01 11:59:10.771 19529-19543/com.example.app2 I/art: Enter while loop.
2019-06-01 11:59:10.789 19529-19543/com.example.app2 I/art: Enter while loop.

After entering while loop all I'm getting is a black screen on my device.

How do I  use these loops within onCreate() method?

Body:
Assuming your goal is to do something repeatedly, e.g. every 1 second, you could use postDelayed(...)

// Java
Handler handler = new Handler();
int delay = 1000; // milliseconds

handler.postDelayed(new Runnable() {
    public void run() {
        // do something
        handler.postDelayed(this, delay);
    }
}, delay);

Source: How to run a method every X seconds


问:
Junit - run set up method once
I set up a class with a couple of tests and rather than using @Before I would like to have a setup method that executes only once before all tests. Is that possible with Junit 4.8?

答:
I solved this problem like this:

Add to your Base abstract class (I mean abstract class where you initialize your driver in setUpDriver() method) this part of code:

```<code>private static boolean started = false;
static{
    if (!started) {
        started = true;
        try {
            setUpDriver();  //method where you initialize your driver
        } catch (MalformedURLException e) {
        }
    }
}
</code>```

And now, if your test classes will extends from Base abstract class -> setUpDriver() method will be executed before first @Test only ONE time per run.

Title: Junit - run set up method once

Body:
I solved this problem like this:

Add to your Base abstract class (I mean abstract class where you initialize your driver in setUpDriver() method) this part of code:

private static boolean started = false;
static{
    if (!started) {
        started = true;
        try {
            setUpDriver();  //method where you initialize your driver
        } catch (MalformedURLException e) {
        }
    }
}

And now, if your test classes will extends from Base abstract class -> setUpDriver() method will be executed before first @Test only ONE time per run.


问:
Getting Error with Pytube: signature = cipher.get_signature(js, stream['s']) KeyError: 's'
I have been this error when running my Pytube script:

```<code>     signature = cipher.get_signature(js, stream['s'])
     KeyError: 's'
</code>```

My code is like this:

```<code>    url = 'https://www.youtube.com/watch?v='
    train_List = []
    i = 0
    while i < len(my_list):
        if len(my_list[i]) > 6:
            urls = url + my_list[i]
            train_List.append(urls)
            yt=YouTube(train_List[i])
            t=yt.streams.filter(only_audio=True).all()
            t[0].download('/pathtofolder')
            i+=1
</code>```

I also tried:

```<code>    t=yt.streams.filter(file_extension='mp4').all()
</code>```

I altered the cipher.py and helper.py files per the recommendation here: https://github.com/nficano/pytube/issues/353#issuecomment-455116197

but it hasn't fixed the problem. After making the alterations, I got the error noted above.

Next, I ran "pip install pytube --upgrade" per some other recommendations. Still getting the KeyError after it downloads a few audio files.

I've also implemented this in mixins.py, per the github issues:

```<code>    if ('signature=' in url) or ('&sig=' in url) or ('&lsig=' in url):
</code>```

but now it's hanging after 3 uploads.

Does anyone have a fix for this?

答:
Have the same problem. If I try a second time it works most of the time...

```<code>url = 'https://www.youtube.com/watch?v=gQrkvZeE3Uc'
yt = YouTube(url)
yt.streams.filter(progressive=True, subtype='mp4').order_by('resolution').desc().last().download()
</code>```

Thanks for any help

Body:
I have been this error when running my Pytube script:

     signature = cipher.get_signature(js, stream['s'])
     KeyError: 's'

My code is like this:

    url = 'https://www.youtube.com/watch?v='
    train_List = []
    i = 0
    while i < len(my_list):
        if len(my_list[i]) > 6:
            urls = url + my_list[i]
            train_List.append(urls)
            yt=YouTube(train_List[i])
            t=yt.streams.filter(only_audio=True).all()
            t[0].download('/pathtofolder')
            i+=1

I also tried:

    t=yt.streams.filter(file_extension='mp4').all()

I altered the cipher.py and helper.py files per the recommendation here: https://github.com/nficano/pytube/issues/353#issuecomment-455116197

but it hasn't fixed the problem. After making the alterations, I got the error noted above.

Next, I ran "pip install pytube --upgrade" per some other recommendations. Still getting the KeyError after it downloads a few audio files.

I've also implemented this in mixins.py, per the github issues:

    if ('signature=' in url) or ('&sig=' in url) or ('&lsig=' in url):

but now it's hanging after 3 uploads.

Does anyone have a fix for this?

Body:
Have the same problem. If I try a second time it works most of the time...

url = 'https://www.youtube.com/watch?v=gQrkvZeE3Uc'
yt = YouTube(url)
yt.streams.filter(progressive=True, subtype='mp4').order_by('resolution').desc().last().download()

Thanks for any help


问:
What is the best way to structure this database?
So I am in the process of building a database from my clients data. Each month they create roughly 25 csv's, which are unique by their topic and attributes, but they all have 1 thing in common; a registration number.

The registration number is the only common variable across all of these csv's.

My task is to move all of this into a database, for which I am leaning towards postgres (If anyone believes nosql would be best for this then please shout out!).

The big problem; structuring this within a database. Should I create 1 table per month that houses all the data, with column 1 being registration and column 2-200 being the attributes? Or should put all the csv's into postgres as they are, and then join them later?

I'm struggling to get my head around the method to structure this when there will be monthly updates to every registration, and we dont want to destroy historical data - we want to keep it for future benchmarks.

I hope this makes sense - I welcome all suggestions!

Thank you.

答:
There are some ways where your question is too broad and asking for an opinion (SQL vs NoSQL).

However, the gist of the question is whether you should load your data one month at a time or into a well-developed data model.  Definitely the latter.

My recommendation is the following.

First, design the data model around how the data needs to be stored in the database, rather than how it is being provided.  There may be one table per CSV file.  I would be a bit surprised, though.  Data often wants to be restructured.

Second, design the archive framework for the CSV files.
 You should archive all the incoming files in a nice directory structure with files from each month.  This structure should be able to accommodate multiple uploads per month, either for all the files or some of them.  Mistakes happen and you want to be sure the input data is available.

Third, copy (this is the Postgres command) the data into staging tables.  This is the beginning of the monthly process.

Fourth, process the data -- including doing validation checks to load it into your data model.

There may be tweaks to this process, based on questions such as:

Does the data need to be available 24/7 even during the  upload process?

Does a validation failure in one part of the data prevent uploading any data?

Are SQL checks (referential integrity and check) sufficient for validating the data?

Do you need to be able to "rollback" the system to any particular update?

These are just questions that can guide your implementation.  They are not intended to be answered here.


问:
Acquiring Text of a label from scene1 to scene2 Unity
I have created a simple 2d card game in Unity , While the user is playing the game , certain information is getting captured like (score,tries,time), When the user wins or loses the game then the appropriate scene (game over or Win scene) is getting triggered, in these 2 scenes id like to copy the info from the score, tries, time fields of the game to the appropriate labels of gameOver or Win, But it seems I'm doing something wrong..

I tried to find similar questions on StackOverflow, Youtube, the web; I checked the documentation and I tried different approaches.

Here is the code I'm working with at the moment, which seems totally correct to me, I don't get any errors, just nothings appears in the labels.

```<code>'''
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class win_results : MonoBehaviour
{
    // public options script;

    public Text score_final_text;
    public Text tries_final_text;
    public Text time_final_text;

    public void player_win_results()
    {
        // script = a.getComponent<options>();

        if (options.user_lvl_choice=="easy")
        {
            GameObject tries_final = GameObject.Find("tries_text_lvl1"); //finds the object named score_results
            tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject time_final = GameObject.Find("TimeCounter_lvl1"); //finds the object named score_results
            time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject score_final = GameObject.Find("score_lvl1"); //finds the object named score_results
            score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
        }
        else if (options.user_lvl_choice == "hard")
        {
            GameObject tries_final = GameObject.Find("tries_text_lvl2"); //finds the object named score_results
            tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject time_final = GameObject.Find("TimeCounter_lvl2"); //finds the object named score_results
            time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject score_final = GameObject.Find("score_lvl2"); //finds the object named score_results
            score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
        }
    }
</code>```

As the code above shows I'm using GameObject.Find as the documentation states, I have double checked the names and typos, the scripts are correctly attached, I get no errors in the output, just nothing happens.

As you can see above I have added an extra "a" character at the end for debugging purposes, the "a" character also doesn't appear in the output, meaning that the gameObject find doesn't work correctly in my example.

What am I doing wrong?

Thanks in advance.

答:
When you load a scene without the second parameter

```<code>SceneManager.LoadScene("scene2");
</code>```

The old scene will be destroyed, all the GameObjects in that scene will also be destroyed except you've called DontDestroyOnLoad on it.

So if you haven't done this job yet, what you get in the new scene are empty data. You can print the values to check.

The easiest way to pass data through scenes is use static field. Create a class and add some static fields:

```<code>class Global
{
     public static string user_lvl_choice;
     public static string tries_final;
     ....
}
</code>```

Then you can set or get these values from any scene.

```<code>Global.user_lvl_choice = "easy"
print(Global.user_lvl_choice);
</code>```

Read more:

static

SceneManager.LoadScene

Object.DontDestroyOnLoad

Body:
I have created a simple 2d card game in Unity , While the user is playing the game , certain information is getting captured like (score,tries,time), When the user wins or loses the game then the appropriate scene (game over or Win scene) is getting triggered, in these 2 scenes id like to copy the info from the score, tries, time fields of the game to the appropriate labels of gameOver or Win, But it seems I'm doing something wrong..

I tried to find similar questions on StackOverflow, Youtube, the web; I checked the documentation and I tried different approaches.

Here is the code I'm working with at the moment, which seems totally correct to me, I don't get any errors, just nothings appears in the labels.

'''
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class win_results : MonoBehaviour
{
    // public options script;

    public Text score_final_text;
    public Text tries_final_text;
    public Text time_final_text;

    public void player_win_results()
    {
        // script = a.getComponent<options>();

        if (options.user_lvl_choice=="easy")
        {
            GameObject tries_final = GameObject.Find("tries_text_lvl1"); //finds the object named score_results
            tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject time_final = GameObject.Find("TimeCounter_lvl1"); //finds the object named score_results
            time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject score_final = GameObject.Find("score_lvl1"); //finds the object named score_results
            score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
        }
        else if (options.user_lvl_choice == "hard")
        {
            GameObject tries_final = GameObject.Find("tries_text_lvl2"); //finds the object named score_results
            tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject time_final = GameObject.Find("TimeCounter_lvl2"); //finds the object named score_results
            time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject score_final = GameObject.Find("score_lvl2"); //finds the object named score_results
            score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
        }
    }

As the code above shows I'm using GameObject.Find as the documentation states, I have double checked the names and typos, the scripts are correctly attached, I get no errors in the output, just nothing happens.

As you can see above I have added an extra "a" character at the end for debugging purposes, the "a" character also doesn't appear in the output, meaning that the gameObject find doesn't work correctly in my example.

What am I doing wrong?

Thanks in advance.

Body:
When you load a scene without the second parameter

SceneManager.LoadScene("scene2");

The old scene will be destroyed, all the GameObjects in that scene will also be destroyed except you've called DontDestroyOnLoad on it.

So if you haven't done this job yet, what you get in the new scene are empty data. You can print the values to check.

The easiest way to pass data through scenes is use static field. Create a class and add some static fields:

class Global
{
     public static string user_lvl_choice;
     public static string tries_final;
     ....
}

Then you can set or get these values from any scene.

Global.user_lvl_choice = "easy"
print(Global.user_lvl_choice);

Read more:

static

SceneManager.LoadScene

Object.DontDestroyOnLoad


问:
Gstreamer or VLC? For desktop and mobile platforms?
Is there any cross platform binaries available for Gstreamer to install it via Web start or Jnlp?

Such as VLC seems almost have all platform compatibility but it does not provide Gst and commands are completely different.

$gst-inspect filesrc missing
$gst-inspect sdp missing
$gst-inspect other codecs missing
- lot of missing in other platforms or its bug in other platforms?

note: I need to port Gstreamer from Linux working model to Iphone, Nokia, Blackberry, Symbian, Atom machine, Arm processors, Ipad, Meego, Windows/Mac/Bsd. Alternative of Gstreamer in such wide crossplatform is also a choice to ignore using Gstreamer, its good but very small future. Also the community seems dont have any action to make it happen, so as a developer it looks like loneliness in the big world

答:
If you want pre-made crossplatform binaries of GStreamer the simplest solution is to get the Media SDK from Entropy Wave:

http://entropywave.com/products/entropy-wave-media-sdk/


问:
Construct a Doc object with labeled offset data
I have a labeled dataset in the spacy offset format.

e.g.:
('I love Berlin!', {'entities': [(7, 13, 'CITY')]})

My goal is to convert the format to the CONLL column format.

e.g.:
I O
love O
Berlin CITY
! O

Is there a way to construct a spacy Doc object with only using the labeled data in offset format? If I can construct a Doc object, it should be easy to achieve my goal using this code.

Thank you in advance

答:
You might want to check out the GoldParse utility functions that can convert entity offsets to BILUO tags or spaCy Span objects. For instance, the biluo_tags_from_offsets helper takes a Doc object and a list of entity offsets and returns the BILUO tags for the tokens. For example:

from spacy.lang.en import English  # Or whichever language you need
from spacy.gold import biluo_tags_from_offsets

nlp = English()

YOUR_DATA = [
    ('I love Berlin!', {'entities': [(7, 13, 'CITY')]})
]

for text, annotations in YOUR_DATA:
    offsets = annotations["entities"]
    doc = nlp(text)
    tags = biluo_tags_from_offsets(doc, offsets)
    print([token.text for token in doc], tags)
```

```['I', 'love', 'Berlin', '!'] ['O', 'O', 'U-CITY', 'O']
```

This is already very close to the output you're looking for. If the label is not O, you can split on the - and you have the entity label for the token at that position.

Body:
You might want to check out the GoldParse utility functions that can convert entity offsets to BILUO tags or spaCy Span objects. For instance, the biluo_tags_from_offsets helper takes a Doc object and a list of entity offsets and returns the BILUO tags for the tokens. For example:

from spacy.lang.en import English  # Or whichever language you need
from spacy.gold import biluo_tags_from_offsets

nlp = English()

YOUR_DATA = [
    ('I love Berlin!', {'entities': [(7, 13, 'CITY')]})
]

for text, annotations in YOUR_DATA:
    offsets = annotations["entities"]
    doc = nlp(text)
    tags = biluo_tags_from_offsets(doc, offsets)
    print([token.text for token in doc], tags)

['I', 'love', 'Berlin', '!'] ['O', 'O', 'U-CITY', 'O']

This is already very close to the output you're looking for. If the label is not O, you can split on the - and you have the entity label for the token at that position.


问:
Microsoft SQL Server Management Studio Setup Blocked
I have installed SQL Server 2018 and want to install the Microsoft SQL Server Management Studio. The followinng problem occcurs during the installation of SSMS.

Setup Blocked
  Something has blocked setup from continuing

Click here for the log file

SSMS can only be upgraded by installing the package of the matching
  language. Please use the matching version of the installer, or
  uninstall the current version of SSMS and run SSMS setup again

I have manually deleted files under C:\Program Files (x86)\Microsoft SQL Server\140\Tools

and have restarted the computer many times.

The same problem still occurs.

How should I do to solve this problem? Please help me.

答:
Open cmd prompt as administrator, copy the below line and RUN:

```<code>reg DELETE “HKLM\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server Management Studio” /reg:32
</code>```

That WORKS FOR ME!!

Body:
Open cmd prompt as administrator, copy the below line and RUN:

reg DELETE “HKLM\SOFTWARE\WOW6432Node\Microsoft\Microsoft SQL Server Management Studio” /reg:32

That WORKS FOR ME!!