问:
Django REST Framework - Allow staff to access all endpoints
I'm building a DRF API, and I would like to allow staff members (is_staff == True) to access all of the REST endpoints, while still providing custom permission checking per ViewSet. Ideally, this would be a global setting, but I'm not against setting it up per ViewSet.

Here are the things I've tried:

Option 1: Check on every custom permission

from rest_framework import permissions

class SomeModelPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user.is_staff:
            return True

        # other logic

    def has_object_permission(self, request, view, obj):
        if request.user.is_staff:
            return True

        # other logic
```

<p>This works, but I'd rather not repeat so much code.</p>

<hr>

<h1>Option 2: Bitwise operators</h1>

<p>I tried removing the <code>is_staff</code> logic from the custom permission above, and adding this to the ViewSet:</p>

<pre class="lang-py prettyprint-override"><code>from rest_framework import permissions, viewsets

class SomeModelViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAdminUser|SomeModelPermission,)
</code>```

However, this actually does not enforce permissions as I'd like, because IsAdminUser inherits from BasePermission, which is defined as:

class BasePermission(object):
    def has_permission(self, request, view):
        return True

    def has_object_permission(self, request, view, obj):
        return True
```

IsAdminUser doesn't define its own has_object_permission, so it will always return True when checking object permissions, resulting in unintended object access.

Any ideas? I was hoping there would be some way I could set a global permissions check that would return True when the user is a staff member, and defer to the custom permissions otherwise. But reading through how permissions are determined, I'm not sure that this is possible.

答:
There is a permission class for admin users.
Here is an example of that:

```<code>class deletecompletedreopenjobAPIView(RetrieveUpdateAPIView):
    queryset = Job.objects._all()
    serializer_class = JobCompletedDeleteStatusSerializer
    lookup_field = 'job_id'
    permission_classes = [IsOwnerOrReadOnly | **IsAdminUser**]
    authentication_classes = (authentication.TokenAuthentication,)
</code>```

My custom IsOwnerOrReadOnly is as follows:

```<code>class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        return obj.user == request.user
</code>```

Body:
I'm building a DRF API, and I would like to allow staff members (is_staff == True) to access all of the REST endpoints, while still providing custom permission checking per ViewSet. Ideally, this would be a global setting, but I'm not against setting it up per ViewSet.

Here are the things I've tried:

Option 1: Check on every custom permission

from rest_framework import permissions

class SomeModelPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user.is_staff:
            return True

        # other logic

    def has_object_permission(self, request, view, obj):
        if request.user.is_staff:
            return True

        # other logic

This works, but I'd rather not repeat so much code.

Option 2: Bitwise operators

I tried removing the is_staff logic from the custom permission above, and adding this to the ViewSet:

from rest_framework import permissions, viewsets

class SomeModelViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAdminUser|SomeModelPermission,)

However, this actually does not enforce permissions as I'd like, because IsAdminUser inherits from BasePermission, which is defined as:

class BasePermission(object):
    def has_permission(self, request, view):
        return True

    def has_object_permission(self, request, view, obj):
        return True

IsAdminUser doesn't define its own has_object_permission, so it will always return True when checking object permissions, resulting in unintended object access.

Any ideas? I was hoping there would be some way I could set a global permissions check that would return True when the user is a staff member, and defer to the custom permissions otherwise. But reading through how permissions are determined, I'm not sure that this is possible.

Body:
There is a permission class for admin users.
Here is an example of that:

class deletecompletedreopenjobAPIView(RetrieveUpdateAPIView):
    queryset = Job.objects._all()
    serializer_class = JobCompletedDeleteStatusSerializer
    lookup_field = 'job_id'
    permission_classes = [IsOwnerOrReadOnly | **IsAdminUser**]
    authentication_classes = (authentication.TokenAuthentication,)

My custom IsOwnerOrReadOnly is as follows:

class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        return obj.user == request.user


来源: stackexchange

问:
Error in comparing two std::chrono::time_point instances
I have two std::chrono::time_point instances in variables exp and time. exp has a time in the future and time is the current time. But when I compare them as in this snippet:

```<code>std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;
</code>```

I get output:

```<code>Sat Apr 26 01:39:43 4758
Fri May 29 18:11:59 2020
1
</code>```

Which is wrong because exp is in the year 4758 and time is in the year 2020.

Where am I going wrong?

答:
t_exp is -4243023785

This value of time_t corresponds to 1835-07-18 22:16:55 (assuming the Unix epoch and a precision of seconds, neither of which are specified by the standard, but are common).

Apparently the implementation of ctime on your platform can't handle dates this far in the past, which is a little surprising as 1835 is not very far in the past.

The value of exp is -4243023785 times a million or a billion (depending on the precision of system_clock on your platform) and is stored with a signed 64 bit integer (there is no overflow).  Thus time > exp == 1 is correct (time is 1590775919s converted to the precision of system_clock).

Sat Apr 26 01:39:43 4758 corresponds to a time_t of 87990716383.

I see nothing wrong with your use of the chrono library in the above code.

Update

The value 87990716383 is being converted to a time_point using from_time_t()

Ah, this combined with the knowledge that on your platform the precision of system_clock is nanoseconds tells me that you are experiencing overflow on the construction of exp.

This is not the code you have:

```<code>std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;
</code>```

The code you have looks something like:

```<code>// ...
std::time_t t_exp = 87990716383;
auto exp = std::chrono::system_clock::from_time_t(t_exp);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;
</code>```

On your platform, system_clock stores nanoseconds since 1970-01-01 00:00:00 UTC in a signed 64 bit integer.  The maximum storable date (system_clock::time_point::max()) on your platform is:

```<code>2262-04-11 23:47:16.854775807
</code>```

Beyond this, the underlying storage of nanoseconds overflows.

When 87990716383 (seconds) is converted in from_time_t, it is multiplied by a billion which overflows.  The overflowed value is -4243003985547758080 which corresponds to the date 1835-07-19 03:46:54.452241920.

You can get a larger range by using a coarser precision, for example:

```<code>std::time_t t_exp = 87990716383;
time_point<system_clock, microseconds> exp{seconds{t_exp}};
// exp == 4758-04-26 01:39:43.000000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two std::chrono::time_point instances in variables exp and time. exp has a time in the future and time is the current time. But when I compare them as in this snippet:

std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

I get output:

Sat Apr 26 01:39:43 4758
Fri May 29 18:11:59 2020
1

Which is wrong because exp is in the year 4758 and time is in the year 2020.

Where am I going wrong?

Body:
t_exp is -4243023785

This value of time_t corresponds to 1835-07-18 22:16:55 (assuming the Unix epoch and a precision of seconds, neither of which are specified by the standard, but are common).

Apparently the implementation of ctime on your platform can't handle dates this far in the past, which is a little surprising as 1835 is not very far in the past.

The value of exp is -4243023785 times a million or a billion (depending on the precision of system_clock on your platform) and is stored with a signed 64 bit integer (there is no overflow).  Thus time > exp == 1 is correct (time is 1590775919s converted to the precision of system_clock).

Sat Apr 26 01:39:43 4758 corresponds to a time_t of 87990716383.

I see nothing wrong with your use of the chrono library in the above code.

Update

The value 87990716383 is being converted to a time_point using from_time_t()

Ah, this combined with the knowledge that on your platform the precision of system_clock is nanoseconds tells me that you are experiencing overflow on the construction of exp.

This is not the code you have:

std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

The code you have looks something like:

// ...
std::time_t t_exp = 87990716383;
auto exp = std::chrono::system_clock::from_time_t(t_exp);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

On your platform, system_clock stores nanoseconds since 1970-01-01 00:00:00 UTC in a signed 64 bit integer.  The maximum storable date (system_clock::time_point::max()) on your platform is:

2262-04-11 23:47:16.854775807

Beyond this, the underlying storage of nanoseconds overflows.

When 87990716383 (seconds) is converted in from_time_t, it is multiplied by a billion which overflows.  The overflowed value is -4243003985547758080 which corresponds to the date 1835-07-19 03:46:54.452241920.

You can get a larger range by using a coarser precision, for example:

std::time_t t_exp = 87990716383;
time_point<system_clock, microseconds> exp{seconds{t_exp}};
// exp == 4758-04-26 01:39:43.000000


问:
How to prevent usage of object in ellipsis
Is there a way to prevent the pass an object to an ellipsis?

Example:

The ellipsis is used in the following function

```<code>int my_printf( const char * format, ... );
</code>```

And there is an object of some type:

```<code>struct Text
{
  const char * c_str();
};
Text text;
</code>```

Is it possible to change struct Text so that the following does not compile?

```<code>my_printf("%s", text ); // should fail to compile
my_printf("%s", text.c_str() ); // this was the intention
</code>```

Changing my_printf to use variadic template arguments instead of an ellipsis is not an option.

答:
In case deleting the copy constructor is an option the usage in ellipsis results in an error.
Unfortunately declaring the copy constructor as explicit does not result in an error.</p>

```<code>#include "stdio.h"

struct A
{
  A( const  A & ) = delete;
  //explicit A( const  A & ) = default;
  A() {}
  int m = 3;
};

int main ()
{
  A a;
  printf("%d", a); // error
}
</code>```

Body:
Is there a way to prevent the pass an object to an ellipsis?

Example:

The ellipsis is used in the following function

int my_printf( const char * format, ... );

And there is an object of some type:

struct Text
{
  const char * c_str();
};
Text text;

Is it possible to change struct Text so that the following does not compile?

my_printf("%s", text ); // should fail to compile
my_printf("%s", text.c_str() ); // this was the intention

Changing my_printf to use variadic template arguments instead of an ellipsis is not an option.

Body:
In case deleting the copy constructor is an option the usage in ellipsis results in an error.
Unfortunately declaring the copy constructor as explicit does not result in an error.

#include "stdio.h"

struct A
{
  A( const  A & ) = delete;
  //explicit A( const  A & ) = default;
  A() {}
  int m = 3;
};

int main ()
{
  A a;
  printf("%d", a); // error
}


问:
Problem showing the 'size' attribute for a 'file_field' using Ruby on Rails 3
I am using Ruby on Rails 3 and I have a form like this:

```<code><%= form_for(@user, ... ) do |f| %>
  ...
  <%= f.file_field :avatar, :id => "test_id", :style => "display: block", :size => "13" %>
  ...
<% end %>
</code>```

When I go to see the source of the page, this is the HTML code generated:

```<code><input type="file" style="display: block;" name="user[avatar]" id="test_id">
</code>```

that means the 'size' attribute there isn't.

I tried on Firefox, Chrome and Safari: same output, but it seems to have everything set correctly.

Is it a problem related to RoR3?

答:
Ya seems so but..

I thought of another alternative :
jquery ..

```<code>$('#test_id').attr('size', 1);
</code>```

bingo!!

ContentLicense: CC BY-SA 2.5

Body:
I am using Ruby on Rails 3 and I have a form like this:

<%= form_for(@user, ... ) do |f| %>
  ...
  <%= f.file_field :avatar, :id => "test_id", :style => "display: block", :size => "13" %>
  ...
<% end %>

When I go to see the source of the page, this is the HTML code generated:

<input type="file" style="display: block;" name="user[avatar]" id="test_id">

that means the 'size' attribute there isn't.

I tried on Firefox, Chrome and Safari: same output, but it seems to have everything set correctly.

Is it a problem related to RoR3?

Body:
Ya seems so but..

I thought of another alternative :
jquery ..

$('#test_id').attr('size', 1);

bingo!!

ContentLicense: CC BY-SA 3.0


问:
Is it possible to improve spaCy's similarity results with custom named entities?
I've found that spaCy's similarity does a decent job of comparing my documents using "en_core_web_lg" out-of-the-box.

I'd like to tighten up relationships in some areas and thought adding custom NER labels to the model would help, but my results before and after show no improvements, even though I've been able to create a test set of custom entities.

Now I'm wondering, was my theory completely wrong, or could I simply be missing something in my pipeline?

If I was wrong, what's the best approach to improve results?  Seems like some sort of custom labeling should help.

Here's an example of what I've tested so far:

```<code>import spacy
from spacy.pipeline import EntityRuler
from spacy.tokens import Doc
from spacy.gold import GoldParse

nlp = spacy.load("en_core_web_lg")

docA = nlp("Add fractions with like denominators.")
docB = nlp("What does one-third plus one-third equal?")

sim_before = docA.similarity(docB)
print(sim_before)
</code>```

0.5949629181460099

^^ Not too shabby, but I'd like to see results closer to 0.85 in this example.

So, I use EntityRuler and add some patterns to try and tighten up the relationships:

```<code>ruler = EntityRuler(nlp)
patterns = [
    {"label": "ADDITION", "pattern": "Add"},
    {"label": "ADDITION", "pattern": "plus"},
    {"label": "FRACTION", "pattern": "one-third"},
    {"label": "FRACTION", "pattern": "fractions"},
    {"label": "FRACTION", "pattern": "denominators"},

]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler, before='ner')
print(nlp.pipe_names)
</code>```

['tagger', 'parser', 'entity_ruler', 'ner']

Adding GoldParse seems to be important, so I added the following and updated NER:

```<code>doc1 = Doc(nlp.vocab, [u'What', u'does', u'one-third', u'plus', u'one-third', u'equal'])
gold1 = GoldParse(doc1, [u'0', u'0', u'U-FRACTION', u'U-ADDITION', u'U-FRACTION', u'O'])

doc2 = Doc(nlp.vocab, [u'Add', u'fractions', u'with', u'like', u'denominators'])
gold2 = GoldParse(doc2, [u'U-ADDITION', u'U-FRACTION', u'O', u'O', u'U-FRACTION'])

ner = nlp.get_pipe("ner")
losses = {}
optimizer = nlp.begin_training()
ner.update([doc1, doc2], [gold1, gold2], losses=losses, sgd=optimizer)
</code>```

{'ner': 0.0}

You can see my custom entities are working, but the test results show zero improvement:

```<code>test1 = nlp("Add fractions with like denominators.")
test2 = nlp("What does one-third plus one-third equal?")

print([(ent.text, ent.label_) for ent in test1.ents])
print([(ent.text, ent.label_) for ent in test2.ents])

sim = test1.similarity(test2)
print(sim)
</code>```

[('Add', 'ADDITION'), ('fractions', 'FRACTION'), ('denominators', 'FRACTION')]

[('one-third', 'FRACTION'), ('plus', 'ADDITION'), ('one-third', 'FRACTION')]

0.5949629181460099

Any tips would be greatly appreciated!

答:
Doc.similarity only uses the word vectors, not any other annotation. From the Doc API:

The default estimate is cosine similarity using an average of word vectors.

Body:
I've found that spaCy's similarity does a decent job of comparing my documents using "en_core_web_lg" out-of-the-box.

I'd like to tighten up relationships in some areas and thought adding custom NER labels to the model would help, but my results before and after show no improvements, even though I've been able to create a test set of custom entities.

Now I'm wondering, was my theory completely wrong, or could I simply be missing something in my pipeline?

If I was wrong, what's the best approach to improve results?  Seems like some sort of custom labeling should help.

Here's an example of what I've tested so far:

import spacy
from spacy.pipeline import EntityRuler
from spacy.tokens import Doc
from spacy.gold import GoldParse

nlp = spacy.load("en_core_web_lg")

docA = nlp("Add fractions with like denominators.")
docB = nlp("What does one-third plus one-third equal?")

sim_before = docA.similarity(docB)
print(sim_before)

0.5949629181460099

^^ Not too shabby, but I'd like to see results closer to 0.85 in this example.

So, I use EntityRuler and add some patterns to try and tighten up the relationships:

ruler = EntityRuler(nlp)
patterns = [
    {"label": "ADDITION", "pattern": "Add"},
    {"label": "ADDITION", "pattern": "plus"},
    {"label": "FRACTION", "pattern": "one-third"},
    {"label": "FRACTION", "pattern": "fractions"},
    {"label": "FRACTION", "pattern": "denominators"},

]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler, before='ner')
print(nlp.pipe_names)

['tagger', 'parser', 'entity_ruler', 'ner']

Adding GoldParse seems to be important, so I added the following and updated NER:

doc1 = Doc(nlp.vocab, [u'What', u'does', u'one-third', u'plus', u'one-third', u'equal'])
gold1 = GoldParse(doc1, [u'0', u'0', u'U-FRACTION', u'U-ADDITION', u'U-FRACTION', u'O'])

doc2 = Doc(nlp.vocab, [u'Add', u'fractions', u'with', u'like', u'denominators'])
gold2 = GoldParse(doc2, [u'U-ADDITION', u'U-FRACTION', u'O', u'O', u'U-FRACTION'])

ner = nlp.get_pipe("ner")
losses = {}
optimizer = nlp.begin_training()
ner.update([doc1, doc2], [gold1, gold2], losses=losses, sgd=optimizer)

{'ner': 0.0}

You can see my custom entities are working, but the test results show zero improvement:

test1 = nlp("Add fractions with like denominators.")
test2 = nlp("What does one-third plus one-third equal?")

print([(ent.text, ent.label_) for ent in test1.ents])
print([(ent.text, ent.label_) for ent in test2.ents])

sim = test1.similarity(test2)
print(sim)

[('Add', 'ADDITION'), ('fractions', 'FRACTION'), ('denominators', 'FRACTION')]

[('one-third', 'FRACTION'), ('plus', 'ADDITION'), ('one-third', 'FRACTION')]

0.5949629181460099

Any tips would be greatly appreciated!


问:
TextView: How to prevent displaying the action menu when selecting text in TextView?
I have a selectable TextView.
I want to prevent showing the context menu when selecting text.

I implemented this code but action bar and context menu still is displayed.

```<code>   tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Return true to ensure the yourTextView is still selectable
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Remove all action items to provide an actionmode-less selection
            menu.clear();
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });
</code>```

How can it be remove forever?

答:
```<code>@Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            menu.removeItem(android.R.id.selectAll);
            menu.removeItem(android.R.id.cut);
            menu.removeItem(android.R.id.copy);
            menu.removeItem(android.R.id.paste);
            menu.removeItem(android.R.id.replaceText);
            menu.removeItem(android.R.id.shareText);
            return true;
        }
</code>```

Try to manually remove item from the menu. I hope it should work now.

Body:
I have a selectable TextView.
I want to prevent showing the context menu when selecting text.

I implemented this code but action bar and context menu still is displayed.

   tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Return true to ensure the yourTextView is still selectable
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Remove all action items to provide an actionmode-less selection
            menu.clear();
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

How can it be remove forever?

Body:
@Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            menu.removeItem(android.R.id.selectAll);
            menu.removeItem(android.R.id.cut);
            menu.removeItem(android.R.id.copy);
            menu.removeItem(android.R.id.paste);
            menu.removeItem(android.R.id.replaceText);
            menu.removeItem(android.R.id.shareText);
            return true;
        }

Try to manually remove item from the menu. I hope it should work now.


问:
Website not loading with URL path, using ACM, CloudfFront, and namecheap as domain manager
I have a website, for example xyz.online hosted on S3.I have 2 buckets in s3, one is xyz.online which contains all the files, and the other one is www.xyz.online which redirects to the first bucket.

Now to shift to HTTPS protocol, I am using ACM(Amazon Certificate Manager), for my domain(xyz.online) and the additional subdomain(www.xyz.online), and verified it by adding the CNAMES for both in my NameCheap account, and the certificate was issued successfully.Then I created a CloudFront distribution network, using this certificate, redirecting HTTP to HTTPS, and index.html as root object.(followed these instructions from here).

The problem I am facing is that www.xyz.online and xyz.online, both successfully redirect to https://xyz.online/home, but when I refresh the page or try to enter https://xyz.online/home directly , it displays an error.I cannot find out where the issue is.

I tried using the CloudFront url directly, https://qwerty.cloudfront.net/home,
the same error page appears, it is given below

```<code>This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>home</Key>
<RequestId>***********</RequestId>
<HostId>*******</HostId>
</Error>
</code>```

答: This error is caused by the S3 bucket for the origin not having a file, either name home or home/index.html.</p>

Body:
I have a website, for example xyz.online hosted on S3.I have 2 buckets in s3, one is xyz.online which contains all the files, and the other one is www.xyz.online which redirects to the first bucket.

Now to shift to HTTPS protocol, I am using ACM(Amazon Certificate Manager), for my domain(xyz.online) and the additional subdomain(www.xyz.online), and verified it by adding the CNAMES for both in my NameCheap account, and the certificate was issued successfully.Then I created a CloudFront distribution network, using this certificate, redirecting HTTP to HTTPS, and index.html as root object.(followed these instructions from here).

The problem I am facing is that www.xyz.online and xyz.online, both successfully redirect to https://xyz.online/home, but when I refresh the page or try to enter https://xyz.online/home directly , it displays an error.I cannot find out where the issue is.

I tried using the CloudFront url directly, https://qwerty.cloudfront.net/home,
the same error page appears, it is given below

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
NoSuchKey
<Message>The specified key does not exist.</Message>
<Key>home</Key>
<RequestId>***********</RequestId>
<HostId>*******</HostId>
</Error>


问:
ReactDOM not showing
```<code>var ReactDom = require('react-dom')
var createReactClass = require('create-react-class')

//Create new react component
var TodoComponent = createReactClass({
    render:function() {
        return(
            <h1>React component</h1>
        )
    }
})

//Put react component in html page
ReactDom.render(<TodoComponent />, document.getElementById('todo-wrapper'))
</code>```

This is my current code and its not rendering
Im pretty new to react

答:
Try this instead, one major flaw with your code that I noticed is you used ReactDom instead of ReactDOM please refer to the react docs for further info on creating class components and rendering them properly

class TodoComponent extends React.Component {
  render() {
    return ( <
      h1 > React component

    )
  }
}

//Put react component in html page
ReactDOM.render( < TodoComponent / > , document.getElementById('todo-wrapper'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<div id="todo-wrapper"></div></code>```

Title: ReactDOM not showing

Body:
var ReactDom = require('react-dom')
var createReactClass = require('create-react-class')

//Create new react component
var TodoComponent = createReactClass({
    render:function() {
        return(

React component

        )
    }
})

//Put react component in html page
ReactDom.render(<TodoComponent />, document.getElementById('todo-wrapper'))

This is my current code and its not rendering
Im pretty new to react

Body:
Try this instead, one major flaw with your code that I noticed is you used ReactDom instead of ReactDOM please refer to the react docs for further info on creating class components and rendering them properly

class TodoComponent extends React.Component {
  render() {
    return ( <
      h1 > React component < /h1>
    )
  }
}

//Put react component in html page
ReactDOM.render( < TodoComponent / > , document.getElementById('todo-wrapper'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<div id="todo-wrapper"></div>


问:
Passing capturing lambda as function pointer
Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.

Consider the following example

```<code>using DecisionFn = bool(*)();

class Decide
{
public:
    Decide(DecisionFn dec) : _dec{dec} {}
private:
    DecisionFn _dec;
};

int main()
{
    int x = 5;
    Decide greaterThanThree{ [x](){ return x > 3; } };
    return 0;
}
</code>```

When I try to compile this, I get the following compilation error:

In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9:  note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are:
9:5:   note: Decide::Decide(DecisionFn)
9:5:   note: no known conversion for argument 1 from 'main()::<lambda()>' to 'DecisionFn {aka bool (*)()}'
6:7:   note: constexpr Decide::Decide(const Decide&)
6:7:   note: no known conversion for argument 1 from 'main()::<lambda()>' to 'const Decide&'
6:7:   note: constexpr Decide::Decide(Decide&&)
6:7:   note: no known conversion for argument 1 from 'main()::<lambda()>' to 'Decide&&'
```

That's one heck of an error message to digest, but I think what I'm getting out of it is that the lambda cannot be treated as a constexpr so therefore I cannot pass it as a function pointer? I've tried making x constexpr as well, but that doesn't seem to help.

答:
Not a direct answer, but a slight variation to use the "functor" template pattern to hide away the specifics of the lambda type and keeps the code nice and simple.

I was not sure how you wanted to use the decide class so I had to extend the class with a function that uses it. See full example here: https://godbolt.org/z/jtByqE

The basic form of your class might look like this:

```<code>template <typename Functor>
class Decide
{
public:
    Decide(Functor dec) : _dec{dec} {}
private:
    Functor _dec;
};
</code>```

Where you pass the type of the function in as part of the class type used like:

```<code>auto decide_fc = [](int x){ return x > 3; };
Decide<decltype(decide_fc)> greaterThanThree{decide_fc};
</code>```

Again, I was not sure why you are capturing x it made more sense (to me) to have a parameter that you pass in to the lambda) so you can use like:

```<code>int result = _dec(5); // or whatever value
</code>```

See the link for a complete example

Body:
Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.

Consider the following example

using DecisionFn = bool(*)();

class Decide
{
public:
    Decide(DecisionFn dec) : _dec{dec} {}
private:
    DecisionFn _dec;
};

int main()
{
    int x = 5;
    Decide greaterThanThree{ [x](){ return x > 3; } };
    return 0;
}

When I try to compile this, I get the following compilation error:

In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9:  note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are:
9:5:   note: Decide::Decide(DecisionFn)
9:5:   note: no known conversion for argument 1 from 'main()::<lambda()>' to 'DecisionFn {aka bool (*)()}'
6:7:   note: constexpr Decide::Decide(const Decide&)
6:7:   note: no known conversion for argument 1 from 'main()::<lambda()>' to 'const Decide&'
6:7:   note: constexpr Decide::Decide(Decide&&)
6:7:   note: no known conversion for argument 1 from 'main()::<lambda()>' to 'Decide&&'

That's one heck of an error message to digest, but I think what I'm getting out of it is that the lambda cannot be treated as a constexpr so therefore I cannot pass it as a function pointer? I've tried making x constexpr as well, but that doesn't seem to help.

Body:
Not a direct answer, but a slight variation to use the "functor" template pattern to hide away the specifics of the lambda type and keeps the code nice and simple.

I was not sure how you wanted to use the decide class so I had to extend the class with a function that uses it. See full example here: https://godbolt.org/z/jtByqE

The basic form of your class might look like this:

template <typename Functor>
class Decide
{
public:
    Decide(Functor dec) : _dec{dec} {}
private:
    Functor _dec;
};

Where you pass the type of the function in as part of the class type used like:

auto decide_fc = [](int x){ return x > 3; };
Decide<decltype(decide_fc)> greaterThanThree{decide_fc};

Again, I was not sure why you are capturing x it made more sense (to me) to have a parameter that you pass in to the lambda) so you can use like:

int result = _dec(5); // or whatever value

See the link for a complete example


问:
How To Reload Table?
I have 2 views we are dealing with.  Main View, and Sub View.

Main View's tablecell's string shows the count of the number of objects in that cell's subView.  When I delete a cell from the subview, and go back to the mainView, the string that shows the count should go down by 1.  Right now this string is not changing until I restart the app.

Any ideas how I can fix this?  The count is being pulled from a NSFetch.

Edit: Added Code

```<code>- (void)configureCell:(TDBadgedCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSDate *today = [NSDate date];
    NSDate *thisWeek  = [today dateByAddingTimeInterval: -604800.0];
    NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83];
    else if (indexPath.row == 2)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        self.predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp <= %@)", thisWeek, today];
        [fetchRequest setPredicate: predicate];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];
        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"Fetch error: %@", error);

        cell.badgeString = [NSString stringWithFormat:@"%i", [results count]];
        [fetchRequest release];
    }
    else if (indexPath.row == 3)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        self.predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp <= %@)", thisMonth, today];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];

        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"Fetch error: %@", error);

        cell.badgeString = [NSString stringWithFormat:@"%i", [results count]];
        [fetchRequest release];
    }
    else if (indexPath.row == 4)
    {
        cell.badgeString = [NSString stringWithFormat:@"%i", [[self.fetchedResultsController fetchedObjects] count]];
    }
</code>```

答: You need to be sure that you're getting the proper handle on the tableview, if you've made an accessor for your tableview in the header file then you need to call it by that name in the viewWillLoad method.</p>

Title: How To Reload Table?

Body:
I have 2 views we are dealing with.  Main View, and Sub View.

Main View's tablecell's string shows the count of the number of objects in that cell's subView.  When I delete a cell from the subview, and go back to the mainView, the string that shows the count should go down by 1.  Right now this string is not changing until I restart the app.

Any ideas how I can fix this?  The count is being pulled from a NSFetch.

Edit: Added Code

- (void)configureCell:(TDBadgedCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSDate *today = [NSDate date];
    NSDate *thisWeek  = [today dateByAddingTimeInterval: -604800.0];
    NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83];
    else if (indexPath.row == 2)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        self.predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp <= %@)", thisWeek, today];
        [fetchRequest setPredicate: predicate];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];
        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"Fetch error: %@", error);

        cell.badgeString = [NSString stringWithFormat:@"%i", [results count]];
        [fetchRequest release];
    }
    else if (indexPath.row == 3)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        self.predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp <= %@)", thisMonth, today];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];

        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"Fetch error: %@", error);

        cell.badgeString = [NSString stringWithFormat:@"%i", [results count]];
        [fetchRequest release];
    }
    else if (indexPath.row == 4)
    {
        cell.badgeString = [NSString stringWithFormat:@"%i", [[self.fetchedResultsController fetchedObjects] count]];
    }


问:
Android Retrofit - Putting the response into an arraylist
Hey guys I have retrofit successfully getting data from a rest API and its printing into the log. However when I try and capture this response into an array list I'm getting an error stating : "Cannot infer arguments (unable to resolve constructor). This error shows in the array list brackets <>

```<code>// Executes the network request on a background thread
        try {
            Response response = getWeather(locationCode, apiKey).execute();
            if (cancelRequest) {
                return;
            }
            if (response.code() == 200) {

                //  Weather weather = response.body().getWeather();
                Log.d(TAG, "onResponse: " + response.body().toString());

                List<Weather> list = new ArrayList<>(((Weather)response.body()));
                //mWeather.postValue(response);
</code>```

GSON Response

```<code> {
"coord": {
    "lon": -5.93,
    "lat": 54.58
},
"weather": [
    {
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04d"
    }
],
"base": "stations",
"main": {
    "temp": 291.56,
    "feels_like": 286.36,
    "temp_min": 291.15,
    "temp_max": 292.15,
    "pressure": 1024,
    "humidity": 45
},
</code>```

If anyone could help me root cause this it would be greatly appreciated.

答:
I feel the POJO Class which you have created might not be proper as you have not shared your POJO class please try the below POJO class in your code an see if the error still persists.

```<code>public class Weather {

private coordinate coord;
private ArrayList<weatherinfo> weather;
private String base;
private maininfo main;

public coordinate getCoord() {
    return coord;
}

public ArrayList<weatherinfo> getWeather() {
    return weather;
}

public String getBase() {
    return base;
}

public maininfo getMain() {
    return main;
}

public static class coordinate{
    String lon,lat;

    public String getLon() {
        return lon;
    }

    public String getLat() {
        return lat;
    }
}

public static class weatherinfo{
    String id,main,description,icon;

    public String getId() {
        return id;
    }

    public String getMain() {
        return main;
    }

    public String getDescription() {
        return description;
    }

    public String getIcon() {
        return icon;
    }
}

public static class maininfo{
    String temp,feels_like,temp_min,temp_max,pressure,humidity;

    public String getTemp() {
        return temp;
    }

    public String getFeels_like() {
        return feels_like;
    }

    public String getTemp_min() {
        return temp_min;
    }

    public String getTemp_max() {
        return temp_max;
    }

    public String getPressure() {
        return pressure;
    }

    public String getHumidity() {
        return humidity;
    }
}
}
</code>```

After that while reading your response try it this way.

```<code>ArrayList<Weather.weatherinfo> list = response.body().getWeather();
</code>```

Happy Coding

Body:
Hey guys I have retrofit successfully getting data from a rest API and its printing into the log. However when I try and capture this response into an array list I'm getting an error stating : "Cannot infer arguments (unable to resolve constructor). This error shows in the array list brackets <>

// Executes the network request on a background thread
        try {
            Response response = getWeather(locationCode, apiKey).execute();
            if (cancelRequest) {
                return;
            }
            if (response.code() == 200) {

                //  Weather weather = response.body().getWeather();
                Log.d(TAG, "onResponse: " + response.body().toString());

                List<Weather> list = new ArrayList<>(((Weather)response.body()));
                //mWeather.postValue(response);

GSON Response

 {
"coord": {
    "lon": -5.93,
    "lat": 54.58
},
"weather": [
    {
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04d"
    }
],
"base": "stations",
"main": {
    "temp": 291.56,
    "feels_like": 286.36,
    "temp_min": 291.15,
    "temp_max": 292.15,
    "pressure": 1024,
    "humidity": 45
},

If anyone could help me root cause this it would be greatly appreciated.

Body:
I feel the POJO Class which you have created might not be proper as you have not shared your POJO class please try the below POJO class in your code an see if the error still persists.

public class Weather {

private coordinate coord;
private ArrayList<weatherinfo> weather;
private String base;
private maininfo main;

public coordinate getCoord() {
    return coord;
}

public ArrayList<weatherinfo> getWeather() {
    return weather;
}

public String getBase() {
    return base;
}

public maininfo getMain() {
    return main;
}

public static class coordinate{
    String lon,lat;

    public String getLon() {
        return lon;
    }

    public String getLat() {
        return lat;
    }
}

public static class weatherinfo{
    String id,main,description,icon;

    public String getId() {
        return id;
    }

    public String getMain() {
        return main;
    }

    public String getDescription() {
        return description;
    }

    public String getIcon() {
        return icon;
    }
}

public static class maininfo{
    String temp,feels_like,temp_min,temp_max,pressure,humidity;

    public String getTemp() {
        return temp;
    }

    public String getFeels_like() {
        return feels_like;
    }

    public String getTemp_min() {
        return temp_min;
    }

    public String getTemp_max() {
        return temp_max;
    }

    public String getPressure() {
        return pressure;
    }

    public String getHumidity() {
        return humidity;
    }
}
}

After that while reading your response try it this way.

ArrayList<Weather.weatherinfo> list = response.body().getWeather();

Happy Coding


问:
OpenCV undefined reference to `cv::imread(cv::String const&, int)'
I cannot get opencv working in C++ code.
I've read all the similar question, but not have gotten my code to compile.

I installed OpenCV from source and included the -D OPENCV_GENERATE_PKGCONFIG=ON option and I'm trying to get a simple OpenCV example to work.

Here's the code:

```<code>    #include <opencv2/core.hpp>
    #include <opencv2/imgcodecs.hpp>
    #include <opencv2/highgui.hpp>
    #include <iostream>
    using namespace cv;
    int main()
    {
        std::string image_path = "/data/000001.jpg";
        Mat img = imread(image_path, IMREAD_COLOR);
        if(img.empty())
        {
            std::cout << "Could not read the image: " << image_path << std::endl;
            return 1;
        }
        imshow("Display window", img);
        int k = waitKey(0); // Wait for a keystroke in the window
        if(k == 's')
        {
            imwrite("starry_night.png", img);
        }
        return 0;
    }
</code>```

Trying to compile with: $/usr/bin/g++ -g pkg-config --cflags --libs opencv main.cpp
causes 'undefined reference' error for all OpenCV calls:
/code/cpp/play/main.cpp:9: undefined reference to `cv::imread(cv::String const&, int)'

Running pkg-config --cflags --libs opencv
returns:

pkg-config --cflags --libs opencv
 -I/usr/local/include/opencv -I/usr/local/include -L/usr/local/lib -lopencv_stitching -vlopencv_superres -lopencv_videostab -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_dnn_objdetect -lopencv_dpm -lopencv_face -lopencv_photo -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_hfs -lopencv_img_hash -lopencv_line_descriptor -lopencv_optflow -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_viz -lopencv_phase_unwrapping -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_dnn -lopencv_plot -lopencv_xfeatures2d -lopencv_shape -lopencv_video -lopencv_ml -lopencv_ximgproc -lopencv_xobjdetect -lopencv_objdetect -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_flann -lopencv_xphoto -lopencv_imgproc -lopencv_core

I also tried to build the code with cmake using this file:

```<code>    set(CMAKE_VERBOSE_MAKEFILE ON)
    cmake_minimum_required(VERSION 3.16)
    project(play)
    set(CMAKE_CXX_STANDARD 14)
    find_package(OpenCV REQUIRED)
    message(STATUS "OpenCV_INCLUDE_DIRS = ${OpenCV_INCLUDE_DIRS}")
    message(STATUS "OpenCV_LIBS = ${OpenCV_LIBS}")
    add_executable(play main.cpp)
</code>```

Is this what OpenCV_LIB is supposed to look like?  Is there supposed to be a path?

```<code>-- OpenCV_INCLUDE_DIRS = /usr/include;/usr/include/opencv
-- OpenCV_LIBS = opencv_calib3d;opencv_core;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_shape;opencv_stitching;opencv_superres;opencv_video;opencv_videoio;opencv_videostab;opencv_viz;opencv_aruco;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_datasets;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hdf;opencv_line_descriptor;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_reg;opencv_rgbd;opencv_saliency;opencv_stereo;opencv_structured_light;opencv_surface_matching;opencv_text;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto
-- Configuring done
</code>```

Thanks for the help.

答:
Thanks for the suggestions.
john was right.  This solved it:

```<code>g++ -g main.cpp `pkg-config --libs opencv`
</code>```

pkg-config needed to be after the source files.

Body:
I cannot get opencv working in C++ code.
I've read all the similar question, but not have gotten my code to compile.

I installed OpenCV from source and included the -D OPENCV_GENERATE_PKGCONFIG=ON option and I'm trying to get a simple OpenCV example to work.

Here's the code:

    #include <opencv2/core.hpp>
    #include <opencv2/imgcodecs.hpp>
    #include <opencv2/highgui.hpp>
    #include <iostream>
    using namespace cv;
    int main()
    {
        std::string image_path = "/data/000001.jpg";
        Mat img = imread(image_path, IMREAD_COLOR);
        if(img.empty())
        {
            std::cout << "Could not read the image: " << image_path << std::endl;
            return 1;
        }
        imshow("Display window", img);
        int k = waitKey(0); // Wait for a keystroke in the window
        if(k == 's')
        {
            imwrite("starry_night.png", img);
        }
        return 0;
    }

Trying to compile with: $/usr/bin/g++ -g pkg-config --cflags --libs opencv main.cpp
causes 'undefined reference' error for all OpenCV calls:
/code/cpp/play/main.cpp:9: undefined reference to `cv::imread(cv::String const&, int)'

Running pkg-config --cflags --libs opencv
returns:

pkg-config --cflags --libs opencv
 -I/usr/local/include/opencv -I/usr/local/include -L/usr/local/lib -lopencv_stitching -vlopencv_superres -lopencv_videostab -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_dnn_objdetect -lopencv_dpm -lopencv_face -lopencv_photo -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_hfs -lopencv_img_hash -lopencv_line_descriptor -lopencv_optflow -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_viz -lopencv_phase_unwrapping -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_dnn -lopencv_plot -lopencv_xfeatures2d -lopencv_shape -lopencv_video -lopencv_ml -lopencv_ximgproc -lopencv_xobjdetect -lopencv_objdetect -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_flann -lopencv_xphoto -lopencv_imgproc -lopencv_core

I also tried to build the code with cmake using this file:

    set(CMAKE_VERBOSE_MAKEFILE ON)
    cmake_minimum_required(VERSION 3.16)
    project(play)
    set(CMAKE_CXX_STANDARD 14)
    find_package(OpenCV REQUIRED)
    message(STATUS "OpenCV_INCLUDE_DIRS = ${OpenCV_INCLUDE_DIRS}")
    message(STATUS "OpenCV_LIBS = ${OpenCV_LIBS}")
    add_executable(play main.cpp)

Is this what OpenCV_LIB is supposed to look like?  Is there supposed to be a path?

-- OpenCV_INCLUDE_DIRS = /usr/include;/usr/include/opencv
-- OpenCV_LIBS = opencv_calib3d;opencv_core;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_shape;opencv_stitching;opencv_superres;opencv_video;opencv_videoio;opencv_videostab;opencv_viz;opencv_aruco;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_datasets;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hdf;opencv_line_descriptor;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_reg;opencv_rgbd;opencv_saliency;opencv_stereo;opencv_structured_light;opencv_surface_matching;opencv_text;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto
-- Configuring done

Thanks for the help.

Body:
Thanks for the suggestions.
john was right.  This solved it:

g++ -g main.cpp `pkg-config --libs opencv`

pkg-config needed to be after the source files.


问:
Is the global name 'a' in the same namespace as the module?
```<code>import math

a = 1

def my_func():
    print('don\'t downvote')

my_func()
</code>```

I believe that the function invocation my_func( ) lies in the local namespace created for the function my_func( ) - ready for correction. Is the name a contained in the same global namespace created for the math module?

答:
No. Let's say your file is called foo.py. When your module is imported, a new global namespace is created for foo, and it contains (among other things) three names:

math, which refers to the math module`

my_func, which refers to your function

a, which refers to 1

Where your function is called doesn't really matter. If my_func contained any free variables, they would always refer to foo's global namespace, not the namespace where it is called.

The math module has its own global namespace. ("Global" really isn't a good term; each module has its own module-level namespace.)

The only "global" namespace in Python is the built-in namespace, which is accessible from all modules.

Body:
import math

a = 1

def my_func():
    print('don\'t downvote')

my_func()

I believe that the function invocation my_func( ) lies in the local namespace created for the function my_func( ) - ready for correction. Is the name a contained in the same global namespace created for the math module?


问:
MongoDB, NodeJS. Get element from promise
I have request to DB with promises, I want to extract 2 values("latitude" and "longitude") for all documents and put it to array.

I'm doing like this;

```<code>const promises = [
    dbo.collection("users").find({ name: "Mark" }, { latitude: 1, longitude: 1, _id: 0 }).toArray()
]
Promise.all(promises).then(function (Presults) {
        console.log(Presults);

    }).catch(function (err) {
        console.log(err);
    });
</code>```

as a result I get all fields, for example: name, gender, latitude, longitude etc.
When I try to specify that I want only latitude, longitude, I always get result undefined
What I've tried: console.log(Presults.latitude);
console.log(Presults[0].latitude);

But I want get output array like this

```<code>[
    { lat: -31.563910, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 }
];
</code>```

I tested without promises, it works:

```<code>    dbo.collection("users").find(
    { name: "Mark" },
    { latitude: 1, longitude: 1, _id: 0 }).toArray(function (err, result) {
        if (err) throw err;
        var array1 = [];
        var z = { "lat": result[0].latitude, "lng": result[0].longitude };
        var y = { "lat": result[0].latitude, "lng": result[0].longitude };
        array1.push(z, y);

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

答:
Try this</p>

```<code>Promise.all(promises).then(function (results) {
    const data = results.flatMap(v => v.map(k => ({ lat: k.latitude, lng: k.longitude})))

    console.log(data)
})
</code>```

Body:
I have request to DB with promises, I want to extract 2 values("latitude" and "longitude") for all documents and put it to array.

I'm doing like this;

const promises = [
    dbo.collection("users").find({ name: "Mark" }, { latitude: 1, longitude: 1, _id: 0 }).toArray()
]
Promise.all(promises).then(function (Presults) {
        console.log(Presults);

    }).catch(function (err) {
        console.log(err);
    });

as a result I get all fields, for example: name, gender, latitude, longitude etc.
When I try to specify that I want only latitude, longitude, I always get result undefined
What I've tried: console.log(Presults.latitude);
console.log(Presults[0].latitude);

But I want get output array like this

[
    { lat: -31.563910, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 }
];

I tested without promises, it works:

    dbo.collection("users").find(
    { name: "Mark" },
    { latitude: 1, longitude: 1, _id: 0 }).toArray(function (err, result) {
        if (err) throw err;
        var array1 = [];
        var z = { "lat": result[0].latitude, "lng": result[0].longitude };
        var y = { "lat": result[0].latitude, "lng": result[0].longitude };
        array1.push(z, y);

        console.log(array1);
    });

Body:
Try this

Promise.all(promises).then(function (results) {
    const data = results.flatMap(v => v.map(k => ({ lat: k.latitude, lng: k.longitude})))

    console.log(data)
})


问:
Firebase authentication with email and password extra fields duplicating - Android - Java
I'm trying to authanticate users with email and password and I want to add two extra fields (name and kredi) when someone going to sign-up. But when I sign-up to my app, two more fields with "user" tag saving to firebase realtime database like this:

```<code>wohR9lJXnMgj9zCYMaasZDctrhf1
kredi:
"20"
name:
"test"
userKredi:
"20"
userName:
"test"
</code>```

I don't understand why this is happening. This is my sign-up activity code:

```<code>import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class SignUpActivity extends AppCompatActivity {

    EditText signUpMail,signUpPass,kullaniciAdi;
    Button signUpButton;
    private FirebaseAuth auth;
    private DatabaseReference databaseReference;

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

        auth=FirebaseAuth.getInstance();

        signUpMail = findViewById(R.id.signUpMail);
        signUpPass = findViewById(R.id.signUpPass);
        kullaniciAdi = findViewById(R.id.kullaniciAdi);
        auth=FirebaseAuth.getInstance();
        signUpButton = findViewById(R.id.signUpButton);

        signUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signUp();
            }
        });
    }
    private void signUp() {
        final String email = signUpMail.getText().toString().trim();
        final String pass = signUpPass.getText().toString().trim();
        final String kredi = "20";
        final String name = kullaniciAdi.getText().toString().trim();

        if(TextUtils.isEmpty(email)){
            Toast.makeText(getApplicationContext(),"Please enter your E-mail address",Toast.LENGTH_LONG).show();
            return;
        }
        if(TextUtils.isEmpty(pass)){
            Toast.makeText(getApplicationContext(),"Please enter your Password",Toast.LENGTH_LONG).show();
        }
        if (pass.length() == 0){
            Toast.makeText(getApplicationContext(),"Please enter your Password",Toast.LENGTH_LONG).show();
        }
        if (pass.length()<8){
            Toast.makeText(getApplicationContext(),"Password must be more than 8 digit",Toast.LENGTH_LONG).show();
        }
        else{
            auth.createUserWithEmailAndPassword(email,pass)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            if (task.isSuccessful()) {

                                Userinformation userinformation = new Userinformation(
                                        name,
                                        kredi
                                );

                                databaseReference = FirebaseDatabase.getInstance().getReference();
                                databaseReference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(userinformation).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){
                                            startActivity(new Intent(SignUpActivity.this, HomeActivity.class));
                                            finish();
                                        }
                                        else{
                                            Toast.makeText(SignUpActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });

                            }
                            else {
                                Toast.makeText(SignUpActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        }
    }
    public void navigate_sign_in(View v){
        Intent inent = new Intent(this, SignInActivity.class);
        startActivity(inent);
    }
}
</code>```

and Userinformation class:

```<code>public class Userinformation {
    public String name;
    public String kredi;

    public Userinformation(){
    }

    public Userinformation(String name,String kredi){
        this.name = name;
        this.kredi = kredi;
    }
    public String getUserName() {
        return name;
    }
    public String getUserKredi() {
        return kredi;
    }
}
</code>```

I just want to save those properties just once. How can I do this?

答:
The problem is at your pojo, change this

```<code>public String getUserName() {
        return name;
    }
    public String getUserKredi() {
        return kredi;
    }
</code>```

to this

```<code>public String getName() {
        return name;
    }
    public String getKredi() {
        return kredi;
    }
</code>```

Body:
I'm trying to authanticate users with email and password and I want to add two extra fields (name and kredi) when someone going to sign-up. But when I sign-up to my app, two more fields with "user" tag saving to firebase realtime database like this:

wohR9lJXnMgj9zCYMaasZDctrhf1
kredi:
"20"
name:
"test"
userKredi:
"20"
userName:
"test"

I don't understand why this is happening. This is my sign-up activity code:

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class SignUpActivity extends AppCompatActivity {

    EditText signUpMail,signUpPass,kullaniciAdi;
    Button signUpButton;
    private FirebaseAuth auth;
    private DatabaseReference databaseReference;

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

        auth=FirebaseAuth.getInstance();

        signUpMail = findViewById(R.id.signUpMail);
        signUpPass = findViewById(R.id.signUpPass);
        kullaniciAdi = findViewById(R.id.kullaniciAdi);
        auth=FirebaseAuth.getInstance();
        signUpButton = findViewById(R.id.signUpButton);

        signUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signUp();
            }
        });
    }
    private void signUp() {
        final String email = signUpMail.getText().toString().trim();
        final String pass = signUpPass.getText().toString().trim();
        final String kredi = "20";
        final String name = kullaniciAdi.getText().toString().trim();

        if(TextUtils.isEmpty(email)){
            Toast.makeText(getApplicationContext(),"Please enter your E-mail address",Toast.LENGTH_LONG).show();
            return;
        }
        if(TextUtils.isEmpty(pass)){
            Toast.makeText(getApplicationContext(),"Please enter your Password",Toast.LENGTH_LONG).show();
        }
        if (pass.length() == 0){
            Toast.makeText(getApplicationContext(),"Please enter your Password",Toast.LENGTH_LONG).show();
        }
        if (pass.length()<8){
            Toast.makeText(getApplicationContext(),"Password must be more than 8 digit",Toast.LENGTH_LONG).show();
        }
        else{
            auth.createUserWithEmailAndPassword(email,pass)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            if (task.isSuccessful()) {

                                Userinformation userinformation = new Userinformation(
                                        name,
                                        kredi
                                );

                                databaseReference = FirebaseDatabase.getInstance().getReference();
                                databaseReference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(userinformation).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){
                                            startActivity(new Intent(SignUpActivity.this, HomeActivity.class));
                                            finish();
                                        }
                                        else{
                                            Toast.makeText(SignUpActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });

                            }
                            else {
                                Toast.makeText(SignUpActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        }
    }
    public void navigate_sign_in(View v){
        Intent inent = new Intent(this, SignInActivity.class);
        startActivity(inent);
    }
}

and Userinformation class:

public class Userinformation {
    public String name;
    public String kredi;

    public Userinformation(){
    }

    public Userinformation(String name,String kredi){
        this.name = name;
        this.kredi = kredi;
    }
    public String getUserName() {
        return name;
    }
    public String getUserKredi() {
        return kredi;
    }
}

I just want to save those properties just once. How can I do this?

Body:
The problem is at your pojo, change this

public String getUserName() {
        return name;
    }
    public String getUserKredi() {
        return kredi;
    }

to this

public String getName() {
        return name;
    }
    public String getKredi() {
        return kredi;
    }


问:
Throwing own exceptions
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }
```

<p>Now I also have this exception that I wrote </p>

<pre class="lang-java prettyprint-override"><code>    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }
</code>```

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

```<code>class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}
</code>```

答:
I'd guess you have a class Bank or the like and a customer comes to do something with his money. So he gives you an account number, a task and maybe an amount of money.
This class would need an Array or List of Accounts. The methods in this class would be thew right place for your Exception. You than have methods, basically the same as in your account. They first check if the Account exists in the array / list and then call the method on the chosen account or throw the exception if it doesn't exist.

method vs function:
In my understanding methods and functions are the same except for one little difference: a function is a function in global space, whereas a method is a function bound to a class or an object. Thus Java doesn't have real functions. But in my understanding, every static method is a function, but bound to the namespace of a class. But that is more a practical than a theoretical point of view.

Title: Throwing own exceptions

Body:
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }

Now I also have this exception that I wrote

    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}


问:
PayPal payment without redirection to PayPal's website
Is there any way to integrate PayPal without redirecting user to PayPal's website for payment in case of debit cards or PayPal payment type ?</p>

答:
There are paypal products available in some countries with this functionalisty. I heard that Payflow Pro and Paypal Payments Advanced have such  functionality.

But actually from my developer experience, if Stripe platform is avaialble for country where your project is hosted, then better to use Stripe Elements - they found a way to securely place fancy controls to get CC info in a way your website can get just either a token or a payment method object, without redirects, and if necessary, show a popup with 3D secure window during payment flow.


问:
Display js array acquired via JSON to webpage
Sorry if causing troubles again =x

With the help from you guys especially Scott Harwell,  I managed to get my php array passed to js array with the following code:

```<code>var horse_array = <?php echo json_encode($horse_info);?>;
</code>```

However, now I encounter problem in displaying the content of array. I could not load it into my html tag with id="horse1_r".

The following is my js code:

```<code><script type="text/javascript">

var horse_array = <?php echo json_encode($horse_info);?>;

function goto1(hid) {

$("#horse1_r").html(horse_array);

}

</script>
</code>```

Your kind help will be much appreciated.

答:
First, json_encode returns a string, you have to decode it to JSON in JavaScrpt.

Second, you have to call goto1

```<code><script type="text/javascript">
    function goto1(horse_array) {
        // $("#horse1_r").html();
        // use horse_array
    }
    var horse_array = $.parseJSON(<?php echo json_encode($horse_info);?>);
    goto1(horse_array);
</script>
</code>```

PS: I think you should modify the goto1 function, it doen't make sense to me.

Body:
Sorry if causing troubles again =x

With the help from you guys especially Scott Harwell,  I managed to get my php array passed to js array with the following code:

var horse_array = <?php echo json_encode($horse_info);?>;

However, now I encounter problem in displaying the content of array. I could not load it into my html tag with id="horse1_r".

The following is my js code:

Your kind help will be much appreciated.

Body:
First, json_encode returns a string, you have to decode it to JSON in JavaScrpt.

Second, you have to call goto1

<script type="text/javascript">
    function goto1(horse_array) {
        // $("#horse1_r").html();
        // use horse_array
    }
    var horse_array = $.parseJSON(<?php echo json_encode($horse_info);?>);
    goto1(horse_array);
</script>

PS: I think you should modify the goto1 function, it doen't make sense to me.


问:
Python Key Generator with String dont work
```<code>import random

mod1 = "BOT"
mod2 = (random.randrange(1,9999))
mod3 = (random.randrange(1,9999))
mod4 = (random.randrange(1,9999))

key = mod1 + "-" + mod2 + "-" + mod3 + "-" + mod4
print(key)
</code>```

When i run this i become the error: TypeError: can only concatenate str (not "int") to str

Can anyone Help me

答:
You have to either convert the mod1-4 to a String if you want to concatenate with the character "-" or use f-string like below

```<code>key = str(mod1) + "-" + str(mod2) + "-" + str(mod3) + "-" + str(mod4)

# alternative
key = f"{mod1}-{mod2}-{mod3}-{mod4}"

print(key)
</code>```

Body:
import random

mod1 = "BOT"
mod2 = (random.randrange(1,9999))
mod3 = (random.randrange(1,9999))
mod4 = (random.randrange(1,9999))

key = mod1 + "-" + mod2 + "-" + mod3 + "-" + mod4
print(key)

When i run this i become the error: TypeError: can only concatenate str (not "int") to str

Can anyone Help me

Body:
You have to either convert the mod1-4 to a String if you want to concatenate with the character "-" or use f-string like below

key = str(mod1) + "-" + str(mod2) + "-" + str(mod3) + "-" + str(mod4)

# alternative
key = f"{mod1}-{mod2}-{mod3}-{mod4}"

print(key)


问:
Finding the longest word in a .txt file without punctuation marks
I am doing Python file I/O exercises and albeit made a huge progress on an exercise in which I try to find the longest words in each line of a .txt file, I can't get rid of the punctuation marks.

Here is the code I have:

```<code>with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))
</code>```

This is the output I get

This is the original-3.txt file where I am reading the data from

```<code>'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
</code>```

As you can see, I am getting the punctuation marks like ["," ";" "?" "!"]

How do you think I can only get the words themselves?

Thank you

答:
You have to strip those characters from the words:

```<code>with open("original-3.txt", 'r') as file1:
    lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(word.strip(",?;!\"") for word in line.split()), key=len))
</code>```

or you use regular expressions to extract everything that looks like a word (i.e. consists of letters):

```<code>import re

for line in lines:
    words = re.findall(r"\w+", line)
    if words:
        print(max(words, key=len))
</code>```

Body:
I am doing Python file I/O exercises and albeit made a huge progress on an exercise in which I try to find the longest words in each line of a .txt file, I can't get rid of the punctuation marks.

Here is the code I have:

with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))

This is the output I get

This is the original-3.txt file where I am reading the data from

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

As you can see, I am getting the punctuation marks like ["," ";" "?" "!"]

How do you think I can only get the words themselves?

Thank you

Body:
You have to strip those characters from the words:

with open("original-3.txt", 'r') as file1:
    lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(word.strip(",?;!\"") for word in line.split()), key=len))

or you use regular expressions to extract everything that looks like a word (i.e. consists of letters):

import re

for line in lines:
    words = re.findall(r"\w+", line)
    if words:
        print(max(words, key=len))


问:
How to find before VAT and total vat amount from the total bill amount?
In this case,
total bill amount 210
(vat percentage : 5%)

before vat: 200
vat amount: 10

How to find this before VAT and VAT amount from the total bill amount.I want to show these two in different fields.

答:
```<code>let total = 210;
let vatPercetage = 5;

let vat  = (vatPercetage * total) / (100 + vatPercetage)
billBeforeVat = total - vat
</code>```


问:
How can I change the options that `iframe-resizer` is using?
I have an iframe on my page and I'm using iframe-resizer to have it resize to match its content. I'm using the maxHeight option to limit its size. This is working fine.

However, sometimes I want to change the value of maxHeight, in response to actions in the parent page.

I've tried calling iframeResizer(newOptions, myIframe) but this doesn't seem to change anything - the old options are still in effect.

Is there a way I can change the options on the fly?

答: The options you pass to iframe-resizer are not changeable after it has been setup. </p>


问:
What's the best way to stop page scroll within a dropdown menu
I have a dropdown menu on mobile where the page is scrolling at the top when I open the menu.

What's the best way to solve this? here is an example

Tried:

```

<p>Didn't work.</p>

<p>Added css: </p>

```.body-overflow {
   overflow: hidden;
}
```

Didn't work.

What I've realised is that there are two overlapping touchable or scrollable areas. Touching the menu area enables you to move the page behind it. So if there is a way of creating an attribute z-index?

答: I can think of a few ways you can solve this. One way would be to make your top bar sticky. Another option would be to make your whole navigation fixed. Something else you could try is to turn off scrolling on the body element when the menu is expanded. Each of these have pros and cons and you might need to play around with them to find which works best for you.</p>

Body:
I have a dropdown menu on mobile where the page is scrolling at the top when I open the menu.

What's the best way to solve this? here is an example

Tried:

Didn't work.

Added css:

.body-overflow {
   overflow: hidden;
}

Didn't work.

What I've realised is that there are two overlapping touchable or scrollable areas. Touching the menu area enables you to move the page behind it. So if there is a way of creating an attribute z-index?


问:
Add element to binary tree Haskell
I'm implementing the insert function of a BST, below is my code:

```<code>data Tree a = Empty
 | Node Integer (Tree a) a (Tree a)
 deriving (Show, Eq)

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x Empty = Node 0 Empty x Empty
treeInsert x (Node height left a right)
 | x == a = Node height left x right
 | x < a = Node height (treeInsert x left) a right
 | x > a = Node height left a (treeInsert x right)
</code>```

When I use my code it doesn't do anything, like the recurrence is still working

```<code>   tree = foldTree [1, 2, 3]
   tree
=> Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 Empty)
   tree = treeInsert 4 tree
   tree
</code>```

I'm new to Haskell, could anybody help? Thanks a lot.

答:
By writing tree = treeInsert 4 tree, you define a new variable named tree that is defined in trems of itself. In Haskell all variables are immutable, so that means that once tree is assigned a value, you can not assign it a new value. What you can do is define a new variable with the same name, but then tree in the body of tree = … refers to itself.

You thus can use a new variable:

```<code><b>tree2</b> = treeInsert 4 tree</code>```

For example:

```<code>Prelude> tree = Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 Empty)
Prelude> tree2 = treeInsert 4 tree
Prelude> tree2
Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 (Node 0 Empty 4 Empty))</code>```

It looks like the "height" of the nodes is not properly updated however.

Using variables in terms of itself is not uncommon in Haskell, for example you can make an infinite list of zeros with:

```<code><b>zeros</b> = (0:<b>zeros</b>)</code>```

Title: Add element to binary tree Haskell

Body:
I'm implementing the insert function of a BST, below is my code:

data Tree a = Empty
 | Node Integer (Tree a) a (Tree a)
 deriving (Show, Eq)

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x Empty = Node 0 Empty x Empty
treeInsert x (Node height left a right)
 | x == a = Node height left x right
 | x  a = Node height left a (treeInsert x right)

When I use my code it doesn't do anything, like the recurrence is still working

   tree = foldTree [1, 2, 3]
   tree
=> Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 Empty)
   tree = treeInsert 4 tree
   tree

I'm new to Haskell, could anybody help? Thanks a lot.

Body:
By writing tree = treeInsert 4 tree, you define a new variable named tree that is defined in trems of itself. In Haskell all variables are immutable, so that means that once tree is assigned a value, you can not assign it a new value. What you can do is define a new variable with the same name, but then tree in the body of tree = … refers to itself.

You thus can use a new variable:

tree2 = treeInsert 4 tree

For example:

Prelude> tree = Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 Empty)
Prelude> tree2 = treeInsert 4 tree
Prelude> tree2
Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 (Node 0 Empty 4 Empty))

It looks like the "height" of the nodes is not properly updated however.

Using variables in terms of itself is not uncommon in Haskell, for example you can make an infinite list of zeros with:

zeros = (0:zeros)