问:
Python OpenCV Error: "TypeError: Image data cannot be converted to float"

So I am trying to create a Python Program to detect similar details in two images using Python's OpenCV.  I have the two images and they are in my current directory, and they exist (see the code in lines 6-17).  But I am getting the following error when I try running it.

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

path1 = "WIN_20171207_13_51_33_Pro.jpg"
path2 = "WIN_20171207_13_51_43_Pro.jpg"

if os.path.isfile(path1):
    img1 = cv2.imread('WIN_20171207_13_51_33_Pro.jpeg',0)
else:
    print ("The file " + path1 + " does not exist.")

if os.path.isfile(path2):
    img2 = cv2.imread('WIN_20171207_13_51_43_Pro.jpeg',0)
else:
    print ("The file " + path2 + " does not exist.")

orb = cv2.ORB_create()

kpl1, des1 = orb.detectAndCompute(img1,None)
kpl2, des2 = orb.detectAndCompute(img2,None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x:x.distance)

img3 = cv2.drawMatches(img1,kpl1,img2,kpl2,matches[:10],None, flags=2)

plt.imshow (img3)
plt.show()
</code>```

Here is the error I keep on getting...

```<code>Traceback (most recent call last):

File "C:\Users\jweir\source\repos\BruteForceFeatureDetection\BruteForceFeatureDetection\BruteForceFeatureDetection.py", line 31, in <module>
    plt.imshow (img3)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in imshow
    **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
    return func(ax, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshow
    im.set_data(X)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\image.py", line 600, in set_data
    raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float
</code>```

Can someone please explpain to me why I am getting this error, what it means, and how to fix it.

答:
You're not actually reading in an image.

Check out what happens if you try to display None in matplotlib:

```<code>plt.imshow(None)
</code>```

```<code>Traceback (most recent call last):

 File ".../example.py", line 16, in <module>
   plt.imshow(None)
 File ".../matplotlib/pyplot.py", line 3157, in imshow
   **kwargs)
 File ".../matplotlib/__init__.py", line 1898, in inner
   return func(ax, *args, **kwargs)
 File ".../matplotlib/axes/_axes.py", line 5124, in imshow
   im.set_data(X)
 File ".../matplotlib/image.py", line 596, in set_data
   raise TypeError("Image data can not convert to float")

TypeError: Image data can not convert to float
</code>```

You're reading WIN_20171207_13_51_33_Pro.jpeg but you're checking if WIN_20171207_13_51_33_Pro.jpg exists. Note the different extensions. Why do you have the filename written twice (and differently)? Just simply write:

```<code>if os.path.isfile(path1):
    img1 = cv2.imread(path1, 0)
else:
    print ("The file " + path1 + " does not exist.")
</code>```

Note that even if you put a bogus file into cv2.imread(), the resulting image will just be None, which doesn't error in any of the subsequent function calls until matplotlib tries to draw it. If you print(img1) after reading, you'll see it's None and not reading properly.

Body:
So I am trying to create a Python Program to detect similar details in two images using Python's OpenCV.  I have the two images and they are in my current directory, and they exist (see the code in lines 6-17).  But I am getting the following error when I try running it.

import numpy as np
import matplotlib.pyplot as plt
import cv2
import os

path1 = "WIN_20171207_13_51_33_Pro.jpg"
path2 = "WIN_20171207_13_51_43_Pro.jpg"

if os.path.isfile(path1):
    img1 = cv2.imread('WIN_20171207_13_51_33_Pro.jpeg',0)
else:
    print ("The file " + path1 + " does not exist.")

if os.path.isfile(path2):
    img2 = cv2.imread('WIN_20171207_13_51_43_Pro.jpeg',0)
else:
    print ("The file " + path2 + " does not exist.")

orb = cv2.ORB_create()

kpl1, des1 = orb.detectAndCompute(img1,None)
kpl2, des2 = orb.detectAndCompute(img2,None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x:x.distance)

img3 = cv2.drawMatches(img1,kpl1,img2,kpl2,matches[:10],None, flags=2)

plt.imshow (img3)
plt.show()

Here is the error I keep on getting...

Traceback (most recent call last):

File "C:\Users\jweir\source\repos\BruteForceFeatureDetection\BruteForceFeatureDetection\BruteForceFeatureDetection.py", line 31, in <module>
    plt.imshow (img3)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in imshow
    **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
    return func(ax, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshow
    im.set_data(X)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\image.py", line 600, in set_data
    raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float

Can someone please explpain to me why I am getting this error, what it means, and how to fix it.

Body:
You're not actually reading in an image.

Check out what happens if you try to display None in matplotlib:

plt.imshow(None)

Traceback (most recent call last):

 File ".../example.py", line 16, in <module>
   plt.imshow(None)
 File ".../matplotlib/pyplot.py", line 3157, in imshow
   **kwargs)
 File ".../matplotlib/__init__.py", line 1898, in inner
   return func(ax, *args, **kwargs)
 File ".../matplotlib/axes/_axes.py", line 5124, in imshow
   im.set_data(X)
 File ".../matplotlib/image.py", line 596, in set_data
   raise TypeError("Image data can not convert to float")

TypeError: Image data can not convert to float

You're reading WIN_20171207_13_51_33_Pro.jpeg but you're checking if WIN_20171207_13_51_33_Pro.jpg exists. Note the different extensions. Why do you have the filename written twice (and differently)? Just simply write:

if os.path.isfile(path1):
    img1 = cv2.imread(path1, 0)
else:
    print ("The file " + path1 + " does not exist.")

Note that even if you put a bogus file into cv2.imread(), the resulting image will just be None, which doesn't error in any of the subsequent function calls until matplotlib tries to draw it. If you print(img1) after reading, you'll see it's None and not reading properly.


来源: stackexchange

问:
Overriding the .Add method in a List of... with validation
I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.

```<code>class Program
{
    static void Main(string[] args)
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory
{
    public Directory(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book
{
    public Book(string isbn, string title)
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}
</code>```

Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN number isn't unique.

I would like to extend on the .Add() method of the List and add that validation, but I'm not sure how to actually do that.

I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.

Perhaps my general approach is backwards?

Please advice.

答:
Why not this?</p>

```<code>public class Directory
{
    private List<Book> _books;

    public IEnumerable<Book> Books
    {
        {
             return _books;
        }
    }

    Public void AddBook(Book book)
    {
         //Validate
        if(valid)
        {
            _books.Add(book);
        }
    }
    //Etc
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.

class Program
{
    static void Main(string[] args)
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory
{
    public Directory(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book
{
    public Book(string isbn, string title)
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}

Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN number isn't unique.

I would like to extend on the .Add() method of the List and add that validation, but I'm not sure how to actually do that.

I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.

Perhaps my general approach is backwards?

Please advice.

Body:
Why not this?

public class Directory
{
    private List<Book> _books;

    public IEnumerable<Book> Books
    {
        {
             return _books;
        }
    }

    Public void AddBook(Book book)
    {
         //Validate
        if(valid)
        {
            _books.Add(book);
        }
    }
    //Etc
}

ContentLicense: CC BY-SA 3.0


问:
Show filtered value in Power BI
Let's say I have those values :
Data

I would like to filter on the value 4 in "Colonne 3" but then, I would like to display the other value if "Colonne 2" has other values.

For example, John and Jean have 4. But they also have other values. Then I would like to show that John has 8 and 7 and Jean has 7.

I hope that it's clear enough for you.

Thanks !

答:
It seems Power BI is limited on how well it can do this without significant coding, but I believe I've gotten you close:

Create a table visual for your data (all 4 columns), this will be Table1

Create a slicer using only column 3, (This will be Slicer1)

With Slicer1 selected go to >Format>Edit Interactions, hover over Table1 and make sure it has the 'Filter' icon selected

Create another slicer, using only column 2 (This will be Slicer2)

With Slicer2 selected, make sure the filter interaction with Slicer1 is 'None' and the filter interaction with Table1 is 'None'

Select Slicer1 again and make sure the filter interaction with Slicer2 is set to 'filter'

Make a copy of Table1, this will be Table2.

Select Slicer1 and make sure the filter interaction with Table2 is set to 'None'

Select Slicer2 and make sure the filter interaction with Table2 is set to 'filter'

So now when you choose a value in Slicer1, Table1 will be filtered to that value and Slicer2 will be filtered to the names of those values, all you need to do is select the filtered values in the slicer and this will filter Table2.

Here are some screenshots:

1. All are unfiltered

2. Filter Slicer1

3. Filter Slicer2

Please let me know if you need any further clarification.

Thanks!

Title: Show filtered value in Power BI


问:
.NET DataGridView control uses up a TON of memory for me
I am using a DataGridView control in my app at the moment and I am hitting a weird memory issue with it. I am not using DataBinding at all, just manual population. The data that I am putting in there is not a lot at all. We're talking about 20 rows by 20 columns of data at the most usually.

The work flow for that control is that I have a ComboBox with different "data sets" that I load as you pick them. So a common usage scenario is cycling through the data sets in the comboBox and seeing them render in the dataGrid. What I am seeing is that when people cycle through the data sets, the app memory usage jumps from 100MB to 1100MB instantly and then drops back down when GC kicks in. But if you cycle through the data sets quickly (i.e. faster than the GC kicks in), you will run out of memory and the app will die.

After debugging, I found that the MAIN reason the memory jumps up like crazy is that I have some columns in that datagrid that are of Image Type. I use them to display a 16x16 icon that indicates status for that row. These icons are stored in an ImageList and I just set them as the value for that cell as I populate the rows of the data grid. If I take out the images and replace them with simple text, I see absolutely no memory spikes whatsoever.

So what is the deal here? Why do images, tiny 16x16, cause the control to go crazy on my with memory like that?

More info:

My logic as you switch data sets is:

Clear all the grid rows: dataGrid.Rows.Clear();

Clear all the columns: dataGrid.Columns.Clear();

Add the columns to the dataGrid control: (most type string, and some DataGridViewImageColumn)

Add the data I have row by row using dataGrid.Rows.Add(object[] data); (the data includes the images I need to use as icons).

答: Datagridviews appear to have a memory leak when it comes to images.  Prior to loading your data, set your datagridview datasource to null, then do a dispose (with a GC.Collect()) on the datasource.</p>

ContentLicense: CC BY-SA 2.5


问:
Hibernate Criteria vs HQL: which is faster?
I have been reading some anwers, but i'm still confused. ¿Why? because the differences that you have mentioned do not relate with the performance. they are related with easy use.(Objetc(criteria) and SQL(hql)). But I would like to know if "criteria" is slower than hql for some reason.

I read this in another anwers

"There is a difference in terms of performance between HQL and criteriaQuery, everytime you fire a query using criteriaQuery, it creates a new alias for the table name which does not reflect in the last queried cache for any DB. This leads to an overhead of compiling the generated SQL, taking more time to execute." by Varun Mehta.

This is very close BUT! i read in another website(http://gary-rowe.com/agilestack/tag/hibernate/) This is no longer the case with Hibernate 3.3 and above(please read this: 9) Hibernate is slow because the SQL generated by the Criteria interface is not consistent)

I have done some test trying to find out the differences but both generate qry's and it doesn't change the alias to the table.

I'm very confused. If somebody knows the main reason please, could you help us. Thanks

答:
I'm the guy who wrote the Hibernate 3 query translator back in 2004, so I know something about how it works.

Criteria, in theory should have less overhead than an HQL query (except for named queries, which I'll get to).  This is because Criteria doesn't need to parse anything.   HQL queries are parsed with an ANTLR-based parser and then the resulting AST is turned into SQL.  However, with HQL/JPAQL you can define named queries, where the SQL is generated when the
SessionFactory starts up.  In theory, named queries have less overhead than Criteria.

So, in terms of SQL-generation overhead we have:

Named HQL/JPAQL Query - SQL generation happens only once.

Criteria - No need to parse before generating.

(non-named) HQL/JPAQL Query - Parse, then generate.

That said, choosing a query technique based on the overhead of parsing and SQL generation is probably a mistake in my opinion.  This overhead is typically very small when compared to performing a real query on a real database server with real data.   If this overhead does actually show up when profiling the app then maybe you should switch to a named query.

Here are the things I consider when deciding between Criteria and HQL/JPAQL:

First, you have to decide if you're OK with having a dependency on Hibernate-proprietary API in your code.   JPA doesn't have Criteria.

Criteria is really good at handling many optional search parameters such as you might find on a typical web page with a multi-parameter 'search form'.  With HQL, developers tend to tack on where clause expressions with StringBuilder (avoid this!).  With Criteria, you don't need to do that.  Hardik posted similar opinions.

HQL/JPAQL can be used for most other things, because the code tends to be smaller and easier for developers to understand.

Really frequent queries can be turned into named queries if you use HQL.  I prefer to do this later, after some profiling.


问:
Nested Resources w/ Rails 5.1 form_with
Per this pull request I can see that an array should be passed to form_with's model param. However, when I supply the following:

```<code><%= form_with(model: [@trip, @activity], local: true) do |f| %>
  ...
<% end %>
</code>```

Rails will return - ActionView::Template::Error (undefined method activity_path' for #<#<Class:0x007f80231e3070>:0x007f8023010dd8>):

My routes file looks like:

```<code>  resources :trips do
    resources :activities
  end
</code>```

The output of rake routes looks like -

```<code>     trip_activities GET    /trips/:trip_id/activities(.:format)          activities#index
                     POST   /trips/:trip_id/activities(.:format)          activities#create
   new_trip_activity GET    /trips/:trip_id/activities/new(.:format)      activities#new
  edit_trip_activity GET    /trips/:trip_id/activities/:id/edit(.:format) activities#edit
       trip_activity GET    /trips/:trip_id/activities/:id(.:format)      activities#show
                     PATCH  /trips/:trip_id/activities/:id(.:format)      activities#update
                     PUT    /trips/:trip_id/activities/:id(.:format)      activities#update
                     DELETE /trips/:trip_id/activities/:id(.:format)      activities#destroy
               trips GET    /trips(.:format)                              trips#index
                     POST   /trips(.:format)                              trips#create
            new_trip GET    /trips/new(.:format)                          trips#new
           edit_trip GET    /trips/:id/edit(.:format)                     trips#edit
                trip GET    /trips/:id(.:format)                          trips#show
                     PATCH  /trips/:id(.:format)                          trips#update
                     PUT    /trips/:id(.:format)                          trips#update
                     DELETE /trips/:id(.:format)                          trips#destroy
</code>```

And my activities_controller.rb -

```<code>  before_action :set_activity, only: %i[show update edit destroy]

  def edit; end

  def update
    dates = calculate_datetimes(params[:date_range])
    @activity.assign_attributes(name: params[:name],
                                summary: params[:summary],
                                start_datetime: dates[0],
                                end_datetime: dates[1])
    if @activity.save
      flash[:success] = 'Activity successfully updated'
      redirect_to(@trip)
    else
      set_humanized_daterange
      render :edit
    end
  end

  private

  def set_activity
    @activity = Activity.find(params[:id])
  end
</code>```

tl;dr - how should I setup my form_with for a nested resource, and why is this form thinking I want to use the activity_path? Ideally I'd like to move this form into a partial and use the same form for both my #new and #edit actions.

答:
Adding to max answer, if you want to support shallow nesting you can also use:

form_with(model: [@trip, @activity])

And change the render on your edit.html.erb to pass nil to trip, like:

<%= render 'form', trip: nil, activity: @activity %>

and keep it passing the trip model in your new.html.erb

Title: Nested Resources w/ Rails 5.1 form_with

Body:
Per this pull request I can see that an array should be passed to form_with's model param. However, when I supply the following:

<%= form_with(model: [@trip, @activity], local: true) do |f| %>
  ...
<% end %>

Rails will return - ActionView::Template::Error (undefined method activity_path' for #<#<Class:0x007f80231e3070>:0x007f8023010dd8>):

My routes file looks like:

  resources :trips do
    resources :activities
  end

The output of rake routes looks like -

     trip_activities GET    /trips/:trip_id/activities(.:format)          activities#index
                     POST   /trips/:trip_id/activities(.:format)          activities#create
   new_trip_activity GET    /trips/:trip_id/activities/new(.:format)      activities#new
  edit_trip_activity GET    /trips/:trip_id/activities/:id/edit(.:format) activities#edit
       trip_activity GET    /trips/:trip_id/activities/:id(.:format)      activities#show
                     PATCH  /trips/:trip_id/activities/:id(.:format)      activities#update
                     PUT    /trips/:trip_id/activities/:id(.:format)      activities#update
                     DELETE /trips/:trip_id/activities/:id(.:format)      activities#destroy
               trips GET    /trips(.:format)                              trips#index
                     POST   /trips(.:format)                              trips#create
            new_trip GET    /trips/new(.:format)                          trips#new
           edit_trip GET    /trips/:id/edit(.:format)                     trips#edit
                trip GET    /trips/:id(.:format)                          trips#show
                     PATCH  /trips/:id(.:format)                          trips#update
                     PUT    /trips/:id(.:format)                          trips#update
                     DELETE /trips/:id(.:format)                          trips#destroy

And my activities_controller.rb -

  before_action :set_activity, only: %i[show update edit destroy]

  def edit; end

  def update
    dates = calculate_datetimes(params[:date_range])
    @activity.assign_attributes(name: params[:name],
                                summary: params[:summary],
                                start_datetime: dates[0],
                                end_datetime: dates[1])
    if @activity.save
      flash[:success] = 'Activity successfully updated'
      redirect_to(@trip)
    else
      set_humanized_daterange
      render :edit
    end
  end

  private

  def set_activity
    @activity = Activity.find(params[:id])
  end

tl;dr - how should I setup my form_with for a nested resource, and why is this form thinking I want to use the activity_path? Ideally I'd like to move this form into a partial and use the same form for both my #new and #edit actions.


问:
Categorical Variables Table with Percentages in R
I have a series of categorical variables that have the response options (Favorable, Unfavorable, Neutral).

I want to create a table in R that will give the list of all 10 variables in rows (one variable per row) - with the percentage response "Favorable, Unfavorable, Neutral" in the columns.  Is this possible in R?  Ideally, I would also want to be able to group this by another categorical variable (e.g. to compare how males vs. females responded to the questions differently).

答:
Adapting lefft's example but trying to do everything in dplyr:

```<code>dat %>%
    gather(variable, value) %>%
    group_by(variable) %>%
    count(value) %>%
    mutate(pct = n / sum(n) * 100) %>%
    select(-n) %>%
    spread(value, pct)
</code>```

Body:
Adapting lefft's example but trying to do everything in dplyr:

dat %>%
    gather(variable, value) %>%
    group_by(variable) %>%
    count(value) %>%
    mutate(pct = n / sum(n) * 100) %>%
    select(-n) %>%
    spread(value, pct)


问:
Prolog - Finding alternative words (synonyms)
I'm trying to figure out how I would go about creating a synonym finder in Prolog.

I have some words here...

```<code>word(likes).
word(house).
word(chair).
</code>```

If the input was likes, I would want to output a synonym such as 'loves'. Or for house I would want to output 'home'.

I want to do this with the synonym predicate instead of adding the alternative words as a new word().

I've got as far as doing this:

```<code>synonym (house,[home]).
</code>```

I'm not sure where to go from here.

答:
If you're willing to enumerate your cases manually I would consider having a predicate that "normalizes" or "simplifies" vocabulary. For instance, something like this:

```<code>%% synonym(Synonym, CanonicalTerm) :- Synonym is a synonym for CanonicalTerm
synonym(loves,  enjoys).
synonym(likes,  enjoys).
synonym(enjoys, enjoys).
</code>```

Prologs usually index on the first argument, so this lookup will be fast (certainly faster than enumerating the whole database and doing a member/2 lookup). And then you can simply perform this step after parsing or on-demand, and code your rules around the canonical term.

WordNet probably does not consider love and like to be synonyms, really, so it is probably overkill for your needs.

Let's apply this to the earlier question:

```<code>?- phrase(sentence(np(Noun,_), vp(Verb, np(Object, _))),
   [a,teenage,boy,loves,a,big,problem]),
   synonym(Verb, CanonicalVerb),
   present(Suggestion, Noun, CanonicalVerb, Object).
Noun = boy,
Verb = loves,
CanonicalVerb = enjoys,
Object = problem,
Suggestion = 'construction kit'
</code>```

This of course assumes you update the present/4 fact as well.

Body:
I'm trying to figure out how I would go about creating a synonym finder in Prolog.

I have some words here...

word(likes).
word(house).
word(chair).

If the input was likes, I would want to output a synonym such as 'loves'. Or for house I would want to output 'home'.

I want to do this with the synonym predicate instead of adding the alternative words as a new word().

I've got as far as doing this:

synonym (house,[home]).

I'm not sure where to go from here.

Body:
If you're willing to enumerate your cases manually I would consider having a predicate that "normalizes" or "simplifies" vocabulary. For instance, something like this:

%% synonym(Synonym, CanonicalTerm) :- Synonym is a synonym for CanonicalTerm
synonym(loves,  enjoys).
synonym(likes,  enjoys).
synonym(enjoys, enjoys).

Prologs usually index on the first argument, so this lookup will be fast (certainly faster than enumerating the whole database and doing a member/2 lookup). And then you can simply perform this step after parsing or on-demand, and code your rules around the canonical term.

WordNet probably does not consider love and like to be synonyms, really, so it is probably overkill for your needs.

Let's apply this to the earlier question:

?- phrase(sentence(np(Noun,_), vp(Verb, np(Object, _))),
   [a,teenage,boy,loves,a,big,problem]),
   synonym(Verb, CanonicalVerb),
   present(Suggestion, Noun, CanonicalVerb, Object).
Noun = boy,
Verb = loves,
CanonicalVerb = enjoys,
Object = problem,
Suggestion = 'construction kit'

This of course assumes you update the present/4 fact as well.


问:
Fastest way to get all the points between two (X,Y) coordinates in python
So I have a shapely LineString:

```<code>print np.round(shapely_intersecting_lines.coords).astype(np.int)
>>> array([[ 1520, -1140],
           [ 1412,  -973]])
</code>```

This can be interpreted as a numpy array as well as seen above.

I want to get all the points in between, that is I want to get the points of the line in between as integer values. The output should be something like this:

```<code>array([[ 1520, -1140],
       [ 1519, -1139],
       [ 1519, -1138],
       ...,
       [ 1413,  -975],
       [ 1412,  -974],
       [ 1412,  -973]], dtype=int32)
</code>```

I posted this earlier in gis.stackexchange hoping there was a solution in shapely that was efficient. The solution was good at first, however, the solution is now too slow as I run this over 50000 times in my code. On my computer each loop takes about 0.03s resulting in over a day of running. It is too slow for what I need here and was hoping to see if anyone knows of a vectorized solution to this.

答:
Bresenham may be smart but I'm pretty sure brute force vectorization is faster. I've written two variants - the first is easier to read, the second is faster (80 us vs 50 us).

Update Fixed a  bug (thanks @Varlor) and added an nd variant.

```<code>import numpy as np
from timeit import timeit

def connect(ends):
    d0, d1 = np.abs(np.diff(ends, axis=0))[0]
    if d0 > d1:
        return np.c_[np.linspace(ends[0, 0], ends[1, 0], d0+1, dtype=np.int32),
                     np.round(np.linspace(ends[0, 1], ends[1, 1], d0+1))
                     .astype(np.int32)]
    else:
        return np.c_[np.round(np.linspace(ends[0, 0], ends[1, 0], d1+1))
                     .astype(np.int32),
                     np.linspace(ends[0, 1], ends[1, 1], d1+1, dtype=np.int32)]

def connect2(ends):
    d0, d1 = np.diff(ends, axis=0)[0]
    if np.abs(d0) > np.abs(d1):
        return np.c_[np.arange(ends[0, 0], ends[1,0] + np.sign(d0), np.sign(d0), dtype=np.int32),
                     np.arange(ends[0, 1] * np.abs(d0) + np.abs(d0)//2,
                               ends[0, 1] * np.abs(d0) + np.abs(d0)//2 + (np.abs(d0)+1) * d1, d1, dtype=np.int32) // np.abs(d0)]
    else:
        return np.c_[np.arange(ends[0, 0] * np.abs(d1) + np.abs(d1)//2,
                               ends[0, 0] * np.abs(d1) + np.abs(d1)//2 + (np.abs(d1)+1) * d0, d0, dtype=np.int32) // np.abs(d1),
                     np.arange(ends[0, 1], ends[1,1] + np.sign(d1), np.sign(d1), dtype=np.int32)]

def connect_nd(ends):
    d = np.diff(ends, axis=0)[0]
    j = np.argmax(np.abs(d))
    D = d[j]
    aD = np.abs(D)
    return ends[0] + (np.outer(np.arange(aD + 1), d) + (aD//2)) // aD

ends = np.array([[ 1520, -1140],
                 [ 1412,  -73]])

ends_4d = np.array([[  100, -302, 101, -49],
                    [ -100,  -45, 112, 100]])

print(connect(ends))
print(connect_nd(ends_4d))

assert np.all(connect(ends)==connect2(ends))
assert np.all(connect(ends)==connect_nd(ends))
assert np.all(connect(ends)==connect(ends[:, ::-1])[:, ::-1])
assert np.all(connect(ends)==connect(ends[::-1])[::-1])

print(timeit('f(ends)', globals={'f': connect, 'ends': ends}, number=10000)*100, 'us')
print(timeit('f(ends)', globals={'f': connect2, 'ends': ends}, number=10000)*100, 'us')
print(timeit('f(ends)', globals={'f': connect_nd, 'ends': ends}, number=10000)*100, 'us')
</code>```

Sample output:

```<code>[[ 1520 -1140]
 [ 1520 -1139]
 [ 1520 -1138]
 ...,
 [ 1412   -75]
 [ 1412   -74]
 [ 1412   -73]]
[[ 100 -302  101  -49]
 [  99 -301  101  -48]
 [  98 -300  101  -48]
 ...,
 [ -98  -47  112   99]
 [ -99  -46  112   99]
 [-100  -45  112  100]]
78.8237597000034 us
48.02509490000375 us
62.78072760001123 us
</code>```

Body:
So I have a shapely LineString:

print np.round(shapely_intersecting_lines.coords).astype(np.int)
>>> array([[ 1520, -1140],
           [ 1412,  -973]])

This can be interpreted as a numpy array as well as seen above.

I want to get all the points in between, that is I want to get the points of the line in between as integer values. The output should be something like this:

array([[ 1520, -1140],
       [ 1519, -1139],
       [ 1519, -1138],
       ...,
       [ 1413,  -975],
       [ 1412,  -974],
       [ 1412,  -973]], dtype=int32)

I posted this earlier in gis.stackexchange hoping there was a solution in shapely that was efficient. The solution was good at first, however, the solution is now too slow as I run this over 50000 times in my code. On my computer each loop takes about 0.03s resulting in over a day of running. It is too slow for what I need here and was hoping to see if anyone knows of a vectorized solution to this.

Body:
Bresenham may be smart but I'm pretty sure brute force vectorization is faster. I've written two variants - the first is easier to read, the second is faster (80 us vs 50 us).

Update Fixed a  bug (thanks @Varlor) and added an nd variant.

import numpy as np
from timeit import timeit

def connect(ends):
    d0, d1 = np.abs(np.diff(ends, axis=0))[0]
    if d0 > d1:
        return np.c_[np.linspace(ends[0, 0], ends[1, 0], d0+1, dtype=np.int32),
                     np.round(np.linspace(ends[0, 1], ends[1, 1], d0+1))
                     .astype(np.int32)]
    else:
        return np.c_[np.round(np.linspace(ends[0, 0], ends[1, 0], d1+1))
                     .astype(np.int32),
                     np.linspace(ends[0, 1], ends[1, 1], d1+1, dtype=np.int32)]

def connect2(ends):
    d0, d1 = np.diff(ends, axis=0)[0]
    if np.abs(d0) > np.abs(d1):
        return np.c_[np.arange(ends[0, 0], ends[1,0] + np.sign(d0), np.sign(d0), dtype=np.int32),
                     np.arange(ends[0, 1] * np.abs(d0) + np.abs(d0)//2,
                               ends[0, 1] * np.abs(d0) + np.abs(d0)//2 + (np.abs(d0)+1) * d1, d1, dtype=np.int32) // np.abs(d0)]
    else:
        return np.c_[np.arange(ends[0, 0] * np.abs(d1) + np.abs(d1)//2,
                               ends[0, 0] * np.abs(d1) + np.abs(d1)//2 + (np.abs(d1)+1) * d0, d0, dtype=np.int32) // np.abs(d1),
                     np.arange(ends[0, 1], ends[1,1] + np.sign(d1), np.sign(d1), dtype=np.int32)]

def connect_nd(ends):
    d = np.diff(ends, axis=0)[0]
    j = np.argmax(np.abs(d))
    D = d[j]
    aD = np.abs(D)
    return ends[0] + (np.outer(np.arange(aD + 1), d) + (aD//2)) // aD

ends = np.array([[ 1520, -1140],
                 [ 1412,  -73]])

ends_4d = np.array([[  100, -302, 101, -49],
                    [ -100,  -45, 112, 100]])

print(connect(ends))
print(connect_nd(ends_4d))

assert np.all(connect(ends)==connect2(ends))
assert np.all(connect(ends)==connect_nd(ends))
assert np.all(connect(ends)==connect(ends[:, ::-1])[:, ::-1])
assert np.all(connect(ends)==connect(ends[::-1])[::-1])

print(timeit('f(ends)', globals={'f': connect, 'ends': ends}, number=10000)*100, 'us')
print(timeit('f(ends)', globals={'f': connect2, 'ends': ends}, number=10000)*100, 'us')
print(timeit('f(ends)', globals={'f': connect_nd, 'ends': ends}, number=10000)*100, 'us')

Sample output:

[[ 1520 -1140]
 [ 1520 -1139]
 [ 1520 -1138]
 ...,
 [ 1412   -75]
 [ 1412   -74]
 [ 1412   -73]]
[[ 100 -302  101  -49]
 [  99 -301  101  -48]
 [  98 -300  101  -48]
 ...,
 [ -98  -47  112   99]
 [ -99  -46  112   99]
 [-100  -45  112  100]]
78.8237597000034 us
48.02509490000375 us
62.78072760001123 us


问:
Combining two character variables into a character list in R to be used in ggplot
I am making over 200 stacked bar graphs to illustrate plant species change over time. I need to make a named character list similar to this:

```<code>species_color_code <- c("ALDE" = "CORAL", "BRJA" = "BLUE",
"BRSQ2" = "POWDERBLUE")
</code>```

This list is used in ggplot to assign each plant species a specific color.

I have already assigned a random color to each species name (i.e ALDE, BRJA, etc) in a previous step and saved to a .csv file for future use. I have just over 400 plant species that each have a random color assigned, so making the above list by hand is going to be time consuming.

My problem is that I have not figured out how to pull the species name and color name from the CSV file, add a "=" and then  place them all into a c() function to make the correct list for ggplot.

```<code>> species_color_file
    Species   Color_Samples
1      PASM    lightsalmon2
2     PSSP6   darkturquoise
3      AGCR           snow2
4     ELLAL   antiquewhite4
5     ELTR7         tomato1
</code>```

I have looped through each row of the .csv file found each Species Name and corresponding Color. No matter how I paste(), c(), etc. I can't make them work/match what is needed for the plot.

```<code>species_color_codes <- as.character(list())
for(j in 1:nrow(species_color_file)){
    species_color_names <- paste(species_color_file$Species[j],
    species_color_file$Color_Samples[j], sep = "=", collapse = "")
    species_color_codes <- c(species_color_codes, species_color_names,
    sep = ",")
}
</code>```

What I get:

```<code>> species_color_codes
                                          sep                                               sep
     "PASM=lightsalmon2"                      ","    "PSSP6=darkturquoise"                      ","
                                              sep                                               sep
            "AGCR=snow2"                      ","    "ELLAL=antiquewhite4"                      ","
</code>```

What i need :

```<code>> species_color_codes <- c("ALDE" = "CORAL", "BRJA" = "BLUE", "BRSQ2" = "POWDERBLUE")
> species_color_codes
        ALDE         BRJA        BRSQ2
     "CORAL"       "BLUE" "POWDERBLUE"
</code>```

Thanks for any help!

答:
Try this:

```<code>species_color_codes <- species_color_file$Color_Samples
names(species_color_codes) <- species_color_file$Species
</code>```

You are attempting to create a named vector - that is, a vector where each element has a name. In your first example, you don't need the quotation around the species, as these will just be the character names.

Example:

```<code>> species_color_codes <- c(PASM  =  "lightsalmon2",
+ PSSP6 =  "darkturquoise",
+ AGCR  =         "snow2",
+ ELLAL =  "antiquewhite4",
+ ELTR7 =        "tomato1")
> species_color_codes
  PASM           PSSP6            AGCR           ELLAL           ELTR7
"lightsalmon2" "darkturquoise"  "snow2" "antiquewhite4"       "tomato1"
</code>```

You've stored the names in a data file and then read them back in. Thus, all you need to do is store the colors in a new object and then assign the species names to the names property of that object.

Body:
I am making over 200 stacked bar graphs to illustrate plant species change over time. I need to make a named character list similar to this:

species_color_code <- c("ALDE" = "CORAL", "BRJA" = "BLUE",
"BRSQ2" = "POWDERBLUE")

This list is used in ggplot to assign each plant species a specific color.

I have already assigned a random color to each species name (i.e ALDE, BRJA, etc) in a previous step and saved to a .csv file for future use. I have just over 400 plant species that each have a random color assigned, so making the above list by hand is going to be time consuming.

My problem is that I have not figured out how to pull the species name and color name from the CSV file, add a "=" and then  place them all into a c() function to make the correct list for ggplot.

> species_color_file
    Species   Color_Samples
1      PASM    lightsalmon2
2     PSSP6   darkturquoise
3      AGCR           snow2
4     ELLAL   antiquewhite4
5     ELTR7         tomato1

I have looped through each row of the .csv file found each Species Name and corresponding Color. No matter how I paste(), c(), etc. I can't make them work/match what is needed for the plot.

species_color_codes <- as.character(list())
for(j in 1:nrow(species_color_file)){
    species_color_names <- paste(species_color_file$Species[j],
    species_color_file$Color_Samples[j], sep = "=", collapse = "")
    species_color_codes <- c(species_color_codes, species_color_names,
    sep = ",")
}

What I get:

> species_color_codes
                                          sep                                               sep
     "PASM=lightsalmon2"                      ","    "PSSP6=darkturquoise"                      ","
                                              sep                                               sep
            "AGCR=snow2"                      ","    "ELLAL=antiquewhite4"                      ","

What i need :

> species_color_codes <- c("ALDE" = "CORAL", "BRJA" = "BLUE", "BRSQ2" = "POWDERBLUE")
> species_color_codes
        ALDE         BRJA        BRSQ2
     "CORAL"       "BLUE" "POWDERBLUE"

Thanks for any help!

Body:
Try this:

species_color_codes <- species_color_file$Color_Samples
names(species_color_codes) <- species_color_file$Species

You are attempting to create a named vector - that is, a vector where each element has a name. In your first example, you don't need the quotation around the species, as these will just be the character names.

Example:

> species_color_codes <- c(PASM  =  "lightsalmon2",
+ PSSP6 =  "darkturquoise",
+ AGCR  =         "snow2",
+ ELLAL =  "antiquewhite4",
+ ELTR7 =        "tomato1")
> species_color_codes
  PASM           PSSP6            AGCR           ELLAL           ELTR7
"lightsalmon2" "darkturquoise"  "snow2" "antiquewhite4"       "tomato1"

You've stored the names in a data file and then read them back in. Thus, all you need to do is store the colors in a new object and then assign the species names to the names property of that object.


问:
Referencing data from sheet one to sheet 2
I have a large spread sheet with multiple pages, columns and rows on each page.

on page Teams, I have row 3 column B as rider #12, and Column C as Time:

I need Column C,row 3 to display the time of the rider# from B3 from page Master Score Sheet.  On master score sheet, rider Numbers are in Column A and their times are displayed in column W.

Any help would be appreciated!

答:
Stick index and match formula in column c3 in your teams sheet
Like this: =index (referenceSheetname (A:W), match (referenceSheetname(A:A),teamsSheetname.B3,0),26)
Replace sheetnames with exact worksheetnames of your teams sheet and reference sheet where data is stored
Thanks
Serge</p>


问:
cut processing in prolog
can somebody please explain the processing of the following command:

```<code>max(X,Y,Max) :- X >= Y, !, Max = X ; Max = Y.
</code>```

I can't understand, what exactly does it mean ! in the middle, thanks in advance

答:
The ! (cut) means if you got this far (successfully in the current goal), don't do any backtracking (consider alternative ways to satisfy the current goal) that might have been open before the cut's placement.

In your example the cut is being used to tersely express how to define the Max of X and Y.  That is, once you succeed with the subgoal X >= Y, the right alternative is no longer in doubt (so unify Max with X).

The tricky thing here is the precedence of , (representing logical AND) and ; (representing logical OR).  The latter binds more weakly than the former, so that the alternative subgoal unifying Max with Y can only be reached if X >= Y fails (the alternative for the current goal will not be considered if the cut is passed).

Title: cut processing in prolog

Body:
can somebody please explain the processing of the following command:

max(X,Y,Max) :- X >= Y, !, Max = X ; Max = Y.

I can't understand, what exactly does it mean ! in the middle, thanks in advance


问:
Javascript Background toggle on Popup
I have a div assigned to trigger some Javascipt which opens a 'PopUp' RSVP form on my site,I however also want to have a black background full screen overlay when the window pops up to hide the rest of the site.

The popup window works fine using this:

```<code>$(function() {
    // contact form animations
    $('#contact').click(function() {
    $('#contactForm').fadeToggle();
});

$(document).mouseup(function (e) {
    var container = $("#contactForm");

    if (!container.is(e.target) // if the target of the click isn't the      container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.fadeOut();
    }
});
</code>```

So I want to attach the overlay action into this function so that it toggles on and off with the PopUpWindow. I already have a div assigned with the correct CSS,I just need to get it to also toggle:

```<code>.sidebar-overlay {
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: rgba(0,0,0,1);
    position: fixed;
    z-index: 3;
    display: none;
    cursor: e-resize;
}
</code>```

I am a little stuck so any help is very much appreciated. Thanks

答:
I think in your script, you checked for the contact form being clicked or not, but then you hide only the form, and not the sidebar-overlay section. So it's really just a slight mix up in which selector is in use. (I can't be positive if that's what's going on, as you did not include the html markup in your question.)

Here's a quick example with your code and the matching html. Only, the sidebar-overlay is hid on click of the document area.

  $('#contact').click(function() {
    var container = $(".sidebar-overlay");
    container.fadeToggle();
  });

  $(document).mouseup(function (e) {

    var container = $(".sidebar-overlay");
    var contactform = $("#contactForm");

    if (!contactform.is(e.target) // if the target of the click isn't the      container...
        && contactform.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.fadeOut();
    }
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidebar-overlay {
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(0,0,0,1);
  position: fixed;
  z-index: 3;
  display: none;
  cursor: e-resize;
}
#contactForm{
  width:50%;
  margin:20px auto;
  padding:20px;
  background:pink;
}</code>```

<button id="contact">click</button>

<form id="contactForm">
This is my form

field 1 ______

field 2 ______

</form>

```

Title: Javascript Background toggle on Popup

Body:
I have a div assigned to trigger some Javascipt which opens a 'PopUp' RSVP form on my site,I however also want to have a black background full screen overlay when the window pops up to hide the rest of the site.

The popup window works fine using this:

$(function() {
    // contact form animations
    $('#contact').click(function() {
    $('#contactForm').fadeToggle();
});

$(document).mouseup(function (e) {
    var container = $("#contactForm");

    if (!container.is(e.target) // if the target of the click isn't the      container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.fadeOut();
    }
});

So I want to attach the overlay action into this function so that it toggles on and off with the PopUpWindow. I already have a div assigned with the correct CSS,I just need to get it to also toggle:

.sidebar-overlay {
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: rgba(0,0,0,1);
    position: fixed;
    z-index: 3;
    display: none;
    cursor: e-resize;
}

I am a little stuck so any help is very much appreciated. Thanks

Body:
I think in your script, you checked for the contact form being clicked or not, but then you hide only the form, and not the sidebar-overlay section. So it's really just a slight mix up in which selector is in use. (I can't be positive if that's what's going on, as you did not include the html markup in your question.)

Here's a quick example with your code and the matching html. Only, the sidebar-overlay is hid on click of the document area.

  $('#contact').click(function() {
    var container = $(".sidebar-overlay");
    container.fadeToggle();
  });

  $(document).mouseup(function (e) {

    var container = $(".sidebar-overlay");
    var contactform = $("#contactForm");

    if (!contactform.is(e.target) // if the target of the click isn't the      container...
        && contactform.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.fadeOut();
    }
  });

.sidebar-overlay {
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(0,0,0,1);
  position: fixed;
  z-index: 3;
  display: none;
  cursor: e-resize;
}
#contactForm{
  width:50%;
  margin:20px auto;
  padding:20px;
  background:pink;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="contact">click</button>

<div class="sidebar-overlay">

<form id="contactForm">
This is my form<br />
field 1 ______<br />
field 2 ______<br />
</form>

</div>


问:
dql select return empty result symfony 3
I'm trying to get all videos from a DB that contain a keyword, It's an API REST building with Symfony 3. Here is a sample of the URL

```<code>http://localhost/Server/symfony/web/app_dev.php/video/search/prueba
</code>```

Where "prueba" is the keyword that i'm trying to find

Here is the function..

```<code>public function searchAction(Request $request, $search = null){
    $helper = $this->get("app.helper");
    $em = $this->getDoctrine()->getManager();
    if($search != null){
        $dql = "SELECT v.title FROM BackendBundle:Video v "
                . "WHERE v.title LIKE :search OR "
                . "v.description LIKE :search ORDER BY v.id DESC";

        $query = $em->createQuery($dql)
                ->setParameter("search", "%search%");
    } else {
        $dql = "SELECT v FROM BackendBundle:Video v ORDER BY v.id DESC";
        $query = $em->createQuery($dql);
    }
    $page = $request->query->getInt("page", 1);
    $paginator = $this->get("knp_paginator");
    $items_per_page = 6;
    $pagination = $paginator->paginate($query, $page, $items_per_page);

    $total_items_count = $pagination->getTotalItemCount();
    $data = array(
        "status" => "success",
        "total_items_count" => $total_items_count,
        "page_actual" => $page,
        "items_per_page" => $items_per_page,
        "total_pages" => ceil($total_items_count/$items_per_page),
        "data" => $pagination
    );
    return $helper->toJson($data);
}
</code>```

The result should be a JSON with 4 videos.. but I get

```<code>{
    "status": "success",
    "total_items_count": 0,
    "page_actual": 1,
    "items_per_page": 6,
    "total_pages": 0,
    "data": []
}
</code>```

where "data" is an array with the video data

Somebody know what I miss? the dql consult.. it's rigth?

Somebody could tell me what is the mistake? I need a clue.. the dql consult is correct?

答:
I see you use knp_paginator service. Try to get items from paginator like this:

```<code>$data = array(
    "status" => "success",
    "total_items_count" => $total_items_count,
    "page_actual" => $page,
    "items_per_page" => $items_per_page,
    "total_pages" => ceil($total_items_count/$items_per_page),
    "data" => $pagination->getItems()
);
</code>```

Body:
I'm trying to get all videos from a DB that contain a keyword, It's an API REST building with Symfony 3. Here is a sample of the URL

http://localhost/Server/symfony/web/app_dev.php/video/search/prueba

Where "prueba" is the keyword that i'm trying to find

Here is the function..

public function searchAction(Request $request, $search = null){
    $helper = $this->get("app.helper");
    $em = $this->getDoctrine()->getManager();
    if($search != null){
        $dql = "SELECT v.title FROM BackendBundle:Video v "
                . "WHERE v.title LIKE :search OR "
                . "v.description LIKE :search ORDER BY v.id DESC";

        $query = $em->createQuery($dql)
                ->setParameter("search", "%search%");
    } else {
        $dql = "SELECT v FROM BackendBundle:Video v ORDER BY v.id DESC";
        $query = $em->createQuery($dql);
    }
    $page = $request->query->getInt("page", 1);
    $paginator = $this->get("knp_paginator");
    $items_per_page = 6;
    $pagination = $paginator->paginate($query, $page, $items_per_page);

    $total_items_count = $pagination->getTotalItemCount();
    $data = array(
        "status" => "success",
        "total_items_count" => $total_items_count,
        "page_actual" => $page,
        "items_per_page" => $items_per_page,
        "total_pages" => ceil($total_items_count/$items_per_page),
        "data" => $pagination
    );
    return $helper->toJson($data);
}

The result should be a JSON with 4 videos.. but I get

{
    "status": "success",
    "total_items_count": 0,
    "page_actual": 1,
    "items_per_page": 6,
    "total_pages": 0,
    "data": []
}

where "data" is an array with the video data

Somebody know what I miss? the dql consult.. it's rigth?

Somebody could tell me what is the mistake? I need a clue.. the dql consult is correct?

Body:
I see you use knp_paginator service. Try to get items from paginator like this:

$data = array(
    "status" => "success",
    "total_items_count" => $total_items_count,
    "page_actual" => $page,
    "items_per_page" => $items_per_page,
    "total_pages" => ceil($total_items_count/$items_per_page),
    "data" => $pagination->getItems()
);


问:
Xcode 9 error: "iPhone has denied the launch request"
Using Xcode beta 9 (v4), I'm trying to launch the app by clicking on the "play" button. I get a "build succeeded" but right before launching, a popup message appears in Xcode:

"iPhone has denied the launch request."

It used to work yesterday. It does work on the simulator. I've rebooted my computer, the iPhone, uninstall the app, cleaned the build. Running out of ideas.

答:
I have a workaround:

If you change the scheme to 'Ask on Launch' it works.

In Xcode top bar

```<code>Product > Scheme > Edit Scheme > 'Info' tab > Executable:  "Ask on Launch"
</code>```

http://upload-images.jianshu.io/upload_images/663014-d5d182e310052664.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240

It's slightly annoying but it works.

Body:
I have a workaround:

If you change the scheme to 'Ask on Launch' it works.

In Xcode top bar

Product > Scheme > Edit Scheme > 'Info' tab > Executable:  "Ask on Launch"

http://upload-images.jianshu.io/upload_images/663014-d5d182e310052664.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240

It's slightly annoying but it works.


问:
Fastest way to perform calculation between two dataframe colums?
I have a pandas dataframe with 6 million rows. The columns are:

```<code>['x', 'y']
</code>```

I need to apply a simple calculation between x an y, and append it to the dataframe.

This is what I've tried:

```<code>'''
Calculates the height of a pressure level in feet
'''
def pressure_to_elevation(P, T = None):

    sea_level_pressure = 1013.25

    if T is not None:
        # https://www.omnicalculator.com/physics/air-pressure-at-altitude

        P0 = sea_level_pressure
        g = 9.80665
        M = 0.0289644
        R0 = 8.31447

        m = (np.log(P/P0)*T) / -(g*M/R0)
        f = 3.28084 * m
        return f

    b = 0.190284
    c = 145366.45

    return (1-math.pow((P/sea_level_pressure), b)) * c

test_df['result'] = test_fd.apply(lambda row: pressure_to_elevation(row['x'], row['y']),axis=1)
</code>```

Unfortunately, this takes a ridiculous amount of time... in fact, I've yet to see it complete.

Is there a faster way to do this?

答:
Try this:

```<code>def pressure_to_elevation(P, T):

    sea_level_pressure = 1013.25

    P0 = sea_level_pressure
    g = 9.80665
    M = 0.0289644
    R0 = 8.31447

    b = 0.190284
    c = 145366.45

    return np.where(T.notnull(),
                    3.28084 * ((np.log(P/P0)*T) / -(g*M/R0)),
                    (1-np.pow((P/sea_level_pressure), b)) * c)
</code>```

Usage:

```<code>test_df['result'] = pressure_to_elevation(test_df['x'], test_df['y'])
</code>```

Body:
I have a pandas dataframe with 6 million rows. The columns are:

['x', 'y']

I need to apply a simple calculation between x an y, and append it to the dataframe.

This is what I've tried:

'''
Calculates the height of a pressure level in feet
'''
def pressure_to_elevation(P, T = None):

    sea_level_pressure = 1013.25

    if T is not None:
        # https://www.omnicalculator.com/physics/air-pressure-at-altitude

        P0 = sea_level_pressure
        g = 9.80665
        M = 0.0289644
        R0 = 8.31447

        m = (np.log(P/P0)*T) / -(g*M/R0)
        f = 3.28084 * m
        return f

    b = 0.190284
    c = 145366.45

    return (1-math.pow((P/sea_level_pressure), b)) * c

test_df['result'] = test_fd.apply(lambda row: pressure_to_elevation(row['x'], row['y']),axis=1)

Unfortunately, this takes a ridiculous amount of time... in fact, I've yet to see it complete.

Is there a faster way to do this?

Body:
Try this:

def pressure_to_elevation(P, T):

    sea_level_pressure = 1013.25

    P0 = sea_level_pressure
    g = 9.80665
    M = 0.0289644
    R0 = 8.31447

    b = 0.190284
    c = 145366.45

    return np.where(T.notnull(),
                    3.28084 * ((np.log(P/P0)*T) / -(g*M/R0)),
                    (1-np.pow((P/sea_level_pressure), b)) * c)

Usage:

test_df['result'] = pressure_to_elevation(test_df['x'], test_df['y'])


问:
Have a text from database to get a color out from what it says

Hey guys, im not good with coding so after failing to find out how from googling Im gonna try get help from the pros.

So, im just making something for fun cause im bored. I have a sql database with a table that consists of name, link and status.
The status has 3 options, Permanently Banned, Temporarily Banned and Kicked.

Currently I have it like this putting font color in the code, but then it all get in red text.

```<code>while($row = $result->fetch_assoc()) {
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b><font color='red'> " . $row["status"] . "</font></b></td></tr>";

}
</code>```

I want Permanently Banned to be in red, Temporarily Banned in orange and Kicked in green. I don't understand how to make the colors appear like that.

I appreciate any help, im still a newbie when it comes to coding so im sorry if this is a really easy solution that I failed to find :P

I also have a problem with the link, but im just gonna let it be for now, maybe I'l ask after this is fixed..

Thanks! :)

答:
Use your status as a CSS class:

```<code>$statusclass = str_replace(' ', '-', strtolower($row[status]));`
</code>```

then change your HTML for the status:

```<code>`<td class='text-left " . $statusclass . "'></td></tr>";`
</code>```

Then add CSS to your output, preferably in the , but anywhere might do:

```<code><style type="text/css">
.permanently-banned { font-weight: bold; color: Red; }
.temporarily-banned { font-weight: bold; color: Orange; }
.kicked { font-weight: bold; color: Green; }
</style>
</code>```

Body:
Hey guys, im not good with coding so after failing to find out how from googling Im gonna try get help from the pros.

So, im just making something for fun cause im bored. I have a sql database with a table that consists of name, link and status.
The status has 3 options, Permanently Banned, Temporarily Banned and Kicked.

Currently I have it like this putting font color in the code, but then it all get in red text.

while($row = $result->fetch_assoc()) {
    echo "

     ". $row["name"]. "
     ". $row["link"]. "
     " . $row["status"] . "
";

}

I want Permanently Banned to be in red, Temporarily Banned in orange and Kicked in green. I don't understand how to make the colors appear like that.

I appreciate any help, im still a newbie when it comes to coding so im sorry if this is a really easy solution that I failed to find :P

I also have a problem with the link, but im just gonna let it be for now, maybe I'l ask after this is fixed..

Thanks! :)

Body:
Use your status as a CSS class:

$statusclass = str_replace(' ', '-', strtolower($row[status]));`

then change your HTML for the status:

`<td class='text-left " . $statusclass . "'></td></tr>";`

Then add CSS to your output, preferably in the <head>, but anywhere might do:

<style type="text/css">
.permanently-banned { font-weight: bold; color: Red; }
.temporarily-banned { font-weight: bold; color: Orange; }
.kicked { font-weight: bold; color: Green; }
</style>


问:
Publicly Available Spam Filter Training Set
I'm new to machine learning, and for my first project I'd like to write a naive Bayes spam filter. I was wondering if there are any publicly available training sets of labeled spam/not spam emails, preferably in plain text and not a dump of a relational database (unless they pretty-print those?).

I know such a publicly available database exists for other kinds of text classification, specifically news article text. I just haven't been able to find the same sort of thing for emails.

答:
Here is what I was looking for: http://untroubled.org/spam/

This archive has around a gigabyte of compressed accumulated spam messages dating 1998 - 2011. Now I just need to get non-spam email. So I'll just query my own Gmail for that using the getmail program and the tutorial at mattcutts.com


问:
C# reuse method and avoid disposing on using
I would like to optionally dispose (with a using statement) an object. If the connection string is passed in the constructor, then the using must dispose and if the object SQLDataLayer is passed in the constructor, then I don't want to dispose. This is to avoid passing the SQLDataLayer object in every re-usable method, is this the right approach?

```<code>public class RepoCategory
{
    readonly string connString;
    SQLDataLayer dl = null;

    public RepoCategory(string conn_string)
    {
        this.connString = conn_string;
    }

    public RepoCategory(SQLDataLayer dl)
    {
        this.dl = dl;
    }

    //I WANT TO MAGICALLY generate using(null) if dl was passed in constructor
    //or using(dl = new SQLDataLayer(connString)) if connString was passed.
    public Category Get(int category_sid)
    {
        Category cat = null;
        using (SQLDataLayer dlDispose = (dl == null) ? new SQLDataLayer(connString) : null)
        {
            //can this be simplified/avoided?
            if (dlDispose != null)
                dl = dlDispose;
            cat = dl.GetCat();
        }
        return cat;
    }
    //I DON'T WANT TO PASS THE DL MANUALLY EVERYTIME
    public Category Get(SQLDataLayer dl, int category_sid)
    {
        Category cat = null;
        cat = dl.GetCat();
        return cat;
    }
}
</code>```

thanks!

答:
In your particular example, like this:

```<code>SQLDataLayer dlDispose = null;
SQLDataLayer dl = this.dl ?? (dlDispose = new SQLDataLayer(connString));
using (dlDispose) { dl.Blah(...) }
</code>```

This also fixes the bug where you leave the class field referring to a short-lived connection that you're also disposing.

For more general usefulness, it is helpful to have a holder class that implements Dispose and will conditionally call Dispose on the object it holds.

Body:
I would like to optionally dispose (with a using statement) an object. If the connection string is passed in the constructor, then the using must dispose and if the object SQLDataLayer is passed in the constructor, then I don't want to dispose. This is to avoid passing the SQLDataLayer object in every re-usable method, is this the right approach?

public class RepoCategory
{
    readonly string connString;
    SQLDataLayer dl = null;

    public RepoCategory(string conn_string)
    {
        this.connString = conn_string;
    }

    public RepoCategory(SQLDataLayer dl)
    {
        this.dl = dl;
    }

    //I WANT TO MAGICALLY generate using(null) if dl was passed in constructor
    //or using(dl = new SQLDataLayer(connString)) if connString was passed.
    public Category Get(int category_sid)
    {
        Category cat = null;
        using (SQLDataLayer dlDispose = (dl == null) ? new SQLDataLayer(connString) : null)
        {
            //can this be simplified/avoided?
            if (dlDispose != null)
                dl = dlDispose;
            cat = dl.GetCat();
        }
        return cat;
    }
    //I DON'T WANT TO PASS THE DL MANUALLY EVERYTIME
    public Category Get(SQLDataLayer dl, int category_sid)
    {
        Category cat = null;
        cat = dl.GetCat();
        return cat;
    }
}

thanks!

Body:
In your particular example, like this:

SQLDataLayer dlDispose = null;
SQLDataLayer dl = this.dl ?? (dlDispose = new SQLDataLayer(connString));
using (dlDispose) { dl.Blah(...) }

This also fixes the bug where you leave the class field referring to a short-lived connection that you're also disposing.

For more general usefulness, it is helpful to have a holder class that implements Dispose and will conditionally call Dispose on the object it holds.


问:
Filtering set returning function results
I'm hoping to clarify my understanding of how set returning functions behave behind the scenes in PostgreSQL.

Let's set I have a set returning function called 'a_at_date' which returns:

```<code> SELECT * FROM a WHERE date = a_date
</code>```

Where a_date is a function parameter.

If I use this like so:

```<code>SELECT *
FROM a_at_date(a_date)
WHERE other_field = 123
</code>```

Then, for example, can this ever take advantage of an index on [date, other_field] in the same way that this can:

```<code>SELECT *
FROM a
WHERE a = a_date AND other_field = 123
</code>```

In other words does a set returning function run in isolation of any outer query and therefore limiting the indexing options?

答:
In principle, the optimizer has no clue what a function does – the function body is a string that is handled by the call handler of the function's procedural language.

The one exception are functions written in LANGUAGE sql. If they are simple enough, and inlining them can be proven not to change the semantics of the SQL statement, the query rewriter will inline them.

See the following comment in backend/optimizer/prep/prepjointree.c:

/*
 * inline_set_returning_functions
 *              Attempt to "inline" set-returning functions in the FROM clause.
 *
 * If an RTE_FUNCTION rtable entry invokes a set-returning function that
 * contains just a simple SELECT, we can convert the rtable entry to an
 * RTE_SUBQUERY entry exposing the SELECT directly.  This is especially
 * useful if the subquery can then be "pulled up" for further optimization,
 * but we do it even if not, to reduce executor overhead.
 *
 * This has to be done before we have started to do any optimization of
 * subqueries, else any such steps wouldn't get applied to subqueries
 * obtained via inlining.  However, we do it after pull_up_sublinks
 * so that we can inline any functions used in SubLink subselects.
 *
 * Like most of the planner, this feels free to scribble on its input data
 * structure.
 */
```

<p>There are also two instructive comments in <code>inline_set_returning_function</code> in <code>backend/optimizer/util/clauses.c</code>:</p>

<pre class="lang-none prettyprint-override"><code>/*
 * Forget it if the function is not SQL-language or has other showstopper
 * properties.  In particular it mustn't be declared STRICT, since we
 * couldn't enforce that.  It also mustn't be VOLATILE, because that is
 * supposed to cause it to be executed with its own snapshot, rather than
 * sharing the snapshot of the calling query.  (Rechecking proretset is
 * just paranoia.)
 */
</code>```

and

/*
 * Make sure the function (still) returns what it's declared to.  This
 * will raise an error if wrong, but that's okay since the function would
 * fail at runtime anyway.  Note that check_sql_fn_retval will also insert
 * RelabelType(s) and/or NULL columns if needed to make the tlist
 * expression(s) match the declared type of the function.
 *
 * If the function returns a composite type, don't inline unless the check
 * shows it's returning a whole tuple result; otherwise what it's
 * returning is a single composite column which is not what we need. (Like
 * check_sql_fn_retval, we deliberately exclude domains over composite
 * here.)
 */
```

<p>Use <code>EXPLAIN</code> to see if your function is inlined.</p>

<p>An example where it works:</p>

```CREATE TABLE a (
   "date" date NOT NULL,
   other_field text NOT NULL
);

CREATE OR REPLACE FUNCTION a_at_date(date)
   RETURNS TABLE ("date" date, other_field text)
   LANGUAGE sql STABLE CALLED ON NULL INPUT
   AS 'SELECT "date", other_field FROM a WHERE "date" = $1';

EXPLAIN (VERBOSE, COSTS off)
SELECT *
FROM a_at_date(current_date)
WHERE other_field = 'value';

                               QUERY PLAN
-------------------------------------------------------------------------
 Seq Scan on laurenz.a
   Output: a.date, a.other_field
   Filter: ((a.other_field = 'value'::text) AND (a.date = CURRENT_DATE))
(3 rows)
```

Body:
I'm hoping to clarify my understanding of how set returning functions behave behind the scenes in PostgreSQL.

Let's set I have a set returning function called 'a_at_date' which returns:

 SELECT * FROM a WHERE date = a_date

Where a_date is a function parameter.

If I use this like so:

SELECT *
FROM a_at_date(a_date)
WHERE other_field = 123

Then, for example, can this ever take advantage of an index on [date, other_field] in the same way that this can:

SELECT *
FROM a
WHERE a = a_date AND other_field = 123

In other words does a set returning function run in isolation of any outer query and therefore limiting the indexing options?

Body:
In principle, the optimizer has no clue what a function does – the function body is a string that is handled by the call handler of the function's procedural language.

The one exception are functions written in LANGUAGE sql. If they are simple enough, and inlining them can be proven not to change the semantics of the SQL statement, the query rewriter will inline them.

See the following comment in backend/optimizer/prep/prepjointree.c:

/*
 * inline_set_returning_functions
 *              Attempt to "inline" set-returning functions in the FROM clause.
 *
 * If an RTE_FUNCTION rtable entry invokes a set-returning function that
 * contains just a simple SELECT, we can convert the rtable entry to an
 * RTE_SUBQUERY entry exposing the SELECT directly.  This is especially
 * useful if the subquery can then be "pulled up" for further optimization,
 * but we do it even if not, to reduce executor overhead.
 *
 * This has to be done before we have started to do any optimization of
 * subqueries, else any such steps wouldn't get applied to subqueries
 * obtained via inlining.  However, we do it after pull_up_sublinks
 * so that we can inline any functions used in SubLink subselects.
 *
 * Like most of the planner, this feels free to scribble on its input data
 * structure.
 */

There are also two instructive comments in inline_set_returning_function in backend/optimizer/util/clauses.c:

/*
 * Forget it if the function is not SQL-language or has other showstopper
 * properties.  In particular it mustn't be declared STRICT, since we
 * couldn't enforce that.  It also mustn't be VOLATILE, because that is
 * supposed to cause it to be executed with its own snapshot, rather than
 * sharing the snapshot of the calling query.  (Rechecking proretset is
 * just paranoia.)
 */

and

/*
 * Make sure the function (still) returns what it's declared to.  This
 * will raise an error if wrong, but that's okay since the function would
 * fail at runtime anyway.  Note that check_sql_fn_retval will also insert
 * RelabelType(s) and/or NULL columns if needed to make the tlist
 * expression(s) match the declared type of the function.
 *
 * If the function returns a composite type, don't inline unless the check
 * shows it's returning a whole tuple result; otherwise what it's
 * returning is a single composite column which is not what we need. (Like
 * check_sql_fn_retval, we deliberately exclude domains over composite
 * here.)
 */

Use EXPLAIN to see if your function is inlined.

An example where it works:

CREATE TABLE a (
   "date" date NOT NULL,
   other_field text NOT NULL
);

CREATE OR REPLACE FUNCTION a_at_date(date)
   RETURNS TABLE ("date" date, other_field text)
   LANGUAGE sql STABLE CALLED ON NULL INPUT
   AS 'SELECT "date", other_field FROM a WHERE "date" = $1';

EXPLAIN (VERBOSE, COSTS off)
SELECT *
FROM a_at_date(current_date)
WHERE other_field = 'value';

                               QUERY PLAN
-------------------------------------------------------------------------
 Seq Scan on laurenz.a
   Output: a.date, a.other_field
   Filter: ((a.other_field = 'value'::text) AND (a.date = CURRENT_DATE))
(3 rows)


问:
Regular expressions for 301 redirect
How can I redirect http://example.com/news.php?id=268&page=25 and all pages like  http://example.com/news.php?id=X&page=Y to another page using regular expressions?

I tried using http://example.com/news.php?id=/d&page=/d.

答:
```<code>$string = 'http://example.com/news.php?id=268&page=25';
$pattern = '/^[^\?]+\?id=(\d+)&page=(\d+)$/';
$replacement = 'https://mynewdomain/with/too/many/subpaths/page.php?id=$1&page=$2';
echo preg_replace($pattern, $replacement, $string);
</code>```

Title: Regular expressions for 301 redirect


问:
Expression of type list(object) doesn't conform to expected list scala
Supposedly I have the following

```<code>case class test {
                   a:string
                   b: string
                   c: Int
                   d: Int }

var temp = List(test("lol","lel",1,2))
var total = List(test)

total = total:::temp //this doesn't work because temp is of type [test] while total is of type [test.type]
</code>```

I do not understand the difference.
The reason I want to use this is that I want to have a running list where elements will be conditionally added in a loop.
So in this instance, total should initially an empty list which takes test objects. How do I do this?

Any feedback is appreciated!

答:
Based on your description ('I want to have a running list where elements will be conditionally added in a loop'), my understanding is that you are getting Test objects from some source and want to put them in a list but only if they meet certain criteria. We can express this requirement as a method. For convenience, we'll put the method in the Test companion object. Companion objects are a place to put things that should be available without having to instantiate any objects.

```<code>case class Test(a: String, b: String, c: Int, d: Int)

object Test {
  /**
  Returns a list of `Test` objects that pass the given criteria.

  @param tests some source of tests that we can loop over one at a
    time.
  @param condition checks whether a `Test` object should go into our
    output list.
  */
  def runningList(
    tests: Iterable[Test])(condition: Test => Boolean): List[Test] =
    tests.filter(condition).toList
}
</code>```

You can use it like (e.g.):

```<code>Test.runningList(testsSource) { test => test.c > 0 && test.d < 100 }
</code>```

As you can see here, I've used a few Scala features, like iterables and their list conversion method, multi-parameter-list methods, first-class functions, function-as-last-argument DSL, and so on. If you have more questions on these topics I'd recommend a Scala tutorial.

Body:
Supposedly I have the following

case class test {
                   a:string
                   b: string
                   c: Int
                   d: Int }

var temp = List(test("lol","lel",1,2))
var total = List(test)

total = total:::temp //this doesn't work because temp is of type [test] while total is of type [test.type]

I do not understand the difference.
The reason I want to use this is that I want to have a running list where elements will be conditionally added in a loop.
So in this instance, total should initially an empty list which takes test objects. How do I do this?

Any feedback is appreciated!

Body:
Based on your description ('I want to have a running list where elements will be conditionally added in a loop'), my understanding is that you are getting Test objects from some source and want to put them in a list but only if they meet certain criteria. We can express this requirement as a method. For convenience, we'll put the method in the Test companion object. Companion objects are a place to put things that should be available without having to instantiate any objects.

case class Test(a: String, b: String, c: Int, d: Int)

object Test {
  /**
  Returns a list of `Test` objects that pass the given criteria.

  @param tests some source of tests that we can loop over one at a
    time.
  @param condition checks whether a `Test` object should go into our
    output list.
  */
  def runningList(
    tests: Iterable[Test])(condition: Test => Boolean): List[Test] =
    tests.filter(condition).toList
}

You can use it like (e.g.):

Test.runningList(testsSource) { test => test.c > 0 && test.d < 100 }

As you can see here, I've used a few Scala features, like iterables and their list conversion method, multi-parameter-list methods, first-class functions, function-as-last-argument DSL, and so on. If you have more questions on these topics I'd recommend a Scala tutorial.


问:
Find missing element
I saw the following question:

Given an array A of integers, find an integer k that is not present in A. Assume that the integers are 32-bit signed integers.

How to solve it?

Thank you

//// update -- This is the provided solution - but I don't think it is correct ////
Consider a very simple hash function F(x)=x mod (n+1). we can build a bit-vector of length
n+1 that is initialized to 0 and for every element in A, we set bit F(A[i]) to 1.Since there are only n elements in the array, we can find the missing element easily.

I think the above solution is wrong.

For example,
A [ 2, 100, 4 ], then both 4 and 100 will match to the same place.

答:
Since there appear to be no upperbounds or other constraints:</p>

```<code>for (int i = int.MinValue; i <= int.MaxValue; i++)
{
    if (! A.Contains(i))
    {
       // found it !
       break;
    }
}
</code>```

Title: Find missing element

Body:
Since there appear to be no upperbounds or other constraints:

for (int i = int.MinValue; i <= int.MaxValue; i++)
{
    if (! A.Contains(i))
    {
       // found it !
       break;
    }
}


问:
Using Telegram bot webhook by pyTelegramBotAPI and Flask on pythonanywhere.com
The question is about using webhooks in a Telegram bot using the pyTelegramBotAPI module.
I am using pythonanywhere.com to host the bot.

The following code works fine:

```<code>from flask import Flask, request
import telebot

secret = "A_SECRET_NUMBER"
bot = telebot.TeleBot ('YOUR_AUTHORIZATION_TOKEN')
bot.set_webhook("https://YOUR_PYTHONANYWHERE_USERNAME.pythonanywhere.c..
}".format(secret), max_connections=1)

app = Flask(__name__)
@app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
   update = request.get_json()
   if "message" in update:
   text = update["message"]["text"]
   chat_id = update["message"]["chat"]["id"]
   bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))
return "OK"
</code>```

But when I use message handlers as shown in the example, I receive no answer from the bot:

```<code># Process webhook calls
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
   if flask.request.headers.get('content-type') == 'application/json':
   json_string = flask.request.get_data().decode('utf-8')
   update = telebot.types.Update.de_json(json_string)
   bot.process_new_updates([update])
   return ''
else:
   flask.abort(403)

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
   def send_welcome(message):
   bot.reply_to(message,
   ("Hi there, I am EchoBot.\n"
   "I am here to echo your kind words back to you."))

# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
   def echo_message(message):
   bot.reply_to(message, message.text)
</code>```

I have tried examples from different libraries, but still no answer.

Any ideas?

It would be great if you could share a working example of Telegram "echo-bot" on pythonanywhere.com.

Thanks.

答:
You should disable threading in the TeleBot constructor like this:

```<code>bot = telebot.TeleBot('YOUR_AUTHORIZATION_TOKEN', threaded=False)
</code>```

I had the same issue and found a solution here:
https://www.pythonanywhere.com/forums/topic/9562/#id_post_40177

Threading is unavailable for free PythonAnywhere accounts.

Body:
The question is about using webhooks in a Telegram bot using the pyTelegramBotAPI module.
I am using pythonanywhere.com to host the bot.

The following code works fine:

from flask import Flask, request
import telebot

secret = "A_SECRET_NUMBER"
bot = telebot.TeleBot ('YOUR_AUTHORIZATION_TOKEN')
bot.set_webhook("https://YOUR_PYTHONANYWHERE_USERNAME.pythonanywhere.c..
}".format(secret), max_connections=1)

app = Flask(__name__)
@app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
   update = request.get_json()
   if "message" in update:
   text = update["message"]["text"]
   chat_id = update["message"]["chat"]["id"]
   bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))
return "OK"

But when I use message handlers as shown in the example, I receive no answer from the bot:

# Process webhook calls
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
   if flask.request.headers.get('content-type') == 'application/json':
   json_string = flask.request.get_data().decode('utf-8')
   update = telebot.types.Update.de_json(json_string)
   bot.process_new_updates([update])
   return ''
else:
   flask.abort(403)

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
   def send_welcome(message):
   bot.reply_to(message,
   ("Hi there, I am EchoBot.\n"
   "I am here to echo your kind words back to you."))

# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
   def echo_message(message):
   bot.reply_to(message, message.text)

I have tried examples from different libraries, but still no answer.

Any ideas?

It would be great if you could share a working example of Telegram "echo-bot" on pythonanywhere.com.

Thanks.

Body:
You should disable threading in the TeleBot constructor like this:

bot = telebot.TeleBot('YOUR_AUTHORIZATION_TOKEN', threaded=False)

I had the same issue and found a solution here:
https://www.pythonanywhere.com/forums/topic/9562/#id_post_40177

Threading is unavailable for free PythonAnywhere accounts.


问:
Store JSON data outside of _v property in MongoDB
I'm using MongoDB as a database for my web application. I'm looking for a way to insert and retrieve dynamic JSON data without making any typed classes for it.

My web application sends a JSON string. Then in the backend I convert that JSON string to a BsonDocument and insert that into MongoDB:

```<code>var obj = BsonDocument.Parse(json.ToString());
Db.GetCollection<dynamic>("Items").InsertOneAsync(obj);
</code>```

This works fine, except that the structure in MongoDB looks like this:

```<code>_id = ObjectId("55618d35d747199c0a486fe0")
_t = MongoDB.Bson.BsonDocument, MongoDB.Bson
_v = (3 fields)
   username = "JohDoe"
   password = "xxxxx"
   email = "em@il.com"
</code>```

In other words, my JSON object is stored inside _v. I don't want to store everything in a "sub" property. I want it to look like this:

```<code>_id = ObjectId("55618d35d747199c0a486fe0")
_t = MongoDB.Bson.BsonDocument, MongoDB.Bson
username = "JohDoe"
password = "xxxxx"
email = "em@il.com"
</code>```

Is it possible to store the data like that without creating any typed objects my self?

答:
In my case, to fix the issue I am using:

GetCollection< BsonDocument > to insert new documents.

GetCollection< dynamic > to query the DB.

Body:
I'm using MongoDB as a database for my web application. I'm looking for a way to insert and retrieve dynamic JSON data without making any typed classes for it.

My web application sends a JSON string. Then in the backend I convert that JSON string to a BsonDocument and insert that into MongoDB:

var obj = BsonDocument.Parse(json.ToString());
Db.GetCollection<dynamic>("Items").InsertOneAsync(obj);

This works fine, except that the structure in MongoDB looks like this:

_id = ObjectId("55618d35d747199c0a486fe0")
_t = MongoDB.Bson.BsonDocument, MongoDB.Bson
_v = (3 fields)
   username = "JohDoe"
   password = "xxxxx"
   email = "em@il.com"

In other words, my JSON object is stored inside _v. I don't want to store everything in a "sub" property. I want it to look like this:

_id = ObjectId("55618d35d747199c0a486fe0")
_t = MongoDB.Bson.BsonDocument, MongoDB.Bson
username = "JohDoe"
password = "xxxxx"
email = "em@il.com"

Is it possible to store the data like that without creating any typed objects my self?


答:
You can simply add a CSS class for each case and then style it via CSS. Of course you have to clean the name in order to remove spaces with underscore or hyphens.

```<code>while($row = $result->fetch_assoc()) {
    $cleanStatus = strtolower(preg_replace('/\s+/', '_', $row["status"]));
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b class='".$cleanStatus."'> " . $row["status"] . "</b></td></tr>";
}
</code>```

So your CSS could look like:

```<code>.permanently_banned {
   color: red;
}

.temporarily_banned {
   color: orange;
}

.kicked {
   color: green;
}
</code>```

Title: Have a text from database to get a color out from what it says

Body:
You can simply add a CSS class for each case and then style it via CSS. Of course you have to clean the name in order to remove spaces with underscore or hyphens.

while($row = $result->fetch_assoc()) {
    $cleanStatus = strtolower(preg_replace('/\s+/', '_', $row["status"]));
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b class='".$cleanStatus."'> " . $row["status"] . "</b></td></tr>";
}

So your CSS could look like:

.permanently_banned {
   color: red;
}

.temporarily_banned {
   color: orange;
}

.kicked {
   color: green;
}


问:
"int() argument must be a string" processing output of date.split(':')
 I have a function that gets the day from a string structured as DD:MM:YY.

```<code>def get_day(date):
    day=int(date.split(':'))
    return day
</code>```

 I expect the function to return an integer with the number of the day, but instead I get this error

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

答:
```<code>date.split(':')
</code>```

returns a list of strings,
try

```<code>date.split(':')[0]
</code>```

to get the first item of that list

Body:
 I have a function that gets the day from a string structured as DD:MM:YY.

def get_day(date):
    day=int(date.split(':'))
    return day

 I expect the function to return an integer with the number of the day, but instead I get this error

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Body:
date.split(':')

returns a list of strings,
try

date.split(':')[0]

to get the first item of that list


问:
Firefox content script not loading in some pages
Context

I am currently working on a browser extension which is working as expected with Chrome and Opera but I am facing issues with Firefox. Here is a minimal version of manifest.json needed to reproduce the problem:

```<code>{
    "name": "Example",
    "version": "0.0.1",
    "author": "Pyves",
    "content_scripts": [
        {
            "all_frames": true,
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "content.js"
            ]
        }
    ],
    "manifest_version": 2
}
</code>```

And here is the related content.js:

```<code>console.log("Content script loaded");
</code>```

Issue

Content script loaded is systematically logged regardless of the visited page when using Chrome and Opera. Nevertheless, the content script doesn't seem to load in some pages when using Firefox, for instance raw GitHub pages such as the following:
https://raw.githubusercontent.com/badges/shields/master/README.md

There are no error messages in the Firefox console stating why the content script was not executed on that particular page.

Questions

Why is the Firefox extension unable to load the content script into some pages?

What changes need to be made so that the extension works consistently on all browsers?

答:
I finally figured out why the extension's content script is not loading in some pages when using Firefox.

After analysing the requests with the Network developer tools, it turns out that the following headers are returned when getting GitHub raw pages:

```<code>Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
</code>```

According to the MDN Web Docs, the sandbox CSP directive has the following effect:

enables a sandbox for the requested resource [...]. It applies
  restrictions to a page's actions including preventing popups,
  preventing the execution of plugins and scripts, and enforcing a
  same-origin policy.

Therefore Firefox is preventing extensions from executing content scripts in pages with the sandbox CSP, whereas other browsers such as Chrome and Opera do allow this behaviour. Related bug reports in Mozilla's Bugzilla (1267027 and 1411641) highlight that:

CSP 'sandbox' directive prevents content scripts from matching, due to unique origin

This issue has been acknowledged and will hopefully be fixed in future releases of Firefox.

Body:
Context

I am currently working on a browser extension which is working as expected with Chrome and Opera but I am facing issues with Firefox. Here is a minimal version of manifest.json needed to reproduce the problem:

{
    "name": "Example",
    "version": "0.0.1",
    "author": "Pyves",
    "content_scripts": [
        {
            "all_frames": true,
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "content.js"
            ]
        }
    ],
    "manifest_version": 2
}

And here is the related content.js:

console.log("Content script loaded");

Issue

Content script loaded is systematically logged regardless of the visited page when using Chrome and Opera. Nevertheless, the content script doesn't seem to load in some pages when using Firefox, for instance raw GitHub pages such as the following:
https://raw.githubusercontent.com/badges/shields/master/README.md

There are no error messages in the Firefox console stating why the content script was not executed on that particular page.

Questions

Why is the Firefox extension unable to load the content script into some pages?

What changes need to be made so that the extension works consistently on all browsers?

Body:
I finally figured out why the extension's content script is not loading in some pages when using Firefox.

After analysing the requests with the Network developer tools, it turns out that the following headers are returned when getting GitHub raw pages:

Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox

According to the MDN Web Docs, the sandbox CSP directive has the following effect:

enables a sandbox for the requested resource [...]. It applies
  restrictions to a page's actions including preventing popups,
  preventing the execution of plugins and scripts, and enforcing a
  same-origin policy.

Therefore Firefox is preventing extensions from executing content scripts in pages with the sandbox CSP, whereas other browsers such as Chrome and Opera do allow this behaviour. Related bug reports in Mozilla's Bugzilla (1267027 and 1411641) highlight that:

CSP 'sandbox' directive prevents content scripts from matching, due to unique origin

This issue has been acknowledged and will hopefully be fixed in future releases of Firefox.