问:
How to use get_queryset with Django DetailView with self.request.GET.get("q")
I am trying to figure out how to incorporate get_queryset with my Django detailview.  In the normal use case, I have this working, add get_queryset to the DetailView and voila!  It works....However this use case is a little different.

I am using a FormView to get a search value and then upon success, I return a detailview.  This working properly too.  When I try to incorporate a get_queryset to override the queryset, that's when things go awry.

Here's my code:

FormView

```<code>class AuthorSearchView(LoginRequiredMixin,FormView):
    form_class = AuthorSearchForm
    template_name = 'author_search.html'

    def get_form_kwargs(self):
        kwargs = super(AuthorSearchView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        kwargs['q'] = self.request.GET.get("q")
        return kwargs
</code>```

Then in my author_search.html:

```<code><form method="GET" autocomplete=off action="{% url 'Author:author_search_detail' %}">
</code>```

When the user enters a value in the search...it returns a DetailView screen:

```<code>class AuthorSearchDetailView(LoginRequiredMixin,DetailView):
    model = Author
    context_object_name = 'author_detail'
    template_name = 'author_search_detail.html'

    def get_object(self, queryset=None):
        return get_object_or_404(Author, request_number=self.request.GET.get("q"))
        return get_object_or_404
</code>```

The code above works fine. Note I am not using a PK reference in my action reference, as it is not needed for this approach. My URL in the case of the code above is:

```<code>url(r'^author_search_detail/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),
</code>```

However, when I try to incorporate get_queryset instead of get_object with the code below:

```<code>def get_queryset(self):
    queryset = super(AuthorSearchDetailView, self).get_queryset()
    return queryset.filter(request_number=self.request.GET.get("q"))
</code>```

Then I get:

```<code>AuthorSearchDetailView must be called with either an object pk or a slug in the URLconf.
</code>```

I get this is because I'm using DetailView and not providing a PK in my URL.

However, when I go to add a pk in my HTML and my URL as shown below:

```<code><form method="GET" autocomplete=off action="{% url 'Author:author_search_detail'pk=author.pk %}">
</code>```

URL:

```<code>url(r'^author_search_detail/(?P<pk>\d+)/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),
</code>```

I get....

```<code>Reverse for 'author_search_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['Author/author_search_detail/(?P<pk>\\d+)/$']
</code>```

Curiously, if I substitute pk=author.pk with pk=user.pk, I don't get the error.  So this leads me to believe that because I'm using FormView initially to get the DetailView success_url...that there is a problem with the pk reference in the FormView. It doesn't know about the PK.

答:
So after too much thinking about this one...turns out I was overthinking it...

I just needed to update my get_object to the filtered criteria...

```<code>def get_object(self, queryset=None):
    return get_object_or_404(Author, request_number=self.request.GET.get("q"),user=self.request.user,id="1")
    return get_object_or_404
</code>```

Added user and ID to the filter criteria of get_object.

Body:
I am trying to figure out how to incorporate get_queryset with my Django detailview.  In the normal use case, I have this working, add get_queryset to the DetailView and voila!  It works....However this use case is a little different.

I am using a FormView to get a search value and then upon success, I return a detailview.  This working properly too.  When I try to incorporate a get_queryset to override the queryset, that's when things go awry.

Here's my code:

FormView

class AuthorSearchView(LoginRequiredMixin,FormView):
    form_class = AuthorSearchForm
    template_name = 'author_search.html'

    def get_form_kwargs(self):
        kwargs = super(AuthorSearchView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        kwargs['q'] = self.request.GET.get("q")
        return kwargs

Then in my author_search.html:

<form method="GET" autocomplete=off action="{% url 'Author:author_search_detail' %}">

When the user enters a value in the search...it returns a DetailView screen:

class AuthorSearchDetailView(LoginRequiredMixin,DetailView):
    model = Author
    context_object_name = 'author_detail'
    template_name = 'author_search_detail.html'

    def get_object(self, queryset=None):
        return get_object_or_404(Author, request_number=self.request.GET.get("q"))
        return get_object_or_404

The code above works fine. Note I am not using a PK reference in my action reference, as it is not needed for this approach. My URL in the case of the code above is:

url(r'^author_search_detail/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),

However, when I try to incorporate get_queryset instead of get_object with the code below:

def get_queryset(self):
    queryset = super(AuthorSearchDetailView, self).get_queryset()
    return queryset.filter(request_number=self.request.GET.get("q"))

Then I get:

AuthorSearchDetailView must be called with either an object pk or a slug in the URLconf.

I get this is because I'm using DetailView and not providing a PK in my URL.

However, when I go to add a pk in my HTML and my URL as shown below:

<form method="GET" autocomplete=off action="{% url 'Author:author_search_detail'pk=author.pk %}">

URL:

url(r'^author_search_detail/(?P<pk>\d+)/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),

I get....

Reverse for 'author_search_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['Author/author_search_detail/(?P<pk>\\d+)/$']

Curiously, if I substitute pk=author.pk with pk=user.pk, I don't get the error.  So this leads me to believe that because I'm using FormView initially to get the DetailView success_url...that there is a problem with the pk reference in the FormView. It doesn't know about the PK.

Body:
So after too much thinking about this one...turns out I was overthinking it...

I just needed to update my get_object to the filtered criteria...

def get_object(self, queryset=None):
    return get_object_or_404(Author, request_number=self.request.GET.get("q"),user=self.request.user,id="1")
    return get_object_or_404

Added user and ID to the filter criteria of get_object.


来源: stackexchange

问:
What Python module does the file() method belong to?
I am reading a blog post related to a Recurrent Neural Network for Natural Language Processing and am trying to recreate the code to practice with. The sample code uses a method to read in a .txt file called file().read(). I am not familiar with this method and would like to know if it's contained in an importable module, or at least what it would return so I could recreate the method with with different code.

I did attempt to substitute a with open(filename) as f but it did not return the data in the same format as the file().read() method seems to. "File" isn't the easiest term to Google if you're looking for a specific result!

```<code>def train_char_lm(fname, order=4):
    data = file(fname).read()
    lm = defaultdict(Counter)
    pad = "~" * order
    data = pad + data
    for i in xrange(len(data)-order):
        history, char = data[i:i+order], data[i+order]
        lm[history][char]+=1
    def normalize(counter):
        s = float(sum(counter.values()))
        return [(c,cnt/s) for c,cnt in counter.iteritems()]
    outlm = {hist:normalize(chars) for hist, chars in lm.iteritems()}
    return outlm
</code>```

答:
Typing

```<code>help(file)
</code>```

into the IDLE interpreter yields

```<code>Help on class file in module __builtin__:
</code>```

plus additional useful info for you. It is part of the built-in module.

ContentLicense: CC BY-SA 4.0

Body:
I am reading a blog post related to a Recurrent Neural Network for Natural Language Processing and am trying to recreate the code to practice with. The sample code uses a method to read in a .txt file called file().read(). I am not familiar with this method and would like to know if it's contained in an importable module, or at least what it would return so I could recreate the method with with different code.

I did attempt to substitute a with open(filename) as f but it did not return the data in the same format as the file().read() method seems to. "File" isn't the easiest term to Google if you're looking for a specific result!

def train_char_lm(fname, order=4):
    data = file(fname).read()
    lm = defaultdict(Counter)
    pad = "~" * order
    data = pad + data
    for i in xrange(len(data)-order):
        history, char = data[i:i+order], data[i+order]
        lm[history][char]+=1
    def normalize(counter):
        s = float(sum(counter.values()))
        return [(c,cnt/s) for c,cnt in counter.iteritems()]
    outlm = {hist:normalize(chars) for hist, chars in lm.iteritems()}
    return outlm

Body:
Typing

help(file)

into the IDLE interpreter yields

Help on class file in module __builtin__:

plus additional useful info for you. It is part of the built-in module.


问:
Checking if particular value (in cell) is NaN in pandas DataFrame not working using ix or iloc
Lets say I have following pandas DataFrame:

```<code>import pandas as pd
df = pd.DataFrame({"A":[1,pd.np.nan,2], "B":[5,6,0]})
</code>```

Which would look like:

```<code>>>> df
     A  B
0  1.0  5
1  NaN  6
2  2.0  0
</code>```

First option

I know one way to check if a particular value is NaN, which is as follows:

```<code>>>> df.isnull().ix[1,0]
True
</code>```

Second option (not working)

I thought below option, using ix, would work as well, but it's not:

```<code>>>> df.ix[1,0]==pd.np.nan
False
</code>```

I also tried iloc with same results:

```<code>>>> df.iloc[1,0]==pd.np.nan
False
</code>```

However if I check for those values using ix or iloc I get:

```<code>>>> df.ix[1,0]
nan
>>> df.iloc[1,0]
nan
</code>```

So, why is the second option not working? Is it possible to check for NaN values using ix or iloc?

答:
pd.isna(cell_value) can be used to check if a given cell value is nan. Alternatively, pd.notna(cell_value) to check the opposite.

From source code of pandas:

```<code>def isna(obj):
    """
    Detect missing values for an array-like object.

    This function takes a scalar or array-like object and indicates
    whether values are missing (``NaN`` in numeric arrays, ``None`` or ``NaN``
    in object arrays, ``NaT`` in datetimelike).

    Parameters
    ----------
    obj : scalar or array-like
        Object to check for null or missing values.

    Returns
    -------
    bool or array-like of bool
        For scalar input, returns a scalar boolean.
        For array input, returns an array of boolean indicating whether each
        corresponding element is missing.

    See Also
    --------
    notna : Boolean inverse of pandas.isna.
    Series.isna : Detect missing values in a Series.
    DataFrame.isna : Detect missing values in a DataFrame.
    Index.isna : Detect missing values in an Index.

    Examples
    --------
    Scalar arguments (including strings) result in a scalar boolean.

    >>> pd.isna('dog')
    False

    >>> pd.isna(np.nan)
    True
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Lets say I have following pandas DataFrame:

import pandas as pd
df = pd.DataFrame({"A":[1,pd.np.nan,2], "B":[5,6,0]})

Which would look like:

>>> df
     A  B
0  1.0  5
1  NaN  6
2  2.0  0

First option

I know one way to check if a particular value is NaN, which is as follows:

>>> df.isnull().ix[1,0]
True

Second option (not working)

I thought below option, using ix, would work as well, but it's not:

>>> df.ix[1,0]==pd.np.nan
False

I also tried iloc with same results:

>>> df.iloc[1,0]==pd.np.nan
False

However if I check for those values using ix or iloc I get:

>>> df.ix[1,0]
nan
>>> df.iloc[1,0]
nan

So, why is the second option not working? Is it possible to check for NaN values using ix or iloc?

Body:
pd.isna(cell_value) can be used to check if a given cell value is nan. Alternatively, pd.notna(cell_value) to check the opposite.

From source code of pandas:

def isna(obj):
    """
    Detect missing values for an array-like object.

    This function takes a scalar or array-like object and indicates
    whether values are missing (``NaN`` in numeric arrays, ``None`` or ``NaN``
    in object arrays, ``NaT`` in datetimelike).

    Parameters
    ----------
    obj : scalar or array-like
        Object to check for null or missing values.

    Returns
    -------
    bool or array-like of bool
        For scalar input, returns a scalar boolean.
        For array input, returns an array of boolean indicating whether each
        corresponding element is missing.

    See Also
    --------
    notna : Boolean inverse of pandas.isna.
    Series.isna : Detect missing values in a Series.
    DataFrame.isna : Detect missing values in a DataFrame.
    Index.isna : Detect missing values in an Index.

    Examples
    --------
    Scalar arguments (including strings) result in a scalar boolean.

    >>> pd.isna('dog')
    False

    >>> pd.isna(np.nan)
    True


问:
Why postgres "scan index(btree)" phase of plan returns all rows?
I have some misunderstanding with btree using Postgres 9.6.

I'm using SELECT max(total_amount) FROM bookings;

Total rows count 2111110, total_amount - numeric(10,2)

I have index on this column

```<code>CREATE INDEX ON bookings USING btree (total_amount);
</code>```

When I'm using explain I see:

And as I know Btree is ordered tree, so to find min key value you should go left from root to end, maximum - right

So why postgres gets all rows but not one from scan index node?

答:
What you posted is an execution plan, and the numbers are estimates, not true counts.  A quirk of the way execution plans are reported is that the estimated number of rows for the node assumes the node will run to completion.  Note that the LIMIT node above it then scales back both the row estimate and the cost estimate to account for the fact that it is expected to stop early.  It would be possible to push that scale back reporting from the LIMIT node down to the lower node, but that is just not the accounting convention that has been used.

If you do the EXPLAIN (ANALYZE) of the plan, it would also report actual counts, and you would see that the actual count is 1.  It is a bit confusing that the estimated counts and the actual counts are not reported on the same basis here.

Body:
I have some misunderstanding with btree using Postgres 9.6.

I'm using SELECT max(total_amount) FROM bookings;

Total rows count 2111110, total_amount - numeric(10,2)

I have index on this column

CREATE INDEX ON bookings USING btree (total_amount);

When I'm using explain I see:

And as I know Btree is ordered tree, so to find min key value you should go left from root to end, maximum - right

So why postgres gets all rows but not one from scan index node?


问:
Why 'wait with predicate' solves the 'lost wakeup' for condition variable?
I am trying to understand the difference between spurious vs lost wakeup in case of a condition variable. Following is small piece code I tried. I understand that 'consumer' in this case could wake up without any notification and therefore the wait needs to check for predicate.

But how does wait with predicate solves the issue of 'lost wakeup'? As you can see in code below; 'wait' is not called for 5 seconds and I was expecting it to miss first few notifications; but with predate, it does not miss any. Are these notifications saved for future wait?

```<code>#include <iostream>
#include <deque>
#include <condition_variable>
#include <thread>

std::deque<int> q;
std::mutex m;
std::condition_variable cv;

void dump_q()
{
    for (auto x: q) {
        std::cout << x << std::endl;
    }
}

void producer()
{
    for(int i = 0; i < 10; i++) {
        std::unique_lock<std::mutex> locker(m);
        q.push_back(i);
        std::cout << "produced: " << i << std::endl;
        cv.notify_one();

        std::this_thread::sleep_for(std::chrono::seconds(1));
        locker.unlock();
    }
}

void consumer()
{
    while (true) {
        int data = 0;
        std::this_thread::sleep_for(std::chrono::seconds(5));   // <- should miss first 5 notications?
        std::unique_lock<std::mutex> locker(m);
        cv.wait(locker);
        //cv.wait(locker, [](){return !q.empty();});  // <- this fixes both spurious and lost wakeups
        data = q.front();
        q.pop_front();
        std::cout << "--> consumed: " << data << std::endl;
        locker.unlock();
    }
}

int main(int argc, char *argv[])
{
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join();
    t2.join();
    return 0;
}
</code>```

答:
It is the atomic "unlock and wait" operation that prevents lost wakeups. A lost wakeup happens this way:

We acquire the lock that protects the data.

We check to see whether we need to wait and we see that we do.

We need to release the lock because otherwise no other thread can access the data.

We wait for a wakeup.

You can see the risk of a lost wakeup here. Between steps 3 and 4, another thread could acquire the lock and send a wakeup. We have released the lock, so another thread can do this, but we aren't waiting yet, so we wouldn't get the signal.

So long as step 2 is done under the protection of the lock and steps 3 and 4 are atomic, there is no risk of a lost wakeup. A wakeup cannot be sent until the data is modified which cannot be done until another thread acquires the lock. Since 3 and 4 are atomic, any thread that sees the lock as unlocked will necessarily also see us waiting.

This atomic "unlock and wait" is the primary purpose of condition variables and the reason they must always be associated with a mutex and a predicate.

In code above, consumer is not waiting for first few notifications because it is sleeping. Is it not missing notify in this case? Is this case not similar to race condition between #3 and #4?

Nope. Can't happen.

Either the consumer that is not waiting holds the lock or it doesn't. If the consumer that is not waiting holds the lock, it can't miss anything. The predicate cannot change when it holds the lock.

If the consumer is not holding the lock, then it doesn't matter what it misses. When it checks to see whether it should lock in step 2, if it missed anything, it will necessarily see it in step 2 and it will see that it does not need to wait, so it will not wait for the wakeup that it missed.

So if the predicate is such that the thread does not need to wait, the thread will not wait because it checks the predicate. There is no opportunity for a missed wakeup prior to step 1.

The only time an actual wakeup is needed is if a thread goes to sleep. The atomic unlock and sleep ensures that a thread can only decide to go to sleep while it holds the lock and while the thing it needs to wait for has not yet happened.

Body:
I am trying to understand the difference between spurious vs lost wakeup in case of a condition variable. Following is small piece code I tried. I understand that 'consumer' in this case could wake up without any notification and therefore the wait needs to check for predicate.

But how does wait with predicate solves the issue of 'lost wakeup'? As you can see in code below; 'wait' is not called for 5 seconds and I was expecting it to miss first few notifications; but with predate, it does not miss any. Are these notifications saved for future wait?

#include <iostream>
#include <deque>
#include <condition_variable>
#include <thread>

std::deque<int> q;
std::mutex m;
std::condition_variable cv;

void dump_q()
{
    for (auto x: q) {
        std::cout << x << std::endl;
    }
}

void producer()
{
    for(int i = 0; i < 10; i++) {
        std::unique_lock<std::mutex> locker(m);
        q.push_back(i);
        std::cout << "produced: " << i << std::endl;
        cv.notify_one();

        std::this_thread::sleep_for(std::chrono::seconds(1));
        locker.unlock();
    }
}

void consumer()
{
    while (true) {
        int data = 0;
        std::this_thread::sleep_for(std::chrono::seconds(5));   // <- should miss first 5 notications?
        std::unique_lock<std::mutex> locker(m);
        cv.wait(locker);
        //cv.wait(locker, [](){return !q.empty();});  // <- this fixes both spurious and lost wakeups
        data = q.front();
        q.pop_front();
        std::cout << "--> consumed: " << data << std::endl;
        locker.unlock();
    }
}

int main(int argc, char *argv[])
{
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join();
    t2.join();
    return 0;
}


问:
Does overflow:hidden applied to  work on iPhone Safari?
Does overflow:hidden applied to  work on iPhone Safari? It seems not.
I can't create a wrapper on the whole website to achieve that...

Do you know the solution?

Example: I have a long page, and simply I want to hide the content that goes underneath the "fold", and it should work on iPhone/iPad.

答:
Here is what I did: I check the body y position , then make the body fixed and adjust the top to the negative of that position. On reverse, I make the body static and set the scroll to the value I recorded before.</p>

```<code>var body_x_position = 0;

function disable_bk_scrl(){

    var elb = document.querySelector('body');

    body_x_position = elb.scrollTop;
    // get scroll position in px

    var body_x_position_m = body_x_position*(-1);
    console.log(body_x_position);

    document.body.style.position = "fixed";

    $('body').css({ top: body_x_position_m });

}

function enable_bk_scrl(){

    document.body.style.position = "static";

    document.body.scrollTo(0, body_x_position);

    console.log(body_x_position);
}
</code>```

Title: Does overflow:hidden applied to <body> work on iPhone Safari?

Body:
Here is what I did: I check the body y position , then make the body fixed and adjust the top to the negative of that position. On reverse, I make the body static and set the scroll to the value I recorded before.

var body_x_position = 0;

function disable_bk_scrl(){

    var elb = document.querySelector('body');

    body_x_position = elb.scrollTop;
    // get scroll position in px

    var body_x_position_m = body_x_position*(-1);
    console.log(body_x_position);

    document.body.style.position = "fixed";

    $('body').css({ top: body_x_position_m });

}

function enable_bk_scrl(){

    document.body.style.position = "static";

    document.body.scrollTo(0, body_x_position);

    console.log(body_x_position);
}


问:
why am I getting the following errors : In constructor 'B::B(int, int)': no matching function for call to 'A::A()'
I'm getting errors and don't know what is wrong

I've tried leaving out the constructors.

i'm getting the following errors:

In constructor 'B::B(int, int)': no matching function for call to 'A::A()'

note candidates are:

A::A(const A&)

A::A(int, int)

```<code>#include <iostream>
using namespace std;

class A{
  public:
         int a;
         int b;
         A(int a1, int b1){
               a=a1; b = b1;
               }
  };

class B : public A {
  public:
         int c;
         int d;
         int e;
         B(int c1=10, int d1=20){
               c=c1; d=d1;
               e = a * b;
               }
  void show(){
       cout <<"a = "<<a<<endl;
       cout <<"b = "<<b<<endl;
       cout <<"c = "<<c<<endl;
       cout <<"d = "<<d<<endl;
       cout <<"e = "<<e<<endl;
       }
  };

int main() {
  A a(2,2);
  B b;
  b.show();
  return 0;
}
</code>```

答:
B inherits from A so it needs to construct an A but you don't have a default constructor for A nor do you explicitly call a constructor for A from B's initialization list.

Something like this is what you need:

```<code>B(int c1=10, int d1=20) : A(c1, d1) {
               c=c1; d=d1;
               e = a * b;
               }
</code>```

Or make A default constructible.

Also, you should be using the initialization list for c, d, and e as well, instead of assigning to the in the body of your constructor (though the optimizer will take care of it in this situation, it's better form to do it the right way all the time)

```<code>B(int c1=10, int d1=20) : A(c1, d1), c(c1), d(d1), e(a*b) {}
</code>```

Body:
I'm getting errors and don't know what is wrong

I've tried leaving out the constructors.

i'm getting the following errors:

In constructor 'B::B(int, int)': no matching function for call to 'A::A()'

note candidates are:

A::A(const A&)

A::A(int, int)

#include <iostream>
using namespace std;

class A{
  public:
         int a;
         int b;
         A(int a1, int b1){
               a=a1; b = b1;
               }
  };

class B : public A {
  public:
         int c;
         int d;
         int e;
         B(int c1=10, int d1=20){
               c=c1; d=d1;
               e = a * b;
               }
  void show(){
       cout <<"a = "<<a<<endl;
       cout <<"b = "<<b<<endl;
       cout <<"c = "<<c<<endl;
       cout <<"d = "<<d<<endl;
       cout <<"e = "<<e<<endl;
       }
  };

int main() {
  A a(2,2);
  B b;
  b.show();
  return 0;
}

Body:
B inherits from A so it needs to construct an A but you don't have a default constructor for A nor do you explicitly call a constructor for A from B's initialization list.

Something like this is what you need:

B(int c1=10, int d1=20) : A(c1, d1) {
               c=c1; d=d1;
               e = a * b;
               }

Or make A default constructible.

Also, you should be using the initialization list for c, d, and e as well, instead of assigning to the in the body of your constructor (though the optimizer will take care of it in this situation, it's better form to do it the right way all the time)

B(int c1=10, int d1=20) : A(c1, d1), c(c1), d(d1), e(a*b) {}


问:
Pairwise substration table
My dataset looks like this:

```<code>Col1 Col2
A     2
B     5
C     1
D     4
</code>```

I would like to substract rows from Col2 so that the final output looks like this:

```<code>    A   B   C   D
A   0  -3   1  -2
B   3   0   4   1
C  -1  -4   0  -3
D   2  -1   3   0
</code>```

I would appreciate some help as I am struggling formatting the results into a pairwise comparison table.

答:
Using outer is definitely a good option. For instance:

```<code>x2 <- 1:4; names(x2) <- c("A","B","C","D")
x3 <- 1:4; names(x3) <- c("A","B","C","D")

outer(x2,x3, "-")

  [,1] [,2] [,3] [,4]
A    0   -1   -2   -3
B    1    0   -1   -2
C    2    1    0   -1
D    3    2    1    0
</code>```

Thanks @jogo for the suggestion

Title: Pairwise substration table

Body:
My dataset looks like this:

Col1 Col2
A     2
B     5
C     1
D     4

I would like to substract rows from Col2 so that the final output looks like this:

    A   B   C   D
A   0  -3   1  -2
B   3   0   4   1
C  -1  -4   0  -3
D   2  -1   3   0

I would appreciate some help as I am struggling formatting the results into a pairwise comparison table.

Body:
Using outer is definitely a good option. For instance:

x2 <- 1:4; names(x2) <- c("A","B","C","D")
x3 <- 1:4; names(x3) <- c("A","B","C","D")

outer(x2,x3, "-")

  [,1] [,2] [,3] [,4]
A    0   -1   -2   -3
B    1    0   -1   -2
C    2    1    0   -1
D    3    2    1    0

Thanks @jogo for the suggestion


问:
.findAll() finds nothing from webpage
In order to pull out reviews from google store, I am trying to learn the library beautiful soup. I wrote a code that should get me all reviews (including the star rating, date and name of reviewer) but the output is just an empty list. The problem is probably something very basic that I am just too inexperienced to know of.

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
my_url = 'https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true'
uclient = urlopen(my_url)
page_html = uclient.read()
uclient.close()
page_soup = soup(page_html, "html.parser")
reviews = page_soup.findAll("div",{"class":'d15Mdf bAhLNe'})
len(reviews)
</code>```

The output is 0.

What should I do in order to fix this?

答:
You need to scroll to get all reviews which requires browser automation e.g. selenium (the POST request which does batch updates doesn't look easy to copy.

If you only want the page 1 , before scroll, reviews you can regex them out (my regex isn't good enough to get in one go)

```<code>import requests
import re

url = "https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true"
r = requests.get(url)
p = re.compile(r'gp:AOqpTOH5kmss3scHG0QoYWgIF-BGIBxKlo-1-KRNg2GEzHXfpccogYalrSCBLbjLp-Y4h-T69r-4nFVYuea8Zg",(.*)\);</script><script aria-hidden="true"', re.DOTALL)
data = p.findall(r.text)[0]
p2 = re.compile(r'"(.*?)",|\d{21}')
items = p2.findall(data)
x = 0
for i in items:
    if re.search(r'(\d{21})', i):
        #print(i)
        print( items[x-2], ' : ' , items[x-1])
    x+=1
</code>```

Title: .findAll() finds nothing from webpage

Body:
In order to pull out reviews from google store, I am trying to learn the library beautiful soup. I wrote a code that should get me all reviews (including the star rating, date and name of reviewer) but the output is just an empty list. The problem is probably something very basic that I am just too inexperienced to know of.

from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
my_url = 'https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true'
uclient = urlopen(my_url)
page_html = uclient.read()
uclient.close()
page_soup = soup(page_html, "html.parser")
reviews = page_soup.findAll("div",{"class":'d15Mdf bAhLNe'})
len(reviews)

The output is 0.

What should I do in order to fix this?

Body:
You need to scroll to get all reviews which requires browser automation e.g. selenium (the POST request which does batch updates doesn't look easy to copy.

If you only want the page 1 , before scroll, reviews you can regex them out (my regex isn't good enough to get in one go)

import requests
import re

url = "https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true"
r = requests.get(url)
p = re.compile(r'gp:AOqpTOH5kmss3scHG0QoYWgIF-BGIBxKlo-1-KRNg2GEzHXfpccogYalrSCBLbjLp-Y4h-T69r-4nFVYuea8Zg",(.*)\);</script><script aria-hidden="true"', re.DOTALL)
data = p.findall(r.text)[0]
p2 = re.compile(r'"(.*?)",|\d{21}')
items = p2.findall(data)
x = 0
for i in items:
    if re.search(r'(\d{21})', i):
        #print(i)
        print( items[x-2], ' : ' , items[x-1])
    x+=1


问:
How to correctly access props in vue.js without passing through the div
I have an api call being executed in the create hook in my vue root.  Then I have a component which is trying to use the data returned from the api call.

My question is very simple.  The example below works but is there a way to just have <stage-execs></stage-execs> without passing in job_execs = job_execs ?

I prefer the cleaner look of just using <stage-execs></stage-execs>

```<code>    <div id="vue-job">
    <div class="column">
        <div class="row">
            <stage-execs v-bind:job_execs=job_execs></stage-execs>
        <br><br>
    </div>
    </div>

<script>
    Vue.component('stage-execs', {
        delimiters: [ '[[', ']]' ],
        props: ['job_execs'],
        template: `
        <ul id="example-1">
          <h3>Stages</h3>
          <li v-for="item in this.job_execs">
            [[ item.build_id ]]
          </li>
        </ul>
        `,

var v_root = new Vue({
    delimiters: [ '[[', ']]' ],
    el: '#vue-job',
    data: {
        job_execs: []
    },
    created() {
        url="http://{{ api_endpoint }}"
        fetch(url)
            .then(response => response.json())
            .then(body => {
                for(i=0; i<body.length; i++){
                    this.job_execs.push({
                        'build_id': JSON.stringify(body[i].build_id),
                        'status': JSON.stringify(body[i].status.name),
                    })
                }
        })
        .catch( err => {
            console.log('Error Fetching:', url, err);
            return { 'failure': url, 'reason': err };
        });

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

答: No you can't. The best you can do is lose the v-bind, so :job_execs=job_execs. (The : is a shorthand for v-bind)

Body:
I have an api call being executed in the create hook in my vue root.  Then I have a component which is trying to use the data returned from the api call.

My question is very simple.  The example below works but is there a way to just have <stage-execs></stage-execs> without passing in job_execs = job_execs ?

I prefer the cleaner look of just using <stage-execs></stage-execs>

            <stage-execs v-bind:job_execs=job_execs></stage-execs>


问:
Are character constants always positive?
I'm curious if I can compile

```<code>int map [] = { [ /*(unsigned char)*/ 'a' ]=1 };
</code>```

regardless of platform or if it's better to cast character constants to unsigned char prior to using them as indices.

答:
I'm curious if I can compile

```<code>int map [] = { [ /*(unsigned char)*/ 'a' ]=1 };
</code>```

regardless of platform or if it's better to cast character constants
  to unsigned char prior to using them as indices.

Your specific code is safe.

'a' is an integer character constant.  The language specifies of these that

An integer character constant has type int. The value of an integer
  character constant containing a single character that maps to a
  single-byte execution character is the numerical value of the
  representation of the mapped character interpreted as an integer. [...]
  If an integer character constant contains a
  single character or escape sequence, its value is the one that results
  when an object with type char whose value is that of the single
  character or escape sequence is converted to type int.

(C2011, paragraph 6.4.4.4/10)

It furthermore specifies that

If a member of the basic execution character set is stored in a char object, its value is guaranteed to be nonnegative.

(C2011, paragraph 6.2.5/3)

and it requires of every implementation that both the basic source and basic execution character sets contain, among other characters, the lowercase Latin letters, including 'a'.  (C2011, paragraph 5.2.1/3)

You should take care, however: an integer character constant for a character that is not a member of the basic execution character set, including a multibyte character, or for a multi-character integer character constant does need not to be nonnegative.  Some of those could, in principle, be negative even on machines where default char is an unsigned type.

Moreover, again considering multibyte characters, the cast to unsigned char is not necessarily safe either, in that you could produce collisions that way.  To be sure to avoid collisions, you would need to convert to unsigned int, but that could produce much larger arrays than you expect.  If you stick to the basic character sets  then you're ok.  If you stick to single-byte characters then you're ok with a cast.  If you must accommodate multibyte characters then for portability, you should probably choose a different approach.

Body:
I'm curious if I can compile

int map [] = { [ /*(unsigned char)*/ 'a' ]=1 };

regardless of platform or if it's better to cast character constants
  to unsigned char prior to using them as indices.

Your specific code is safe.

'a' is an integer character constant.  The language specifies of these that

An integer character constant has type int. The value of an integer
  character constant containing a single character that maps to a
  single-byte execution character is the numerical value of the
  representation of the mapped character interpreted as an integer. [...]
  If an integer character constant contains a
  single character or escape sequence, its value is the one that results
  when an object with type char whose value is that of the single
  character or escape sequence is converted to type int.

(C2011, paragraph 6.4.4.4/10)

It furthermore specifies that

If a member of the basic execution character set is stored in a char object, its value is guaranteed to be nonnegative.

(C2011, paragraph 6.2.5/3)

and it requires of every implementation that both the basic source and basic execution character sets contain, among other characters, the lowercase Latin letters, including 'a'.  (C2011, paragraph 5.2.1/3)

You should take care, however: an integer character constant for a character that is not a member of the basic execution character set, including a multibyte character, or for a multi-character integer character constant does need not to be nonnegative.  Some of those could, in principle, be negative even on machines where default char is an unsigned type.

Moreover, again considering multibyte characters, the cast to unsigned char is not necessarily safe either, in that you could produce collisions that way.  To be sure to avoid collisions, you would need to convert to unsigned int, but that could produce much larger arrays than you expect.  If you stick to the basic character sets  then you're ok.  If you stick to single-byte characters then you're ok with a cast.  If you must accommodate multibyte characters then for portability, you should probably choose a different approach.


问:
If my interface must return Task what is the best way to have a no-operation implementation?
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?

I have gone with Task.Delay(0) below, however I would like to know if this has any performance side-effects if the function is called a lot (for argument's sake, say hundreds of times a second):

Does this syntactic sugar un-wind to something big?

Does it start clogging up my application's thread pool?

Is the compiler cleaver enough to deal with Delay(0) differently?

Would return Task.Run(() => { }); be any different?

Is there a better way?

```<code>using System.Threading.Tasks;

namespace MyAsyncTest
{
    internal interface IFooFace
    {
        Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
    }

    /// <summary>
    /// An implementation, that unlike most cases, will not have a long-running
    /// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
    /// </summary>
    internal class LazyBar : IFooFace
    {
        #region IFooFace Members

        public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
            // First, do something really quick
            var x = 1;

            // Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
            // Is it a real no-op, or if I call this a lot, will it adversely affect the
            // underlying thread-pool? Better way?
            return Task.Delay(0);

            // Any different?
            // return Task.Run(() => { });

            // If my task returned something, I would do:
            // return Task.FromResult<int>(12345);
        }

        #endregion
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Test();
        }

        private static async void Test()
        {
            IFooFace foo = FactoryCreate();
            await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
            return;
        }

        private static IFooFace FactoryCreate()
        {
            return new LazyBar();
        }
    }
}
</code>```

答:
When you must return specified type:</p>

```<code>Task.FromResult<MyClass>(null);
</code>```

Body:
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?

I have gone with Task.Delay(0) below, however I would like to know if this has any performance side-effects if the function is called a lot (for argument's sake, say hundreds of times a second):

Does this syntactic sugar un-wind to something big?

Does it start clogging up my application's thread pool?

Is the compiler cleaver enough to deal with Delay(0) differently?

Would return Task.Run(() => { }); be any different?

Is there a better way?

using System.Threading.Tasks;

namespace MyAsyncTest
{
    internal interface IFooFace
    {
        Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
    }

    ///
    /// An implementation, that unlike most cases, will not have a long-running
    /// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
    ///
    internal class LazyBar : IFooFace
    {
        #region IFooFace Members

        public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
            // First, do something really quick
            var x = 1;

            // Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
            // Is it a real no-op, or if I call this a lot, will it adversely affect the
            // underlying thread-pool? Better way?
            return Task.Delay(0);

            // Any different?
            // return Task.Run(() => { });

            // If my task returned something, I would do:
            // return Task.FromResult<int>(12345);
        }

        #endregion
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Test();
        }

        private static async void Test()
        {
            IFooFace foo = FactoryCreate();
            await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
            return;
        }

        private static IFooFace FactoryCreate()
        {
            return new LazyBar();
        }
    }
}

Body:
When you must return specified type:

Task.FromResult<MyClass>(null);


问:
Flask url_for generates http instead of https when running by docker
I have a flask app running in docker, and setup nginx with Let’s Encrypt. I've added proxy_set_header X-Forwarded-Proto $scheme; to my nginx config, but url_for still returns http url instead https url. But the issue only occurs when running in docker.

This is my nginx config:

```<code>server {
    listen 443 ssl default_server;
    ssl_certificate /etc/letsencrypt/live/markote.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/markote.app/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
</code>```

and my docker file:

```<code>FROM python:3.6-slim

WORKDIR /app

ADD . /app

RUN apt update
RUN apt install -y curl sudo gnupg libcairo2-dev
RUN pip install gunicorn
RUN curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
RUN sudo apt-get install -y nodejs

RUN python setup.py install
RUN npm install
RUN npm run build

EXPOSE 5000

CMD [ "gunicorn", "-c", "gunicorn.py", "wsgi:app" ]
</code>```

If I run gunicorn -c gunicorn.py wsgi:app & instead of sudo docker run -d -p 5000:5000 my/repo, url_for can generate https successfully. Do I miss something?

答: I know it's been a while but you could try url_for('endpoint', _schema='https')

Body:
I have a flask app running in docker, and setup nginx with Let’s Encrypt. I've added proxy_set_header X-Forwarded-Proto $scheme; to my nginx config, but url_for still returns http url instead https url. But the issue only occurs when running in docker.

This is my nginx config:

server {
    listen 443 ssl default_server;
    ssl_certificate /etc/letsencrypt/live/markote.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/markote.app/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

and my docker file:

FROM python:3.6-slim

WORKDIR /app

ADD . /app

RUN apt update
RUN apt install -y curl sudo gnupg libcairo2-dev
RUN pip install gunicorn
RUN curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
RUN sudo apt-get install -y nodejs

RUN python setup.py install
RUN npm install
RUN npm run build

EXPOSE 5000

CMD [ "gunicorn", "-c", "gunicorn.py", "wsgi:app" ]

If I run gunicorn -c gunicorn.py wsgi:app & instead of sudo docker run -d -p 5000:5000 my/repo, url_for can generate https successfully. Do I miss something?


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
it might not be the "intented" use but I've used it for data serialization</p>

```<code>storeToHardDrive(studentList.ToString());
</code>```

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

Body:
it might not be the "intented" use but I've used it for data serialization

storeToHardDrive(studentList.ToString());

OwnerDisplayName: Eric


问:
Reading / Writing files in Javascript - IE6
I need a database storage system for Javascript where the state can be maintained on the local disk.

Here comes the spanners in the works :-

It only needs to support Internet Explorer but the minimum version must be IE6

Files need to be written so they can be read in again later (upon closing and re-opening of browser)

There can be no web server (unless it's extremely easy to distribute and does not require a install) since the HTML pages will be distributed on USB.

Does anyone know of any solutions that might help here?

答: For strictly local IE work use HTA Applications. Then you can access local resources (text files, ADO databases) without security problems.</p>


问:
Why is my timer not working on Unity whenever I stop clicking?
I am working on an Unity project and I need to count the time the user takes to make his next move.

Every object in the game moves by using the mouse and dragging it so whenever the user stops dragging the main object the timer should start and when the user drags the object again it should stop.

This is my script for the drag and the timer:

```<code>private float startPosX;
    private float startPosY;
    public bool isHeld;
    //private float distance = 10;
    private float stopTime;

private void OnMouseDrag()
{
        Vector2 mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector2 objectPos = Camera.main.ScreenToWorldPoint(mousePos);
        transform.position = objectPos;
}

void Update()
{
    if (isHeld) {
        OnMouseDrag();
    }
    if (Input.GetMouseButtonUp(0))
    {
        isHeld = false;
        Debug.Log(isHeld);
        stopTime += Time.deltaTime;
        string minutes = Mathf.Floor((stopTime % 3600) / 60).ToString("00");
        string seconds = (stopTime % 60).ToString("00");
        Debug.Log(minutes + ":" + seconds);
    }
}

private void OnMouseOver()
{
    if (Input.GetMouseButtonDown(0)) {
        isHeld = true;
        Debug.Log(isHeld);
    }
}
</code>```

}

My onMouseDrag() is the actual function used to drag the object and on onMouseOver detects if the mouse is actually over the object.
The timer is given by deltaTime and then I use string minutes and seconds to display it in a nicer way and see if it is working correctly but it is not. I do not know why this is not working and I need some help because I am new to unity and coding.

答:
You'll want to read over the documentation for the Input class, in particular the GetMouseButtonUp function that you're checking:

Returns true during the frame the user releases the given mouse
  button.

You need to call this function from the Update function, since the
  state gets reset each frame. It will not return true until the user
  has pressed the mouse button and released it again. button values are
  0 for left button, 1 for right button, 2 for the middle button.

You may have misunderstood what that function is doing.

This logs one message per click or release:

```<code>void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("once per click: mouse button clicked");
    }
    if (Input.GetMouseButtonUp(0)) {
        Debug.Log("once per click: mouse button released");
    }
}
</code>```

This logs one message per frame:

```<code>void Update() {
    if (Input.GetMouseButton(0)) {
        Debug.Log("once per frame: mouse button held");
    } else {
        Debug.Log("once per frame: mouse button NOT held");
    }
}
</code>```

It just depends if you want something to happen once per click/release, or once per frame.

Body:
I am working on an Unity project and I need to count the time the user takes to make his next move.

Every object in the game moves by using the mouse and dragging it so whenever the user stops dragging the main object the timer should start and when the user drags the object again it should stop.

This is my script for the drag and the timer:

private float startPosX;
    private float startPosY;
    public bool isHeld;
    //private float distance = 10;
    private float stopTime;

private void OnMouseDrag()
{
        Vector2 mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector2 objectPos = Camera.main.ScreenToWorldPoint(mousePos);
        transform.position = objectPos;
}

void Update()
{
    if (isHeld) {
        OnMouseDrag();
    }
    if (Input.GetMouseButtonUp(0))
    {
        isHeld = false;
        Debug.Log(isHeld);
        stopTime += Time.deltaTime;
        string minutes = Mathf.Floor((stopTime % 3600) / 60).ToString("00");
        string seconds = (stopTime % 60).ToString("00");
        Debug.Log(minutes + ":" + seconds);
    }
}

private void OnMouseOver()
{
    if (Input.GetMouseButtonDown(0)) {
        isHeld = true;
        Debug.Log(isHeld);
    }
}

}

My onMouseDrag() is the actual function used to drag the object and on onMouseOver detects if the mouse is actually over the object.
The timer is given by deltaTime and then I use string minutes and seconds to display it in a nicer way and see if it is working correctly but it is not. I do not know why this is not working and I need some help because I am new to unity and coding.

Body:
You'll want to read over the documentation for the Input class, in particular the GetMouseButtonUp function that you're checking:

Returns true during the frame the user releases the given mouse
  button.

You need to call this function from the Update function, since the
  state gets reset each frame. It will not return true until the user
  has pressed the mouse button and released it again. button values are
  0 for left button, 1 for right button, 2 for the middle button.

You may have misunderstood what that function is doing.

This logs one message per click or release:

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("once per click: mouse button clicked");
    }
    if (Input.GetMouseButtonUp(0)) {
        Debug.Log("once per click: mouse button released");
    }
}

This logs one message per frame:

void Update() {
    if (Input.GetMouseButton(0)) {
        Debug.Log("once per frame: mouse button held");
    } else {
        Debug.Log("once per frame: mouse button NOT held");
    }
}

It just depends if you want something to happen once per click/release, or once per frame.


问:
How to lay out specified number of objects per row?
I have an angular project where I need to place items in a grid format. I need two items per row in a card-like format. For example, where my array is:

myfruit:fruit[] = [new fruit(1,"apple","red fruit"),
                   new fruit(2,"banana","yellow fruit"),
                   new fruit(3,"orange","orange fruit")]
}

class fruit{
  public id:number;
  public name:string;
  public description:string;

  constructor(id:number,name:string,description:string){
    this.id=id;
    this.name = name;
    this.description = description;
  }
```

<p>The corresponding HTML:</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="fruit in myfruit">
  <div *ngFor="let i = 0; i < 2;i++">
    <h1>{{fruit.name}}</h1>
    <p>{{fruit.description}}</p>
  </div>
</div>
</code>```

Is this the correct way to lay out my items in rows of two?

答:
If you want to do it via javascript, you could chunk your collection by 2 and loop that on the outer layer.

```<code><div *ngFor="let fruitChunk of chunkArray(myfruit, 2)">
  <div *ngFor="let fruit of fruitChunk">
    <h1>{{fruit.name}}</h1>
    <p>{{fruit.description}}</p>
  </div>
</div>
</code>```

Chunk function:

```<code>function chunkArray(myArray, chunk_size){
    var index = 0;
    var arrayLength = myArray.length;
    var tempArray = [];

    for (index = 0; index < arrayLength; index += chunk_size) {
        var myChunk = myArray.slice(index, index+chunk_size);
        // Do something if you want with the group
        tempArray.push(myChunk);
    }

    return tempArray;
}
</code>```

Source: Link

Body:
I have an angular project where I need to place items in a grid format. I need two items per row in a card-like format. For example, where my array is:

myfruit:fruit[] = [new fruit(1,"apple","red fruit"),
                   new fruit(2,"banana","yellow fruit"),
                   new fruit(3,"orange","orange fruit")]
}

class fruit{
  public id:number;
  public name:string;
  public description:string;

  constructor(id:number,name:string,description:string){
    this.id=id;
    this.name = name;
    this.description = description;
  }

The corresponding HTML:

  <div *ngFor="let i = 0; i < 2;i++">

{{fruit.name}}

{{fruit.description}}

Is this the correct way to lay out my items in rows of two?

Body:
If you want to do it via javascript, you could chunk your collection by 2 and loop that on the outer layer.

<div *ngFor="let fruitChunk of chunkArray(myfruit, 2)">
  <div *ngFor="let fruit of fruitChunk">
    <h1>{{fruit.name}}</h1>
    <p>{{fruit.description}}</p>
  </div>
</div>

Chunk function:

function chunkArray(myArray, chunk_size){
    var index = 0;
    var arrayLength = myArray.length;
    var tempArray = [];

    for (index = 0; index < arrayLength; index += chunk_size) {
        var myChunk = myArray.slice(index, index+chunk_size);
        // Do something if you want with the group
        tempArray.push(myChunk);
    }

    return tempArray;
}

Source: Link


问:
Create a button that will switch the font color of the text of the cell between black and white, adjacent to the currently pointing cell
I am creating a google spreadsheet having two columns. Question and Answers.
Let's consider there are 100 pairs of cells of questions and answers.
All the questions have font color as black and answers have font color as white.
If the current cell is pointing to one question then I want to create a button which upon clicking will change the font color to black and so the answer will be visible for its adjacent cell.

Is there any way to do this?

答: you can do this without heavy scripting with just conditional formatting and simple checkboxes:


问:
Html element not taking up its full width with absolute positioning and inside flexbox
This gray block (https://jsfiddle.net/var6u4g7/) on the right doesn't take up the full width of it's content. It's using the size of the righttext, if you add more words in the righttext element you'll see the grey box is taking up exactly that width. I don't want to assign a fixed width because I don't know how much will be inside it, so I want it to be as wide as its content.

If you remove display: flex on the first element then the width works but other things break. (If you remove the grey box you'll see why I need display: flex. The grey box only appears sometimes, and when it's not there all the content in that row should be vertically center aligned. Is there a way to make this work?

.container {
  display: flex;
  align-items: center;
  background-color: yellow;
}

.leftside {
  margin-right: auto;
}

.rightside {
  position: relative;
}

.righttext {
  background-color: red;
  margin-top: 10px;
  margin-bottom: 10px;
}

.absolute {
  position: absolute;
  right: 0;
  top: 0;
  background-color: gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="leftside">Lorem ipsum dolor sit amet.</div>
  <div class="rightside">
    <div class="righttext">
      Lorem ipsum.
    </div>
    <div class="absolute">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit.
    </div>
  </div>
</div></code>```

答: It's unclear from the question exactly what you are looking for, but if I do understand correctly, you want the red and gray boxes to be full-width. You can do this by adding flex: 1 to .rightside and width: 100%; to .absolute. The flex property indicates that a certain element should take priority. It's shorthand for flex-grow: 1.

Body:
This gray block (https://jsfiddle.net/var6u4g7/) on the right doesn't take up the full width of it's content. It's using the size of the righttext, if you add more words in the righttext element you'll see the grey box is taking up exactly that width. I don't want to assign a fixed width because I don't know how much will be inside it, so I want it to be as wide as its content.

If you remove display: flex on the first element then the width works but other things break. (If you remove the grey box you'll see why I need display: flex. The grey box only appears sometimes, and when it's not there all the content in that row should be vertically center aligned. Is there a way to make this work?

.container {
  display: flex;
  align-items: center;
  background-color: yellow;
}

.leftside {
  margin-right: auto;
}

.rightside {
  position: relative;
}

.righttext {
  background-color: red;
  margin-top: 10px;
  margin-bottom: 10px;
}

.absolute {
  position: absolute;
  right: 0;
  top: 0;
  background-color: gray;
}

Lorem ipsum dolor sit amet.

      Lorem ipsum.

      Lorem ipsum dolor sit amet, consectetur adipisicing elit.


问:
How to display image from a js file in react?
I'm new at programming and very new to React. I'm trying to display an image that comes from a data.js file. I'm getting datas, but not the image. My console.log displays the image path correctly. I know my path is ok because I've tried to import the image and it works fine.

I've tried to create a .env file to mention NODE_PATH=src so I can have absolute path, but that doesn't work either, and I think this a deprecated way to handle absolute path.
I've also tried to put some random url image from google, but it wouldn't work either. That makes me think my problem is not about path.

```<code>// My app.js file

import React from 'react';
import GetImages from './components/ImagesTest/getImages';
import './App.css';

function App() {
  return (
    <div className="App">
      <h1 className="header">Local Storage</h1>
      <GetImages/>
    </div>
  );
}

export default App;

// My class file
import React, { Component } from "react";
import Data from './data';

class GetImages extends Component{

    constructor(props){
        super(props);
        this.state = {
            Data: Data
        };
    }

    render(){
        const {Data} = this.state;

        return(
            <div>
            {
                 Data.map(data=>(

                     <div>
                        { console.log(data.src) }
                        <img src= {data.src} alt = {data.alt}></img>
                        <p>{data.note}</p>
                        <p>{data.w}</p>
                        <p>{data.h}</p>
                     </div>

                ))
            }

            </div>
        )
    }
}

export default GetImages;

// My data.js file

const pictures = [
    {
        "id": "4",
        "title": "the_cats",
        "place": "",
        "note": "This a cat picture",
        "datePhoto": "2018",
        "w": "5312",
        "h": "2988",
        "src": "/../cat1.jpg",
        "alt" : "cat image",
        "lblDate": "Date : ",
        "lblPlace": "Place : ",
        "lblNote": "Note : "
    }
]

export default pictures;
</code>```

Sorry if that question is to easy.. Any help would be great 'cause I'm kind of lost here. Thanks a lot !!

答:
You can try this webpack template  as a starter.

The file-load part, https://blog.cloudboost.io/webpack-for-beginners-part-1-bf8d65e58ecf explains the filer-loader to serve image file.

Body:
I'm new at programming and very new to React. I'm trying to display an image that comes from a data.js file. I'm getting datas, but not the image. My console.log displays the image path correctly. I know my path is ok because I've tried to import the image and it works fine.

I've tried to create a .env file to mention NODE_PATH=src so I can have absolute path, but that doesn't work either, and I think this a deprecated way to handle absolute path.
I've also tried to put some random url image from google, but it wouldn't work either. That makes me think my problem is not about path.

// My app.js file

import React from 'react';
import GetImages from './components/ImagesTest/getImages';
import './App.css';

function App() {
  return (

Local Storage

      <GetImages/>

  );
}

export default App;

// My class file
import React, { Component } from "react";
import Data from './data';

class GetImages extends Component{

    constructor(props){
        super(props);
        this.state = {
            Data: Data
        };
    }

    render(){
        const {Data} = this.state;

        return(

            {
                 Data.map(data=>(

                        { console.log(data.src) }

{data.note}

{data.w}

{data.h}

                ))
            }

        )
    }
}

export default GetImages;

// My data.js file

const pictures = [
    {
        "id": "4",
        "title": "the_cats",
        "place": "",
        "note": "This a cat picture",
        "datePhoto": "2018",
        "w": "5312",
        "h": "2988",
        "src": "/../cat1.jpg",
        "alt" : "cat image",
        "lblDate": "Date : ",
        "lblPlace": "Place : ",
        "lblNote": "Note : "
    }
]

export default pictures;

Sorry if that question is to easy.. Any help would be great 'cause I'm kind of lost here. Thanks a lot !!


问:
How do I use the MySQL MEMORY storage engine with Knex?
I'm using Knex and MySQL for production. I've been using SQLite in-memory for testing, but there are some minor inconsistencies, so I'd like to switch over to using MySQL in memory. Can anyone recommend a good way to do this?

The way I currently do things is that my Knex object is a singleton and has a process flag when it's being run in a test context. I was thinking that I could add something like this to my migrations:

```<code>await knex
                .schema
                .createTable('organization', table => {
                    if (knex.processFlag === 'test')
                        table.engine('MEMORY');
                    table.increments('id').primary().unsigned();
                    table.string('address');
                    table.string('city');
                    table.string('state');
                    table.string('country');
                    table.string('post_code');
                });
</code>```

Thoughts? Are there problems with this approach I'm not considering?

答:
TLDR: I don't recommend it.

I was thinking the same thing myself.  You can create in-memory tables using Knex as you suggested: table.engine('MEMORY');

However, it suffers the same problem as using SQLite, but worse.  It's not like InnoDB stored in memory instead of disk, it's a completely different engine, and it doesn't even try to behave like InnoDB.

I tried replacing InnoDB tables as you propose, and it didn't work.  When replacing just a few tables, my foreign key constraints failed.  Some tables couldn't even be created because the memory engine doesn't support Blob/Text fields.  There are probably many more differences, but I stopped there.

Update: After a little bit of research, the best solution I found was to have MySQL store its data on a tempfs mount (RAM disk.)

In my case, we use docker, and it was as simple as adding the following lines to docker-compose for the MySQL container.

```<code>tmpfs:
  - /var/lib/mysql
</code>```

Body:
I'm using Knex and MySQL for production. I've been using SQLite in-memory for testing, but there are some minor inconsistencies, so I'd like to switch over to using MySQL in memory. Can anyone recommend a good way to do this?

The way I currently do things is that my Knex object is a singleton and has a process flag when it's being run in a test context. I was thinking that I could add something like this to my migrations:

await knex
                .schema
                .createTable('organization', table => {
                    if (knex.processFlag === 'test')
                        table.engine('MEMORY');
                    table.increments('id').primary().unsigned();
                    table.string('address');
                    table.string('city');
                    table.string('state');
                    table.string('country');
                    table.string('post_code');
                });

Thoughts? Are there problems with this approach I'm not considering?

Body:
TLDR: I don't recommend it.

I was thinking the same thing myself.  You can create in-memory tables using Knex as you suggested: table.engine('MEMORY');

However, it suffers the same problem as using SQLite, but worse.  It's not like InnoDB stored in memory instead of disk, it's a completely different engine, and it doesn't even try to behave like InnoDB.

I tried replacing InnoDB tables as you propose, and it didn't work.  When replacing just a few tables, my foreign key constraints failed.  Some tables couldn't even be created because the memory engine doesn't support Blob/Text fields.  There are probably many more differences, but I stopped there.

Update: After a little bit of research, the best solution I found was to have MySQL store its data on a tempfs mount (RAM disk.)

In my case, we use docker, and it was as simple as adding the following lines to docker-compose for the MySQL container.

tmpfs:
  - /var/lib/mysql


问:
priority_queue.top() does not return the right object
I am trying to use a priority queue to return the object 'Bytetree' with lowest 'count'. Therefore i have implemented an bool operator > function in my object. But that does not seem to work, i get objects based on something else

i have tried implmenting operator< as a friend or member function and with countless modifications, but it seems never to get called at all. why not?

```<code>class Bytetree{
public:
bool leaf;
unsigned char byt;
int count;
Bytetree* child0;
Bytetree* child1;

    Bytetree(unsigned char c): byt(c), count(0), child0(nullptr), child1(nullptr), leaf(true){};
    Bytetree(Bytetree* c0, Bytetree* c1): child0(c0), child1(c1), count(c0->count+c1->count), leaf(false){};

         bool operator>(const Bytetree & right) {
    std::cout << "called at all" ;
    return count > right.count;
         }

[...]
 }
</code>```

main

...

```<code> std::priority_queue<Bytetree*, std::deque<Bytetree*>, std::greater<Bytetree*> > que;
for (int i = 0; i<WORDLENGTH; i++){

    que.push(mywc.wordar[i]);
    //  mywc.wordar[i]->print();
}

while(que.size()>=2){
    Bytetree* bt0= que.top();
    que.pop();
    Bytetree* bt1= que.top();
    que.pop();

    que.push(new Bytetree(bt0, bt1));
}
</code>```

答: You have used std::greater<Bytetree *>, but you have declared operator >  on Bytetree, not on Bytetree *.

Body:
I am trying to use a priority queue to return the object 'Bytetree' with lowest 'count'. Therefore i have implemented an bool operator > function in my object. But that does not seem to work, i get objects based on something else

i have tried implmenting operator< as a friend or member function and with countless modifications, but it seems never to get called at all. why not?

class Bytetree{
public:
bool leaf;
unsigned char byt;
int count;
Bytetree* child0;
Bytetree* child1;

    Bytetree(unsigned char c): byt(c), count(0), child0(nullptr), child1(nullptr), leaf(true){};
    Bytetree(Bytetree* c0, Bytetree* c1): child0(c0), child1(c1), count(c0->count+c1->count), leaf(false){};

         bool operator>(const Bytetree & right) {
    std::cout << "called at all" ;
    return count > right.count;
         }

[...]
 }

main

...

 std::priority_queue<Bytetree*, std::deque<Bytetree*>, std::greater<Bytetree*> > que;
for (int i = 0; i<WORDLENGTH; i++){

    que.push(mywc.wordar[i]);
    //  mywc.wordar[i]->print();
}

while(que.size()>=2){
    Bytetree* bt0= que.top();
    que.pop();
    Bytetree* bt1= que.top();
    que.pop();

    que.push(new Bytetree(bt0, bt1));
}


问:
Deleting a cell in tableview, the cell also can be reused,why?
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}
</code>```

答:
There's no reason to delete the UITableViewCell since it can be reused. That cell won't be displayed until it is processed again by cellForRowAtIndexPath, so it won't show up with the old data. The laid-out cell, though -- the view and all of its subviews -- can be reused after new data replaces the old data.

Think of it like each cell is a whiteboard (dry erase board) where it's cut down to a certain size and all of the basic information areas are etched into the surface: a place for some text, another area for a number, a special space for drawing a picture, etc. In tableView:cellForRowAtIndexPath: when you check whether the cell == nil, you're trying to find out if there are any already-etched whiteboards available that you can erase and write the new information on with your dry erase marker. If there aren't then it cuts out and etches a brand new board to write information on, but if there is one that can be erased then it just wipes off the old information with an eraser and writes in the new information. As you can imagine, this saves a lot of time.

When a user is scrolling the table what's actually happening is that when one cell (whiteboard) scrolls off the top and is no longer visible, the system erases the data and moves it to the bottom of the stack; it will be the next one to scroll into view. As a result the system only has to create as many whiteboards as can be visible at any one time -- the ones off-screen don't actually exist.

When you delete a cell all you're really doing is telling the table to (a) stop displaying that cell, and (b) setting a flag so the table can use the eraser to wipe off the old data but still reuse the whiteboard.

Creating cells can be very costly in terms of computing power. If a UITableView had to create a new cell every time one came into view while the user was scrolling -- in the analogy, if it had to cut out a new whiteboard and etch all of the areas into it every time one came into view -- the scrolling would be very jerky and look terrible. By reusing cells, replacing just the changing contents, the table can move smoothly as the user interacts with it.

Body:
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}


答:
Consider making a reproducible example the next time. (see the example I gave in the code, this will be helpful in the future when you have questions).

I used the tidyverse (dplyr package specifically) to solve this problem.

```<code>## Load library (this loads lots of packages, specifically we are using dplyr)
library(tidyverse)

## Reproducible example
data <- tibble(id = c(rep(1,8),rep(2,12)),
               time = c(rep(14,4),rep(18,2),rep(22,2),rep(8,4),12,rep(15,3),rep(19,4)))

print(data)
# A tibble: 20 x 2
      id  time
   <dbl> <dbl>
 1     1    14
 2     1    14
 3     1    14
 4     1    14
 5     1    18
 6     1    18
 7     1    22
 8     1    22
 9     2     8
10     2     8
11     2     8
12     2     8
13     2    12
14     2    15
15     2    15
16     2    15
17     2    19
18     2    19
19     2    19
20     2    19

## Data with increments for each group
new_data <- data %>%
  ##Groups your data by the same variable, in this case you want to increment by 0.25 for each id within the time group
  group_by(time) %>%
  ## Increments each id by 0.25
  mutate(new_time = ifelse((row_number() == 1), time, (0.25 * (row_number()-1)) + time)) %>%
  ## Ungroups the data
  ungroup()

print(as.data.frame(new_data))

   id time new_time
1   1   14    14.00
2   1   14    14.25
3   1   14    14.50
4   1   14    14.75
5   1   18    18.00
6   1   18    18.25
7   1   22    22.00
8   1   22    22.25
9   2    8     8.00
10  2    8     8.25
11  2    8     8.50
12  2    8     8.75
13  2   12    12.00
14  2   15    15.00
15  2   15    15.25
16  2   15    15.50
17  2   19    19.00
18  2   19    19.25
19  2   19    19.50
20  2   19    19.75
</code>```

Title: data.table generate sequence with intervals based on the first and last rows of unique ID

Body:
I have a data table like this. How would I generate a sequence with .25 step for each of the row with the same time in that ID number. I am pretty new to R and try to do some data wrangling ...

     id time
 1:  1   14
 2:  1   14
 3:  1   14
 4:  1   14
 5:  1   18
 6:  1   18
 7:  1   22
 8:  1   22
 9:  2    8
10:  2    8
11:  2    8
12:  2    8
13:  2   12
14:  2   15
15:  2   15
16:  2   15
17:  2   19
18:  2   19
19:  2   19
20:  2   19

I would like it to be like this

    id time new_time
 1:  1   14 14.00
 2:  1   14 14.25
 3:  1   14 14.50
 4:  1   14 14.75
 5:  1   18 18.00
 6:  1   18 18.25
 7:  1   22 22.00
 8:  1   22 22.25
 9:  2    8 8.00
10:  2    8 8.25
11:  2    8 8.50
12:  2    8 8.75
13:  2   12 12.00
14:  2   15 15.00
15:  2   15 15.25
16:  2   15 15.50
17:  2   19 19.00
18:  2   19 19.25
19:  2   19 19.50
20:  2   19 19.75

Body:
Consider making a reproducible example the next time. (see the example I gave in the code, this will be helpful in the future when you have questions).

I used the tidyverse (dplyr package specifically) to solve this problem.

## Load library (this loads lots of packages, specifically we are using dplyr)
library(tidyverse)

## Reproducible example
data <- tibble(id = c(rep(1,8),rep(2,12)),
               time = c(rep(14,4),rep(18,2),rep(22,2),rep(8,4),12,rep(15,3),rep(19,4)))

print(data)
# A tibble: 20 x 2
      id  time
   <dbl> <dbl>
 1     1    14
 2     1    14
 3     1    14
 4     1    14
 5     1    18
 6     1    18
 7     1    22
 8     1    22
 9     2     8
10     2     8
11     2     8
12     2     8
13     2    12
14     2    15
15     2    15
16     2    15
17     2    19
18     2    19
19     2    19
20     2    19

## Data with increments for each group
new_data <- data %>%
  ##Groups your data by the same variable, in this case you want to increment by 0.25 for each id within the time group
  group_by(time) %>%
  ## Increments each id by 0.25
  mutate(new_time = ifelse((row_number() == 1), time, (0.25 * (row_number()-1)) + time)) %>%
  ## Ungroups the data
  ungroup()

print(as.data.frame(new_data))

   id time new_time
1   1   14    14.00
2   1   14    14.25
3   1   14    14.50
4   1   14    14.75
5   1   18    18.00
6   1   18    18.25
7   1   22    22.00
8   1   22    22.25
9   2    8     8.00
10  2    8     8.25
11  2    8     8.50
12  2    8     8.75
13  2   12    12.00
14  2   15    15.00
15  2   15    15.25
16  2   15    15.50
17  2   19    19.00
18  2   19    19.25
19  2   19    19.50
20  2   19    19.75


问:
How to limit this modsecurity rule to one file?
I have this rule bellow, and I'd like to limit for only wp-login.php files. Is it possible?

SecRule REQUEST_HEADERS:User-Agent "@contains python-requests" "id:1000000,t:none,t:lowercase,deny,nolog,msg:'BAD BOT - Detected and Blocked. '"

答:
Use chained rules:</p>

```<code>SecRule REQUEST_URI "wp-admin.php" "chain,id:1000000,t:none,t:lowercase,deny,nolog,msg:'BAD BOT - Detected and Blocked. '"
    SecRule REQUEST_HEADERS:User-Agent "@contains python-requests" ",t:none,t:lowercase"
</code>```

Body:
Use chained rules:

SecRule REQUEST_URI "wp-admin.php" "chain,id:1000000,t:none,t:lowercase,deny,nolog,msg:'BAD BOT - Detected and Blocked. '"
    SecRule REQUEST_HEADERS:User-Agent "@contains python-requests" ",t:none,t:lowercase"


问:
delegatebetween view and view controller
I have a UIView and a ViewController.
In the UIView I have a UITextField, and I need to use a delegate so I can dismiss the keyboard by tapping the "Done" button.
The problem is that I can't use UITextViewDelegate in the UIView and I can't access the Textfield in the UIView from the ViewController.
How can I add a delegate so I can dismiss my textfield?

ViewController:

```<code>import UIKit

class LoginVC: UIViewController, UITextViewDelegate {
override func loadView() {
    super.loadView()
    self.view = BaseView()
}
override func viewDidLoad() {
    super.viewDidLoad()
    self.tabBarController?.navigationController?.setNavigationBarHidden(true, animated: false)

    navigationItem.title = "LoginVC"
    navigationController?.navigationBar.barTintColor = UIColor.appBlue
    navigationController?.navigationBar.barStyle = .black
    navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.appWhite]
    navigationItem.rightBarButtonItem?.tintColor = UIColor.appWhite

    let btnImage = UIImageView(image: UIImage(named: "Help"))
    btnImage.changeImageColor(color: UIColor.appWhite)

    //TODO: Change the btnImage to color white!
    let helpButton = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
    helpButton.setImage(btnImage.image, for: .normal)
    helpButton.addTarget(self, action: #selector(showHelpPopup), for: .touchUpInside)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: helpButton)

}

@objc func showHelpPopup(){

}
}
</code>```

View:

```<code>import UIKit

public final class BaseView: UIView, UITextFieldDelegate {
public override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubview(masterStackView)

    self.backgroundColor = UIColor.white
    NSLayoutConstraint.activate([
        masterStackView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        masterStackView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
        masterStackView.leadingAnchor.constraint(lessThanOrEqualToSystemSpacingAfter: self.leadingAnchor, multiplier: 0.2),
        masterStackView.trailingAnchor.constraint(lessThanOrEqualToSystemSpacingAfter: self.trailingAnchor, multiplier: -0.2),
        masterStackView.heightAnchor.constraint(equalToConstant: 100),
    ])
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

public let addCommentTextField: UITextField = {
    let text = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 30))

    text.placeholder = "Comment"
    text.font = UIFont.systemFont(ofSize: 14, weight: .bold)
    text.borderStyle = UITextField.BorderStyle.roundedRect
    text.autocorrectionType = UITextAutocorrectionType.no
    text.keyboardType = UIKeyboardType.default
    text.returnKeyType = UIReturnKeyType.done
    text.clearButtonMode = .always
    text.contentHorizontalAlignment = .left

    return text
}()
</code>```

答:
No need you can do

```<code>self.view.endEditing(true)
</code>```

Or

```<code>let vi = BaseView()
vi.addCommentTextField.delegate = self
self.view = vi
</code>```

Body:
I have a UIView and a ViewController.
In the UIView I have a UITextField, and I need to use a delegate so I can dismiss the keyboard by tapping the "Done" button.
The problem is that I can't use UITextViewDelegate in the UIView and I can't access the Textfield in the UIView from the ViewController.
How can I add a delegate so I can dismiss my textfield?

ViewController:

import UIKit

class LoginVC: UIViewController, UITextViewDelegate {
override func loadView() {
    super.loadView()
    self.view = BaseView()
}
override func viewDidLoad() {
    super.viewDidLoad()
    self.tabBarController?.navigationController?.setNavigationBarHidden(true, animated: false)

    navigationItem.title = "LoginVC"
    navigationController?.navigationBar.barTintColor = UIColor.appBlue
    navigationController?.navigationBar.barStyle = .black
    navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.appWhite]
    navigationItem.rightBarButtonItem?.tintColor = UIColor.appWhite

    let btnImage = UIImageView(image: UIImage(named: "Help"))
    btnImage.changeImageColor(color: UIColor.appWhite)

    //TODO: Change the btnImage to color white!
    let helpButton = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
    helpButton.setImage(btnImage.image, for: .normal)
    helpButton.addTarget(self, action: #selector(showHelpPopup), for: .touchUpInside)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: helpButton)

}

@objc func showHelpPopup(){

}
}

View:

import UIKit

public final class BaseView: UIView, UITextFieldDelegate {
public override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubview(masterStackView)

    self.backgroundColor = UIColor.white
    NSLayoutConstraint.activate([
        masterStackView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        masterStackView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
        masterStackView.leadingAnchor.constraint(lessThanOrEqualToSystemSpacingAfter: self.leadingAnchor, multiplier: 0.2),
        masterStackView.trailingAnchor.constraint(lessThanOrEqualToSystemSpacingAfter: self.trailingAnchor, multiplier: -0.2),
        masterStackView.heightAnchor.constraint(equalToConstant: 100),
    ])
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

public let addCommentTextField: UITextField = {
    let text = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 30))

    text.placeholder = "Comment"
    text.font = UIFont.systemFont(ofSize: 14, weight: .bold)
    text.borderStyle = UITextField.BorderStyle.roundedRect
    text.autocorrectionType = UITextAutocorrectionType.no
    text.keyboardType = UIKeyboardType.default
    text.returnKeyType = UIReturnKeyType.done
    text.clearButtonMode = .always
    text.contentHorizontalAlignment = .left

    return text
}()

Body:
No need you can do

self.view.endEditing(true)

Or

let vi = BaseView()
vi.addCommentTextField.delegate = self
self.view = vi


问:
Solving for the upper bound and lower bound of liars, in liar-truth teller problem
I am trying to solve a truth teller/ Liar problem. A survey of a class is taken. Answers are in the form of a Matrix A, where A[i][j] represents the reply given by the i-th student about the j-th student. If that character is ‘L’ – it means he/she is a liar; if it’s ‘T’ – then it means that, that student is a truth speaker.

Truth-Speaker (‘T’): All his/her replies are true.
Liar (‘L’) : (S)he has made at least one false reply.

ex. 1

```<code>TLLL

LTLL

LLTL

LLLT
</code>```

Class contains at least 3 and at most 4 liars, 3 is the lower bound of liars, and 4 is the upper bound.

ex. 2

```<code>TLTLT

TTTTT

LLTLL

LLLLL

TLTLT
</code>```

Class contains at least 4 and at most 4 liars

I am not sure how the lower and upper bound was found, any help would be appreciated.

答:
For the first example:

all 4 students only say that they are telling the truth and that the rest are lying

They could all be lying for all we know - so the upper bound is 4

For the lower bound we can assume 1 is telling the truth and that makes sense logically. If we tried to say that more than 1 is true
than this is not possible since the students would say each other are
lying - thus the lower bound is 3

For the second example it takes a little more logic to figure out:

the 4th student says that he is lying - which means he must be lying and that at least one of his claims about the other 4 students lying must be a lie (the claim that he is lying is obviously true) - this means that at least one of the students is not lying so the upper bound becomes 4 and the lower becomes 1

student 2 says that they are all true - which we just proved is wrong so he must be lying

this leaves us with students 1,3 and 5 who all say that student 3 is telling the truth. Since we know that at least one student is telling the truth - then student 3 must be telling the truth (since they all say so).

Then from what student 3 says we know the rest are lying - so the upper=lower=4 liars

Body:
I am trying to solve a truth teller/ Liar problem. A survey of a class is taken. Answers are in the form of a Matrix A, where A[i][j] represents the reply given by the i-th student about the j-th student. If that character is ‘L’ – it means he/she is a liar; if it’s ‘T’ – then it means that, that student is a truth speaker.

Truth-Speaker (‘T’): All his/her replies are true.
Liar (‘L’) : (S)he has made at least one false reply.

ex. 1

TLLL

LTLL

LLTL

LLLT

Class contains at least 3 and at most 4 liars, 3 is the lower bound of liars, and 4 is the upper bound.

ex. 2

TLTLT

TTTTT

LLTLL

LLLLL

TLTLT

Class contains at least 4 and at most 4 liars

I am not sure how the lower and upper bound was found, any help would be appreciated.


问:
Is there a way to zoom before a specified page break when converting an excel sheet to PDF in VBA?
I am working on a project to automate payroll and have developed a couple of Macros already, but am having trouble in the last step. I am copying data from one workbook to another, so that the timecard sheet is attached to the invoice sheet. I am then automating creating PDFs and when I create the PDFs, they shrink to fit the larger page that I have attached. I have inserted a manual page break to create two separate pages in my PDF, but the PDF is still shrinking the first page and not fitting it to the full page. Is there a way to zoom before the page break, so that the first page fits the full PDF size?

I have tried manually changing the PDF formatting, changing the print preview etc.

```<code>Sub Excel_to_PDF()

     Dim Path As String
     Dim filename As String
     Dim ws As Worksheet
     Dim nm As String

     For Each ws In Worksheets

     If ws.Visible = xlSheetVisible Then
        ws.Select
        nm = ws.Name
        ActiveSheet.Rows(44).PageBreak = xlPageBreakManual
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        filename:="C:\Users\rober\Desktop\Invoices\" & nm & "-" & ActiveSheet.Range("K6").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
        End If
        Next ws

        Dim ZoomRng As Range
        Set ZoomRng = Range("A1:M43")
        ZoomRng.Select
        ActiveWindow.Zoom = True

End Sub
</code>```

I want the PDF to be split between two pages. The first page before line 44, and the second page after. That is not a problem. This Macro works for that. What I need is for the sheet before line 44 to be zoomed and not scaled to fit with the same dimensions as the second sheet. The first sheet goes from A1:L43, and the second sheet goes from A50:AC110. The first sheet gets shrunk because of this, and I want it zoomed in on.

答:
Try this i think the zoom was in the wrong place.</p>

```<code>Sub Excel_to_PDF()

     Dim Path As String
     Dim filename As String
     Dim ws As Worksheet
     Dim nm As String

     For Each ws In Worksheets

      If ws.Visible = xlSheetVisible Then
        ws.Select
        nm = ws.Name

        Dim ZoomRng As Range
        Set ZoomRng = Range("A1:M43")
        ZoomRng.Select
        ActiveWindow.Zoom = True

        ActiveSheet.Rows(44).PageBreak = xlPageBreakManual
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        filename:="C:\Users\rober\Desktop\Invoices\" & nm & "-" & ActiveSheet.Range("K6").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
       End If
      Next ws

End Sub
</code>```

Body:
I am working on a project to automate payroll and have developed a couple of Macros already, but am having trouble in the last step. I am copying data from one workbook to another, so that the timecard sheet is attached to the invoice sheet. I am then automating creating PDFs and when I create the PDFs, they shrink to fit the larger page that I have attached. I have inserted a manual page break to create two separate pages in my PDF, but the PDF is still shrinking the first page and not fitting it to the full page. Is there a way to zoom before the page break, so that the first page fits the full PDF size?

I have tried manually changing the PDF formatting, changing the print preview etc.

Sub Excel_to_PDF()

     Dim Path As String
     Dim filename As String
     Dim ws As Worksheet
     Dim nm As String

     For Each ws In Worksheets

     If ws.Visible = xlSheetVisible Then
        ws.Select
        nm = ws.Name
        ActiveSheet.Rows(44).PageBreak = xlPageBreakManual
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        filename:="C:\Users\rober\Desktop\Invoices\" & nm & "-" & ActiveSheet.Range("K6").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
        End If
        Next ws

        Dim ZoomRng As Range
        Set ZoomRng = Range("A1:M43")
        ZoomRng.Select
        ActiveWindow.Zoom = True

End Sub

I want the PDF to be split between two pages. The first page before line 44, and the second page after. That is not a problem. This Macro works for that. What I need is for the sheet before line 44 to be zoomed and not scaled to fit with the same dimensions as the second sheet. The first sheet goes from A1:L43, and the second sheet goes from A50:AC110. The first sheet gets shrunk because of this, and I want it zoomed in on.

Body:
Try this i think the zoom was in the wrong place.

Sub Excel_to_PDF()

     Dim Path As String
     Dim filename As String
     Dim ws As Worksheet
     Dim nm As String

     For Each ws In Worksheets

      If ws.Visible = xlSheetVisible Then
        ws.Select
        nm = ws.Name

        Dim ZoomRng As Range
        Set ZoomRng = Range("A1:M43")
        ZoomRng.Select
        ActiveWindow.Zoom = True

        ActiveSheet.Rows(44).PageBreak = xlPageBreakManual
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        filename:="C:\Users\rober\Desktop\Invoices\" & nm & "-" & ActiveSheet.Range("K6").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
       End If
      Next ws

End Sub


问:
Why can I not implicitly convert type 'UnityEngine.Vector2' to 'float'?
I'm trying to reset an object's position on my main menu screen without reloading the scene. However, I am getting this error (Cannot implicitly convert type 'UnityEngine.Vector2' to 'float') when attempting to reset the velocity and angular velocity of the falling object.

I have tried replacing the 'Vector2.zero' part to just '0f' and to a float that is equal to 0f but it also didn't work.

```<code>void Update () {
        transform.Translate (Vector2.right * Time.deltaTime * moveSpeed);
        if (player.transform.position.x >= 13f) {
            player.GetComponent<Rigidbody2D> ().velocity = Vector2.zero;
            player.GetComponent<Rigidbody2D> ().angularVelocity = Vector2.zero;
            player.transform.position = new Vector2 (-8.5f, 6f);
        }
    }
</code>```

答:
Your problem is here:

```<code>player.GetComponent<Rigidbody2D>().angularVelocity = Vector2.zero;
</code>```

angularVelocity is a float, not a vector. You're trying to pass a pair of values where the compiler can only use one, so it doesn't understand what you want to do.

You can assign 0f instead:

```<code>player.GetComponent<Rigidbody2D>().angularVelocity = 0f;
</code>```

Body:
I'm trying to reset an object's position on my main menu screen without reloading the scene. However, I am getting this error (Cannot implicitly convert type 'UnityEngine.Vector2' to 'float') when attempting to reset the velocity and angular velocity of the falling object.

I have tried replacing the 'Vector2.zero' part to just '0f' and to a float that is equal to 0f but it also didn't work.

void Update () {
        transform.Translate (Vector2.right * Time.deltaTime * moveSpeed);
        if (player.transform.position.x >= 13f) {
            player.GetComponent<Rigidbody2D> ().velocity = Vector2.zero;
            player.GetComponent<Rigidbody2D> ().angularVelocity = Vector2.zero;
            player.transform.position = new Vector2 (-8.5f, 6f);
        }
    }

Body:
Your problem is here:

player.GetComponent<Rigidbody2D>().angularVelocity = Vector2.zero;

angularVelocity is a float, not a vector. You're trying to pass a pair of values where the compiler can only use one, so it doesn't understand what you want to do.

You can assign 0f instead:

player.GetComponent<Rigidbody2D>().angularVelocity = 0f;