问:
hidden tag missing argument
I started using a macro for rendering fields, with errors, if I fail to validate the form, I get this error. If I use the correct credentials I get redirected to where I should and no errors are shown, if I fail to validate it tries to redirect to this same route but raises this error.

```<code>"C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\users\views.py", line 43, in post
    return render_template(self.template_name, title=self.title, form=self.form_class)
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\flask\templating.py", line 140, in render_template
    ctx.app,
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\flask\templating.py", line 120, in _render
    rv = template.render(context)
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\jinja2\environment.py", line 1090, in render
    self.environment.handle_exception()
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\jinja2\environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\jinja2\_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\users\templates\users\login.html", line 3, in top-level template code
    {% from 'macros/_formhelpers.html' import render_field %}
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\templates\base.html", line 69, in top-level template code
    {% block content %}{% endblock %}
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\users\templates\users\login.html", line 9, in block "content"
    {{ form.hidden_tag() }}
TypeError: hidden_tag() missing 1 required positional argument: 'self'
127.0.0.1 - - [31/May/2020 11:29:52] "POST /login/ HTTP/1.1" 500 -
</code>```

Here is my login.html file:

```<code>{% extends "base.html" %}

{% from 'macros/_formhelpers.html' import render_field %}

{% block content %}
 <div class="container">
        <div class="content-section">
            <form method="POST" action="">
                {{ form.hidden_tag() }}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Log In to your account</legend>
                    <div>
                        {{ render_field(form.email) }}
                    </div>
                    <div>
                        {{ render_field(form.password) }}
                    </div>
                    <div>{{ form.remember }} {{ form.remember.label }}</div>
                </fieldset>
                <div class="form-group">
                    {{ form.submit(class="btn btn-outline-info") }}
                </div>
            </form>
        </div>
        <div class="border-top pt-3">
            <small class="text-muted">
                Have not registered yet? <a href="{{ url_for('users.register') }}">Sign Up</a>
            </small>
        </div>
    </div>
{% endblock %}
</code>```

And here is the macro _formhelpers.html file:

{% macro render_field(field) %}
    {{ field.label(class="form-control-label") }}

    {{ field(class="form-control form-control-lg") }}

    {% if field.errors %}

            {% for error in field.errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}```

答:
Turns out it had nothing to do with my html file, instead when I was returning my login template again instead of

```<code>return render_template(self.template_name, title=self.title, form=self.form_class)
</code>```

I needed to write this:

```<code>return render_template(self.template_name, title=self.title, form=self.form_class())
</code>```

Got the solution idea from this post:
Error: "TypeError: hidden_tag() missing 1 required positional argument: 'self' " in Flask, python

Title: hidden tag missing argument

Body:
I started using a macro for rendering fields, with errors, if I fail to validate the form, I get this error. If I use the correct credentials I get redirected to where I should and no errors are shown, if I fail to validate it tries to redirect to this same route but raises this error.

"C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\users\views.py", line 43, in post
    return render_template(self.template_name, title=self.title, form=self.form_class)
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\flask\templating.py", line 140, in render_template
    ctx.app,
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\flask\templating.py", line 120, in _render
    rv = template.render(context)
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\jinja2\environment.py", line 1090, in render
    self.environment.handle_exception()
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\jinja2\environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\venv\lib\site-packages\jinja2\_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\users\templates\users\login.html", line 3, in top-level template code
    {% from 'macros/_formhelpers.html' import render_field %}
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\templates\base.html", line 69, in top-level template code
    {% block content %}{% endblock %}
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\users\templates\users\login.html", line 9, in block "content"
    {{ form.hidden_tag() }}
TypeError: hidden_tag() missing 1 required positional argument: 'self'
127.0.0.1 - - [31/May/2020 11:29:52] "POST /login/ HTTP/1.1" 500 -

Here is my login.html file:

{% extends "base.html" %}

{% from 'macros/_formhelpers.html' import render_field %}

{% block content %}

            <form method="POST" action="">
                {{ form.hidden_tag() }}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Log In to your account</legend>

                        {{ render_field(form.email) }}

                        {{ render_field(form.password) }}

{{ form.remember }} {{ form.remember.label }}

                </fieldset>

                    {{ form.submit(class="btn btn-outline-info") }}

            </form>

                Have not registered yet? Sign Up

{% endblock %}

And here is the macro _formhelpers.html file:

{% macro render_field(field) %}
    {{ field.label(class="form-control-label") }}

    {{ field(class="form-control form-control-lg") }}

    {% if field.errors %}

            {% for error in field.errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

Body:
Turns out it had nothing to do with my html file, instead when I was returning my login template again instead of

return render_template(self.template_name, title=self.title, form=self.form_class)

I needed to write this:

return render_template(self.template_name, title=self.title, form=self.form_class())

Got the solution idea from this post:
Error: "TypeError: hidden_tag() missing 1 required positional argument: 'self' " in Flask, python


来源: stackexchange

问:
How to map images in reactjs
So in a Reactjs class component, I have an array in my state like this:

```<code>myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]
</code>```

and I mapped the array this way:

```<code>{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">
      <img src={ item.image } className="img-fluid" alt={item.title} />
      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}
</code>```

Now, everything works fine, except the image that doesn't display, I really don't understand where I'm getting it wrong.

Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.

答:
You can require dynamically with proper expression:

Change image to (remove ../../../assets/images/website/homepage/ and  .png):

```<code>const myArray = [
  {
    number: 1,
    title: 'Users',
    image: 'users',
  },
  {
    number: 2,
    title: 'Clients',
    image: 'clients',
  },
  {
    number: 3,
    title: 'Admin',
    image: 'admins',
  },
]
</code>```

And to render at UI (add directory path and the extension inside require):

```<code>{myArray.map((item, index) => (
  <Box key={index} className="col-sm-12">
    <img
      src={require('../../../assets/images/website/homepage/' +
        item.image +
        '.png')}
      className="img-fluid"
      alt={item.title}
    />
    <Typography variant="h4">{item.number}</Typography>
  </Box>
))}
</code>```

Why it works?:

Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.

ContentLicense: CC BY-SA 4.0

Title: How to map images in reactjs

Body:
So in a Reactjs class component, I have an array in my state like this:

myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]

and I mapped the array this way:

{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">

      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}

Now, everything works fine, except the image that doesn't display, I really don't understand where I'm getting it wrong.

Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.

Body:
You can require dynamically with proper expression:

Change image to (remove ../../../assets/images/website/homepage/ and  .png):

const myArray = [
  {
    number: 1,
    title: 'Users',
    image: 'users',
  },
  {
    number: 2,
    title: 'Clients',
    image: 'clients',
  },
  {
    number: 3,
    title: 'Admin',
    image: 'admins',
  },
]

And to render at UI (add directory path and the extension inside require):

{myArray.map((item, index) => (
  <Box key={index} className="col-sm-12">
    <img
      src={require('../../../assets/images/website/homepage/' +
        item.image +
        '.png')}
      className="img-fluid"
      alt={item.title}
    />
    <Typography variant="h4">{item.number}</Typography>
  </Box>
))}

Why it works?:

Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.


问:
pytorch got None after backward()
I am learning pytorch and write a simple code as below.

import torch
x = torch.randn(3,requires_grad=True).cuda()
print(x)
y = x * x
print(y)
y.backward(torch.tensor([1,1.0,1]).cuda())
print(x.grad)
```

```tensor([ 0.5934, -1.8813, -0.7817], device='cuda:0', grad_fn=<CopyBackwards>)
tensor([0.3521, 3.5392, 0.6111], device='cuda:0', grad_fn=<MulBackward0>)
None
```

<p>if I change the code as </p>

<pre class="lang-py prettyprint-override"><code>from torch.autograd import Variable
import torch
# x = torch.randn(3,requires_grad=True).cuda()
x = Variable(torch.randn(3).cuda(),requires_grad=True)
print(x)
y = x * x
print(y)
y.backward(torch.tensor([1,1.0,1]).cuda())
print(x.grad)
</code>```

```<code>tensor([0.9800, 0.3597, 1.6315], device='cuda:0', requires_grad=True)
tensor([0.9605, 0.1294, 2.6617], device='cuda:0', grad_fn=<MulBackward0>)
tensor([1.9601, 0.7194, 3.2630], device='cuda:0')
</code>```

The grad is ok. But why? I hate the Variable class.

env

python:3.8

pytorch:1.5

cuda :10.2

答:
I got it.

x = torch.randn(3,requires_grad=True).cuda()
```

<p>x is create by <strong>cuda()</strong>. So x is not a leaf tensor.</p>

<p>Change the code as below will be ok.</p>

<pre class="lang-py prettyprint-override"><code>x = torch.randn(3,requires_grad=True,device=0)
</code>```

Title: pytorch got None after backward()

Body:
I am learning pytorch and write a simple code as below.

import torch
x = torch.randn(3,requires_grad=True).cuda()
print(x)
y = x * x
print(y)
y.backward(torch.tensor([1,1.0,1]).cuda())
print(x.grad)

tensor([ 0.5934, -1.8813, -0.7817], device='cuda:0', grad_fn=<CopyBackwards>)
tensor([0.3521, 3.5392, 0.6111], device='cuda:0', grad_fn=<MulBackward0>)
None

if I change the code as

from torch.autograd import Variable
import torch
# x = torch.randn(3,requires_grad=True).cuda()
x = Variable(torch.randn(3).cuda(),requires_grad=True)
print(x)
y = x * x
print(y)
y.backward(torch.tensor([1,1.0,1]).cuda())
print(x.grad)

tensor([0.9800, 0.3597, 1.6315], device='cuda:0', requires_grad=True)
tensor([0.9605, 0.1294, 2.6617], device='cuda:0', grad_fn=<MulBackward0>)
tensor([1.9601, 0.7194, 3.2630], device='cuda:0')

The grad is ok. But why? I hate the Variable class.

env

python:3.8

pytorch:1.5

cuda :10.2

Body:
I got it.

x = torch.randn(3,requires_grad=True).cuda()

x is create by cuda(). So x is not a leaf tensor.

Change the code as below will be ok.

x = torch.randn(3,requires_grad=True,device=0)


问:
how to add mouse event to set of divs and load data from database form click div?
I am doing project using Laravel 5. I make set of div according to some dynamic number.
This is it out put.

This is code for creating above graphic.

```<code> <section class="content">
        <div class="box box-warning" align="center">
            <div class="gap">
                <div class="box-body">
                    @foreach($rooms as $room)
                    @if($room->roomState === 'Available')
                    <div  id='divelementone' style="width:75px;height:75px;border:1px solid #000;display:inline-block;background-color:yellowgreen;border-radius: 5px;padding-left:10px;padding-right:10px;">{{$room->room_code}}</div>
                    @elseif ($room->roomState === 'UnAvailable')
                    <div  id='divelementtwo' style="width:75px;height:75px;border:1px solid #000;display:inline-block;background-color:red;border-radius: 5px;padding-left:10px;padding-right:10px;">{{$room->room_code}}</div>
                    @elseif ($room->roomState === 'notCheckIn')
                    <div  id='divelementthree' style="width:75px;height:75px;border:1px solid #000;display:inline-block;background-color:yellow;border-radius: 5px;padding-left:10px;padding-right:10px;">{{$room->room_code}}</div>

                    @endif
                    @endforeach
                </div>
            </div>
        </div><!-- /.box -->
</section><!-- /.content -->
</code>```

now I want to attach every div(square) elements to mouse click event. when mouse over the div , change mouse pointer and get some database value specific id and also, I want to view  that value in tool tip or some suitable panel over the div(Square).

I try using JavaScript  to attach mouse click event ,but it work only with first div(square).

I am new comer to web development so , I haven't knowledge ,how to handle this requirement. please , expect some expert help as soon as possible.

Note :
My main purpose is attach mouse click events to every div and load datafrom db and view them tooltip or optionpane.

答:
      @foreach($rooms as $room)

roomState}}), {{$room->room_code}})" id='divelementone' style="width:75px;height:75px;border:1px solid #000;display:inline-block;background-color:yellowgreen;border-radius: 5px;padding-left:10px;padding-right:10px;">{{$room->room_code}}

      @endforeach

```

ContentLicense: CC BY-SA 3.0

Body:
I am doing project using Laravel 5. I make set of div according to some dynamic number.
This is it out put.

This is code for creating above graphic.

                    @foreach($rooms as $room)
                    @if($room->roomState === 'Available')

{{$room->room_code}}

                    @elseif ($room->roomState === 'UnAvailable')

{{$room->room_code}}

                    @elseif ($room->roomState === 'notCheckIn')

{{$room->room_code}}

                    @endif
                    @endforeach

now I want to attach every div(square) elements to mouse click event. when mouse over the div , change mouse pointer and get some database value specific id and also, I want to view  that value in tool tip or some suitable panel over the div(Square).

I try using JavaScript  to attach mouse click event ,but it work only with first div(square).

I am new comer to web development so , I haven't knowledge ,how to handle this requirement. please , expect some expert help as soon as possible.

Note :
My main purpose is attach mouse click events to every div and load datafrom db and view them tooltip or optionpane.

Body:
<div class="box-body">
      @foreach($rooms as $room)
         <div onclick="divClick({{$room->roomState}}), {{$room->room_code}})" id='divelementone' style="width:75px;height:75px;border:1px solid #000;display:inline-block;background-color:yellowgreen;border-radius: 5px;padding-left:10px;padding-right:10px;">{{$room->room_code}}</div>
      @endforeach
</div>


问:
ADO.NET Entity Framework tutorials
Does anyone know of any good tutorials on ADO.NET Entity Framework?

There are a few useful links here at Stack OverFlow, and I've found one tutorial at Jason's DotNet Architecture Blog, but can anyone recommend any other good tutorials?
Any tutorials available from Microsoft, either online or as part of any conference/course material?

答:
Sample application from MSDN

And some inside information from ADO.NET Team Blog

OwnerDisplayName: Yngvar

ContentLicense: CC BY-SA 2.5

Title: ADO.NET Entity Framework tutorials

LastEditorDisplayName: aku

OwnerDisplayName: Prakash


问:
Different orientation in a Multiple page PrintDocument (How to)
I have a PrintDocument that has several pages.
One page in that document must be in a Landscape orientations instead of Portrail.

As the PrintPage event is triggered for each page on the document... at the very begining of that event handler I set the PrintPageEventArgs.PageSettings.Landscape to true.

That doesn't works on THAT page... but I can see that Landscape is set to true and taked into account in the NEXT page.

I assume that somehow... after the event is triggered for a certain page you are not able to change the page orientation. That is more of less logic if you think it... but HOW COULD I SET THAT FLAG before EVENT fires in a multiple page PrintDocument?

Note: I don't know in advance if the "next" page will going to actually need a Landscape orientation.

答:
I'm no expert at printing in .NET; however using Reflector; it looks like you might want to handle the QueryPageSettings event on PrintDocument. It looks like PrintController's private PrintLoop() method, will invoke events in this order for each page:

QueryPageSettings

StartPage

PrintPage

EndPage

Hope this helps.

OwnerDisplayName: Romias

LastEditorDisplayName: Romias

OwnerDisplayName: Phil Price


问:
Convert QTextStream to QByteArray
I need to convert a QTextStream to a QByteArray, and then back again.  I found an example of QTextStream -> QByteArray by constructing a QTextStream(QBytearray) and then any text < < to the stream ends up in the bytearray.

But how about the other way?  Probably a one liner but I can figure it out.  Can someone post and explain?

答:
Check it out if your text stream works via file (maybe via socket):

```<code>QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
   return;

QTextStream in(&file);
QString text;

text = in.readAll();
file.close();

text.QString::toUtf8(); //convert your data to byte array
</code>```

To get your data back use: QString::fromUtf8(const QByteArray &str)

Title: Convert QTextStream to QByteArray

Body:
Check it out if your text stream works via file (maybe via socket):

QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
   return;

QTextStream in(&file);
QString text;

text = in.readAll();
file.close();

text.QString::toUtf8(); //convert your data to byte array

To get your data back use: QString::fromUtf8(const QByteArray &str)


问:
Add one fore each identical index
```<code>l = ['a','b','c','a','a','c']
l1 = ['a1','b','c1','a2','a3','c2']
</code>```

I've a list that looks like this, and if there is more then one index that are identical I want to add one so that the list looks like l1 but I can´t figure out how

答:
Using brute force</p>

```<code>l = ['a','b','c','a','a','c']
b = set(l)
for elem in b:
    count = l.count(elem)
    if count > 1:
        dup = 1
        for i in range(len(l)):
            if l[i] == elem:
                l[i] = l[i] + str(dup)
                dup += 1
print('l: ', l)
</code>```

Title: Add one fore each identical index

Body:
l = ['a','b','c','a','a','c']
l1 = ['a1','b','c1','a2','a3','c2']

I've a list that looks like this, and if there is more then one index that are identical I want to add one so that the list looks like l1 but I can´t figure out how

Body:
Using brute force

l = ['a','b','c','a','a','c']
b = set(l)
for elem in b:
    count = l.count(elem)
    if count > 1:
        dup = 1
        for i in range(len(l)):
            if l[i] == elem:
                l[i] = l[i] + str(dup)
                dup += 1
print('l: ', l)


问:
Translate ternary operator to if function
I tried to use if function inside the container to make the card is not showing when the data is null. However, it always give warning return an identifier.

I can make it using ternary operation, can someone help me to translate it into if function?

this is my code:

```<code>                        Container(
                            child: snapshot.data.notes == null
                                ? null
                                : Card(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 8),
                                      child: Row(
                                        children: <Widget>[
                                          Icon(Icons.short_text),
                                          SizedBox(
                                            width: 8,
                                          ),
                                          Expanded(
                                            child: NotesDetail(
                                              initialValue: snapshot.data.notes,
                                              changeValue: (value) {
                                                print(value);
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                              )),
</code>```

答:
You can add not null condition at the top</p>

```<code>if(snapshot.data.notes != null)
                                 Card(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 8),
                                      child: Row(
                                        children: <Widget>[
                                          Icon(Icons.short_text),
                                          SizedBox(
                                            width: 8,
                                          ),
                                          Expanded(
                                            child: NotesDetail(
                                              initialValue: snapshot.data.notes,
                                              changeValue: (value) {
                                                print(value);
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),

}
</code>```

Body:
I tried to use if function inside the container to make the card is not showing when the data is null. However, it always give warning return an identifier.

I can make it using ternary operation, can someone help me to translate it into if function?

this is my code:

                        Container(
                            child: snapshot.data.notes == null
                                ? null
                                : Card(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 8),
                                      child: Row(
                                        children: <Widget>[
                                          Icon(Icons.short_text),
                                          SizedBox(
                                            width: 8,
                                          ),
                                          Expanded(
                                            child: NotesDetail(
                                              initialValue: snapshot.data.notes,
                                              changeValue: (value) {
                                                print(value);
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                              )),

Body:
You can add not null condition at the top

if(snapshot.data.notes != null)
                                 Card(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 8),
                                      child: Row(
                                        children: <Widget>[
                                          Icon(Icons.short_text),
                                          SizedBox(
                                            width: 8,
                                          ),
                                          Expanded(
                                            child: NotesDetail(
                                              initialValue: snapshot.data.notes,
                                              changeValue: (value) {
                                                print(value);
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),

}


问:
How to get the root directory path in Flutter
Is there a plugin for this problem or can it be solved using dart:io, because path_provider does not have a method for accessing the root directory?

答:
The Directory class may have what you are looking for.

var myDir = new Directory('path_to_root');


问:
Live search bug
I am fetching users preferences and roles, which works all fine and data received correctly.
Default value is placed on the radio buttons to highlight which option user currently have.

I am using Antd Design Table component .

Problem: When i am changing users preferences to printed documents, it successfully does change it by the state of DB however now if i search for other users, the user that appeared on the same row as the previous one will also have printed documents, so it looks like the no matter what results appeared after the search, the change made on the particular row will also be shown in the same row with different results.

```<code> class PreferenceUpdate extends PureComponent {

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

    handleChange = (event) => {
        this.setState({
            userPreference: {
                preference: event.target.value
            }
        });
        this.props.onPreferenceChange(event.target.value);
    };

    render() {
        return (
            <div>
                <Radio.Group defaultValue={this.state.userPreference.isOnlineSystem} size={"small"}
                             onChange={this.handleChange}>
                    <Radio.Button value={false}>Printed Documents</Radio.Button>
                    <Radio.Button value={true}>Online System</Radio.Button>
                </Radio.Group>
            </div>
        )
    };

}

export default PreferenceUpdate;

 const columns = [
    {
        title: 'Email',
        dataIndex: 'email',
        key: 'email',
        render: (text, record) =>
            <div className={"email-text"}>{record.email}</div>
    },
    {
        title: 'Preference',
        dataIndex: 'isOnlineSystem',
        key: 'isOnlineSystem',
        render: (text, record) => {
            return <
                PreferenceUpdate preference={record} onPreferenceChange={(value) => {
                const payload = {isOnlineSystem: value, email: record.email};
                setUserPreference(payload).then(r => {
                    if (r.status < 300) {
                        success("Preference was successfully updated");
                    } else {
                        errorWithMessage({
                            message: "Preference was not updated"
                        })
                    }
                });
            }
            }/>
        }
    },
    {
        title: 'Role',
        dataIndex: 'role',
        key: 'role',
        render: (text, record) => {
            return <RoleUpdate role={record} onRoleChange={(role) => {
                const payload = {role: role, email: record.email};
                updateUserRole(payload).then(r => {
                    if (r.status < 300) {
                        success("Role was successfully updated");
                    } else {
                        errorWithMessage({
                            message: "Role was not updated"
                        })
                    }
                });
            }
            }/>
        }
    }

];

const TextStyle = styled.div`
   font-style: normal;
   font-weight: 600;
   font-size: 13px;
   line-height: 16px;
   color: #1B2F55;
   margin-bottom: 10px

`;

class SearchInput extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            query: '',
            results: [],
        };
    }

    fetchSearchResults = (e) => {
        getUserPreference(e).then(r => {
            if (r.status < 300) {
                this.setState({results: r.data});
            } else {
                errorWithMessage({
                    message: "Could not get data from the server"
                })
            }
        })
    };

    handleInputChange = (e) => {
        this.setState({
            query: e.target.value
        }, () => {
            this.fetchSearchResults(this.state.query)

        })
    };

    render() {

        return (
            <div className="container">
                <h2 style={{marginTop: '200px'}} className="heading">User Search</h2>
                <TextStyle>As an admin you are able to modify user's current preference state and current
                    role</TextStyle>
                <Search
                    value={this.state.query}
                    style={{width: '100%', height: '35px'}}
                    placeholder={'Search....'}
                    onChange={this.handleInputChange}
                />
                <div style={{marginTop: '15px'}}>
                    <Table size={"middle"}
                           columns={columns}
                           dataSource={this.state.results}
                    />
                </div>
            </div>
        );
    }
}

export default SearchInput;
</code>```

答:
In order for Table Row to reset its properties, you need to provide a key to be used as the each row.

You can specify which attribute you TableRow needs to use as a key by usiung rowKey attribute on table

```<code><Table size={"middle"}
    rowKey={'email'}
    columns={columns}
    dataSource={this.state.results}
/>
</code>```

Title: Live search bug

Body:
I am fetching users preferences and roles, which works all fine and data received correctly.
Default value is placed on the radio buttons to highlight which option user currently have.

I am using Antd Design Table component .

Problem: When i am changing users preferences to printed documents, it successfully does change it by the state of DB however now if i search for other users, the user that appeared on the same row as the previous one will also have printed documents, so it looks like the no matter what results appeared after the search, the change made on the particular row will also be shown in the same row with different results.

 class PreferenceUpdate extends PureComponent {

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

    handleChange = (event) => {
        this.setState({
            userPreference: {
                preference: event.target.value
            }
        });
        this.props.onPreferenceChange(event.target.value);
    };

    render() {
        return (

                <Radio.Group defaultValue={this.state.userPreference.isOnlineSystem} size={"small"}
                             onChange={this.handleChange}>
                    <Radio.Button value={false}>Printed Documents</Radio.Button>
                    <Radio.Button value={true}>Online System</Radio.Button>
                </Radio.Group>

        )
    };

}

export default PreferenceUpdate;

 const columns = [
    {
        title: 'Email',
        dataIndex: 'email',
        key: 'email',
        render: (text, record) =>

{record.email}

    },
    {
        title: 'Preference',
        dataIndex: 'isOnlineSystem',
        key: 'isOnlineSystem',
        render: (text, record) => {
            return <
                PreferenceUpdate preference={record} onPreferenceChange={(value) => {
                const payload = {isOnlineSystem: value, email: record.email};
                setUserPreference(payload).then(r => {
                    if (r.status < 300) {
                        success("Preference was successfully updated");
                    } else {
                        errorWithMessage({
                            message: "Preference was not updated"
                        })
                    }
                });
            }
            }/>
        }
    },
    {
        title: 'Role',
        dataIndex: 'role',
        key: 'role',
        render: (text, record) => {
            return <RoleUpdate role={record} onRoleChange={(role) => {
                const payload = {role: role, email: record.email};
                updateUserRole(payload).then(r => {
                    if (r.status < 300) {
                        success("Role was successfully updated");
                    } else {
                        errorWithMessage({
                            message: "Role was not updated"
                        })
                    }
                });
            }
            }/>
        }
    }

];

const TextStyle = styled.div`
   font-style: normal;
   font-weight: 600;
   font-size: 13px;
   line-height: 16px;
   color: #1B2F55;
   margin-bottom: 10px

`;

class SearchInput extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            query: '',
            results: [],
        };
    }

    fetchSearchResults = (e) => {
        getUserPreference(e).then(r => {
            if (r.status < 300) {
                this.setState({results: r.data});
            } else {
                errorWithMessage({
                    message: "Could not get data from the server"
                })
            }
        })
    };

    handleInputChange = (e) => {
        this.setState({
            query: e.target.value
        }, () => {
            this.fetchSearchResults(this.state.query)

        })
    };

    render() {

        return (

User Search

                <TextStyle>As an admin you are able to modify user's current preference state and current
                    role</TextStyle>
                <Search
                    value={this.state.query}
                    style={{width: '100%', height: '35px'}}
                    placeholder={'Search....'}
                    onChange={this.handleInputChange}
                />

        );
    }
}

export default SearchInput;

Body:
In order for Table Row to reset its properties, you need to provide a key to be used as the each row.

You can specify which attribute you TableRow needs to use as a key by usiung rowKey attribute on table

<Table size={"middle"}
    rowKey={'email'}
    columns={columns}
    dataSource={this.state.results}
/>


问:
Create a function that computes the approximation of pi, based on the number of iterations specified
hint：pi can be computed by 4*(1-1/3+1/5-1/7+1/9- ...).

I have idea to solve this question by using while loop, but I'm confused that, in while loop, how can I save my variable every time when i use if conditional.

Here is my code.

```<code>def piA(num):
i = 1
pi = 4
while i <= num:
    s = 0
    float(s)
    if i % 2 == 1:
        s = s + (1/(2*i-1))
        print(s)
    elif i % 2 == 0:
        s = s - (1/(2*i-1))
        print(s)
    i += 1
    print(s)
return pi*s
print(piA(2))
</code>```

The result shows:
1.0
1.0
-0.3333333333333333
-0.3333333333333333
-1.3333333333333333

答:
You don't have to save the previous variable, just use builtin method sum():

```<code>def pi(num):
    return 4*sum((1 if i % 2 else -1)*(1 / (2*i - 1)) for i in range(1, num+1))

print(pi(10000))
</code>```

Prints:

```<code>3.1414926535900345
</code>```

Body:
hint：pi can be computed by 4*(1-1/3+1/5-1/7+1/9- ...).

I have idea to solve this question by using while loop, but I'm confused that, in while loop, how can I save my variable every time when i use if conditional.

Here is my code.

def piA(num):
i = 1
pi = 4
while i <= num:
    s = 0
    float(s)
    if i % 2 == 1:
        s = s + (1/(2*i-1))
        print(s)
    elif i % 2 == 0:
        s = s - (1/(2*i-1))
        print(s)
    i += 1
    print(s)
return pi*s
print(piA(2))

The result shows:
1.0
1.0
-0.3333333333333333
-0.3333333333333333
-1.3333333333333333

Body:
You don't have to save the previous variable, just use builtin method sum():

def pi(num):
    return 4*sum((1 if i % 2 else -1)*(1 / (2*i - 1)) for i in range(1, num+1))

print(pi(10000))

Prints:

3.1414926535900345


问:
Error in `file.write`, wrong argument type
Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data without turning it into a dictionary. How do you skip over the header record with the field names?

```<code>import os
import csv
# Create a file with data in it
def create_file(filename):
  with open(filename, "w") as file:
    fieldnames = ['type', 'name', 'color']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    file.write({'type': 'annual', 'name': 'carnation' , 'color': 'pink'})
    file.write({'type': 'perennial','name': 'daffodil' , 'color': 'yellow'})
    file.write({'type': 'perennial','name': 'iris' , 'color': 'blue'})
    file.write({'type': 'perennial','name': 'poinsettia' , 'color': 'red'})
    file.write({'type': 'annual', 'name': 'sunflower', 'color': 'yelolow'})
   # file.write("name,color,type\n")
    #file.write("carnation,pink,annual\n")
    #file.write("daffodil,yellow,perennial\n")
    #file.write("iris,blue,perennial\n")
    #file.write("poinsettia,red,perennial\n")
    #file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file
  create_file(filename)

  # Open the file
  with open('flowers.csv', 'r') as file:
    # Read the rows of the file
    rowss = csv.reader(file)
    header = next(rowss)
    if header != None:
      for row in rowss:
        # Format the return string for data rows only
        return_string = "a {} {} is {}\n".format(row['color'], row['name'], row['type'])
        print(return_string)

#Call the function

print(contents_of_file("flowers.csv"))

</code>```

it shows error as:

```<code>Error on line 42:
    print(contents_of_file("flowers.csv"))
Error on line 26:
    create_file(filename)
Error on line 9:
    file.write({'type': 'annual', 'name': 'carnation' , 'color': 'pink'})
TypeError: write() argument must be str, not dict
</code>```

答:
Change file.write() to writer.writerow(). file objects don't have a method that take in dictionaries. To write as dictionaries, use the csv.DictWriter() i.e. writer object instead.
Also, here:

```<code>with open('flowers.csv', 'r') as file:
</code>```

I don't think you intend to hard-code the filename ad 'flowers.csv', you have already passed the filename as parameter to the contents_of_file() method.

Body:
Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data without turning it into a dictionary. How do you skip over the header record with the field names?

import os
import csv
# Create a file with data in it
def create_file(filename):
  with open(filename, "w") as file:
    fieldnames = ['type', 'name', 'color']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    file.write({'type': 'annual', 'name': 'carnation' , 'color': 'pink'})
    file.write({'type': 'perennial','name': 'daffodil' , 'color': 'yellow'})
    file.write({'type': 'perennial','name': 'iris' , 'color': 'blue'})
    file.write({'type': 'perennial','name': 'poinsettia' , 'color': 'red'})
    file.write({'type': 'annual', 'name': 'sunflower', 'color': 'yelolow'})
   # file.write("name,color,type\n")
    #file.write("carnation,pink,annual\n")
    #file.write("daffodil,yellow,perennial\n")
    #file.write("iris,blue,perennial\n")
    #file.write("poinsettia,red,perennial\n")
    #file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file
  create_file(filename)

  # Open the file
  with open('flowers.csv', 'r') as file:
    # Read the rows of the file
    rowss = csv.reader(file)
    header = next(rowss)
    if header != None:
      for row in rowss:
        # Format the return string for data rows only
        return_string = "a {} {} is {}\n".format(row['color'], row['name'], row['type'])
        print(return_string)

#Call the function

print(contents_of_file("flowers.csv"))

it shows error as:

Error on line 42:
    print(contents_of_file("flowers.csv"))
Error on line 26:
    create_file(filename)
Error on line 9:
    file.write({'type': 'annual', 'name': 'carnation' , 'color': 'pink'})
TypeError: write() argument must be str, not dict

Body:
Change file.write() to writer.writerow(). file objects don't have a method that take in dictionaries. To write as dictionaries, use the csv.DictWriter() i.e. writer object instead.
Also, here:

with open('flowers.csv', 'r') as file:

I don't think you intend to hard-code the filename ad 'flowers.csv', you have already passed the filename as parameter to the contents_of_file() method.


问:
Callback on memory access?
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?

For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.

The platform I'm working on is x86 Linux and writing in C/C++.

答:
You can use your own version of a "safe-pointer"-like class which will wrap the allocated pointer, and by the way will have an implementation of the dereference operator. It will require using it of cause for allocations, though.

Something in these lines:

```<code>// based on pretty standard auto_ptr
template <class T> class auto_ptr
{
    T* ptr;
public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;}
    T& operator*()              {return *ptr;}   // <<--- add your stuff here
    T* operator->()             {return ptr;} // <<--- and here
    // .
};
</code>```

Title: Callback on memory access?

Body:
You can use your own version of a "safe-pointer"-like class which will wrap the allocated pointer, and by the way will have an implementation of the dereference operator. It will require using it of cause for allocations, though.

Something in these lines:

// based on pretty standard auto_ptr
template <class T> class auto_ptr
{
    T* ptr;
public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;}
    T& operator*()              {return *ptr;}   // <<--- add your stuff here
    T* operator->()             {return ptr;} // <<--- and here
    // .
};


问:
How to do calc function on vendor-prefixed properties in css?
I have to build a navbar that slides from the right side of the screen. It has to cover the whole screen. The problem is that in mobile phones, browsers like chrome have this toolbar at the bottom, which hides some part of the page. Which is not feasible as I also have to display some contact information at the bottom.

The fix for this was using -webkit-fill-available.
But, the css for my navbar and the hamburger menu row is :

```<code>.hamburger-row {
   position: fixed;
   height: 75px;
}
</code>```

And for navigation menu div...

```<code> .nav-menu-div {
    position: fixed;
    height: calc(100vh - 75px);
 }
</code>```

But to introduce -webkit-fill-available, I have to do something like

```<code> height: calc(-webkit-fill-available - 75px);
</code>```

which is not possible in css.

Is there any workaround?

答:
if your problem is that the div isn't showing do you need to put the width property and the background-color (of image) property , if you don't have this, the div isn't showing.

Hope I help you

Body:
I have to build a navbar that slides from the right side of the screen. It has to cover the whole screen. The problem is that in mobile phones, browsers like chrome have this toolbar at the bottom, which hides some part of the page. Which is not feasible as I also have to display some contact information at the bottom.

The fix for this was using -webkit-fill-available.
But, the css for my navbar and the hamburger menu row is :

.hamburger-row {
   position: fixed;
   height: 75px;
}

And for navigation menu div...

 .nav-menu-div {
    position: fixed;
    height: calc(100vh - 75px);
 }

But to introduce -webkit-fill-available, I have to do something like

 height: calc(-webkit-fill-available - 75px);

which is not possible in css.

Is there any workaround?


问:
Remove "overflow: hidden" inline style on Fancybox container on Wordpress
how do I remove overflow:hidden; inline style from the fancybox-content div? I'm using FancyBox 3.5.7. It seems Wordpress is overriding the code. Before coding for WordPress, the inline style was display: inline-block;. Now that I imported the code to Wordpress, it has been added overflow: hidden; when I intended not to. Would appreciate the help in advance, thanks guys.

How do I remove the additional overflow: hidden; inline style from the fancybox-content div. Working on Wordpress

答:
you can add your customized CSS and use
overflow: '(your attribute)' !Important.</p>

<p>!Important is specifying that what property will be affected.
or use inline overflow:none to disable it  </p>

Body:
you can add your customized CSS and use
overflow: '(your attribute)' !Important.

!Important is specifying that what property will be affected.
or use inline overflow:none to disable it


问:
How to follow the condition to underline in the table?
I have a question how to underline in the table according the column data. Below is example coding to explain what I am facing the problem:

I want to detect if column underline is 1 the first name data will draw the underline, if 0 the first name data no show the underline.  Below the sample is hardcode, if real situation, I have too many row to show the data, I cannot 1 by 1 to add text-decoration: underline; in the td. So that, hope someone can guide me how to solve this problem. I am using the php code to make the variable to define the underline.

<?php
if ( Underline	 == 1) {
$add_underline = "text-decoration: underline;";
                                }
 if ( Underline	 == 0) {
$add_underline = "text-decoration: underline;";
                                }
?>

    Firstname
    Lastname
    Underline

    <td style="<?php echo $add_underline;?> ">Jill
    Smith
    1

    <td style="<?php echo $add_underline;?>">Eve
    Jackson
    0

    <td style="<?php echo $add_underline;?>">John
    Doe
    1

```

My output like below the picture:

My expected result like below the picture, Jill and John can underline:

答:
Why not use javascript to achieve this? No matter what the server sends it will evaluate the condition if 1 is set and then underline accordingly... You would have to use classes to get the appropriate table data tags holding the values, I added class='name' to the names  tag and class='underline' tot he underline  tag.

// get the values of the elements with a class of 'name'
let names = document.getElementsByClassName('name');
// get the values of the elements with a class of 'underline'
let underline = document.getElementsByClassName('underline');
// loop over elements using for and use the keys to get and set values
// `i` will iterate until it reaches the length of the list of elements with class of underline
for(let i = 0; i < underline.length; i++){
  // use the key to get the text content and check if 1 is set use Number to change string to number for strict evaluation
  if(Number(underline[i].textContent) === 1){
      // set values set to 1 to underline in css style
      names[i].style.textDecoration = "underline";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Underline</th>
  </tr>
  <tr>
    <td class="name">Jill</td>
    <td>Smith</td>
    <td class='underline'>1</td>
  </tr>
  <tr>
    <td class="name">Eve</td>
    <td>Jackson</td>
    <td class='underline'>0</td>
  </tr>
  <tr>
    <td class="name">John</td>
    <td>Doe</td>
    <td class='underline'>1</td>
  </tr>
</table></code>```

Or using the td child values...

let tr = document.querySelectorAll("tr");
last = null;
for(let i = 1; i < tr.length; i++){
  if(Number(tr[i].lastElementChild.innerHTML) === 1){
      tr[i].firstElementChild.style.textDecoration = "underline";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Underline</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>1</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>0</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>1</td>
  </tr>
</table></code>```

Body:
I have a question how to underline in the table according the column data. Below is example coding to explain what I am facing the problem:

I want to detect if column underline is 1 the first name data will draw the underline, if 0 the first name data no show the underline.  Below the sample is hardcode, if real situation, I have too many row to show the data, I cannot 1 by 1 to add text-decoration: underline; in the td. So that, hope someone can guide me how to solve this problem. I am using the php code to make the variable to define the underline.

<?php
if ( Underline	 == 1) {
$add_underline = "text-decoration: underline;";
                                }
 if ( Underline	 == 0) {
$add_underline = "text-decoration: underline;";
                                }
?>

    Firstname
    Lastname
    Underline

    <td style="<?php echo $add_underline;?> ">Jill
    Smith
    1

    <td style="<?php echo $add_underline;?>">Eve
    Jackson
    0

    <td style="<?php echo $add_underline;?>">John
    Doe
    1

My output like below the picture:

My expected result like below the picture, Jill and John can underline:

Body:
Why not use javascript to achieve this? No matter what the server sends it will evaluate the condition if 1 is set and then underline accordingly... You would have to use classes to get the appropriate table data tags holding the values, I added class='name' to the names <td> tag and class='underline' tot he underline <td> tag.

// get the values of the elements with a class of 'name'
let names = document.getElementsByClassName('name');
// get the values of the elements with a class of 'underline'
let underline = document.getElementsByClassName('underline');
// loop over elements using for and use the keys to get and set values
// `i` will iterate until it reaches the length of the list of elements with class of underline
for(let i = 0; i < underline.length; i++){
  // use the key to get the text content and check if 1 is set use Number to change string to number for strict evaluation
  if(Number(underline[i].textContent) === 1){
      // set values set to 1 to underline in css style
      names[i].style.textDecoration = "underline";
  }
}

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Underline</th>
  </tr>
  <tr>
    <td class="name">Jill</td>
    <td>Smith</td>
    <td class='underline'>1</td>
  </tr>
  <tr>
    <td class="name">Eve</td>
    <td>Jackson</td>
    <td class='underline'>0</td>
  </tr>
  <tr>
    <td class="name">John</td>
    <td>Doe</td>
    <td class='underline'>1</td>
  </tr>
</table>

Or using the td child values...

let tr = document.querySelectorAll("tr");
last = null;
for(let i = 1; i < tr.length; i++){
  if(Number(tr[i].lastElementChild.innerHTML) === 1){
      tr[i].firstElementChild.style.textDecoration = "underline";
  }
}

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Underline</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>1</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>0</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>1</td>
  </tr>
</table>


问:
Xcode won't recognize my new provisioning profile
My app's development provisioning profile expired a couple of weeks ago, so I went to the provisioning portal to get a fresh new one. After obtaining it, I visited the Xcode Organizer, removed the expired profile from my devices as well as my Mac, then imported the new profile. Xcode installs the profile onto my devices immediately, and my app runs again on the devices.

The problem is that while the Organizer is able to see the new profile and install it as normal, the IDE gets confused between the old one and the new one. Every time I try to build the app, it fails immediately. The error console tells me that Xcode can't find the old profile, because the GUID listed belongs to the old one. That's strange; I thought Xcode would've been aware of the new profile by now.

I've tried removing the new profile from my devices and my Mac, then reinstalling the profile. Doesn't work, Xcode is still trying to look for the old one. I've also tried selecting a different profile to make Xcode forget the old one, then selecting the new one. I've even tried manually entering the GUID of the new one in the Other choice. Yet Xcode still insists on looking for the old profile, which by now is already gone from my Mac.

How do I convince Xcode that I've generated a new provisioning profile for my app for it to use?

答:
Here's how I did it in Xcode 4:

Select Don't Code Sign from Project > Build Settings > Code Signing

Clean the build

Build it again - should show an error like "this stuff needs signing"

Choose the new profile from the Code Signing

Rebuild


问:
SQLyog Function: Syntax error when returning values from INNER JOIN
I am writing an SQLyog function to find the status of a client depending on the amount they have spent. The amount they have spent resides in the payment table and all the clients details reside in the clients table.

Edit: Note the function works when the output is just CustStatus, seems like the issue is to do with the inclusion of the other return values.

This is the error I am receiving:

Error Code: 1064 You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ' VARCHAR(50), VARCHAR(50), VARCHAR(10)
  DETERMINISTIC

BEGIN  DECLARE k1 INT(11' at line 2

```<code>DROP FUNCTION IF EXISTS DTC_VIP_members $$
CREATE FUNCTION DTC_VIP_members (v1 INT(11))
RETURNS INT(11), VARCHAR(50), VARCHAR(50), VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE k1 INT(11);
DECLARE CustStatus VARCHAR(10);
SELECT SUM(payment.SaleAmt) INTO k1
FROM payment
INNER JOIN clients
ON payment.client_id = clients.client_id
WHERE payment.client_id = v1;
IF k1 >= 300 THEN
    UPDATE clients
    SET clients.CustStatus = 'VIP';
ELSE
    UPDATE clients
    SET clients.CustStatus = 'Non-VIP';
END IF;
RETURN clients.client_id, clients.first_name, clients.last_name, clients.CustStatus;
END $$

DELIMITER ;
</code>```

答:
Sorry, but your approach looks wrong.

First: I advice to use STORED PROCEDURE instead FUNCTION

Second: using UPDATE statement without WHERE condition cause to update all rows in table that also seems wrong.

So we stored procedure can looks as:

```<code>DROP PROCEDURE IF EXISTS DTC_VIP_members $$
CREATE PROCEDURE DTC_VIP_members (v1 INT(11))
BEGIN
    DECLARE k1 INT(11);
    DECLARE CustStatus VARCHAR(10);

    SELECT SUM(payment.SaleAmt) INTO k1
    FROM payment
    INNER JOIN clients
    ON payment.client_id = clients.client_id
    WHERE payment.client_id = v1;

    IF k1 >= 300 THEN
        UPDATE clients
        SET clients.CustStatus = 'VIP'
        WHERE clients.client_id = v1; -- update only one record
    ELSE
        UPDATE clients
        SET clients.CustStatus = 'Non-VIP'
        WHERE clients.client_id = v1; -- update only one record
    END IF;

    -- select relevant data
    SELECT
        clients.client_id, clients.first_name, clients.last_name, clients.CustStatus
    FROM clients
    WHERE clients.client_id = v1;
END $$

DELIMITER ;
</code>```

Body:
I am writing an SQLyog function to find the status of a client depending on the amount they have spent. The amount they have spent resides in the payment table and all the clients details reside in the clients table.

Edit: Note the function works when the output is just CustStatus, seems like the issue is to do with the inclusion of the other return values.

This is the error I am receiving:

Error Code: 1064 You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ' VARCHAR(50), VARCHAR(50), VARCHAR(10)
  DETERMINISTIC

BEGIN  DECLARE k1 INT(11' at line 2

DROP FUNCTION IF EXISTS DTC_VIP_members $$
CREATE FUNCTION DTC_VIP_members (v1 INT(11))
RETURNS INT(11), VARCHAR(50), VARCHAR(50), VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE k1 INT(11);
DECLARE CustStatus VARCHAR(10);
SELECT SUM(payment.SaleAmt) INTO k1
FROM payment
INNER JOIN clients
ON payment.client_id = clients.client_id
WHERE payment.client_id = v1;
IF k1 >= 300 THEN
    UPDATE clients
    SET clients.CustStatus = 'VIP';
ELSE
    UPDATE clients
    SET clients.CustStatus = 'Non-VIP';
END IF;
RETURN clients.client_id, clients.first_name, clients.last_name, clients.CustStatus;
END $$

DELIMITER ;

Body:
Sorry, but your approach looks wrong.

First: I advice to use STORED PROCEDURE instead FUNCTION

Second: using UPDATE statement without WHERE condition cause to update all rows in table that also seems wrong.

So we stored procedure can looks as:

DROP PROCEDURE IF EXISTS DTC_VIP_members $$
CREATE PROCEDURE DTC_VIP_members (v1 INT(11))
BEGIN
    DECLARE k1 INT(11);
    DECLARE CustStatus VARCHAR(10);

    SELECT SUM(payment.SaleAmt) INTO k1
    FROM payment
    INNER JOIN clients
    ON payment.client_id = clients.client_id
    WHERE payment.client_id = v1;

    IF k1 >= 300 THEN
        UPDATE clients
        SET clients.CustStatus = 'VIP'
        WHERE clients.client_id = v1; -- update only one record
    ELSE
        UPDATE clients
        SET clients.CustStatus = 'Non-VIP'
        WHERE clients.client_id = v1; -- update only one record
    END IF;

    -- select relevant data
    SELECT
        clients.client_id, clients.first_name, clients.last_name, clients.CustStatus
    FROM clients
    WHERE clients.client_id = v1;
END $$

DELIMITER ;


问:
AWS RDS MySQL performance
I am running MySQL 8 on AWS RDS, I have an InnoDB type table with 260,000 rows inside, no extraordinary data size.

My development server features 1GB RAM, 1vCPU, and my AWS RDS server is t3.small.

SELECT Count operations take too long (average 33 seconds) and my data tables in my Laravel project time out, what could be the problem?

```<code>select count('special_cargo_id') from special_cargos
</code>```

33seconds

答:
If you're trying to debug performance of your Database, RDS has a great built in tool for that.

With RDS Performance Insights you should be able to identify where the bottleneck is.

Title: AWS RDS MySQL performance

Body:
I am running MySQL 8 on AWS RDS, I have an InnoDB type table with 260,000 rows inside, no extraordinary data size.

My development server features 1GB RAM, 1vCPU, and my AWS RDS server is t3.small.

SELECT Count operations take too long (average 33 seconds) and my data tables in my Laravel project time out, what could be the problem?

select count('special_cargo_id') from special_cargos

33seconds


问:
googletest gives either multiple main defination when libgtest_main.a is used or gives undefined reference to testing when libgtest_main.a is not used
I built googletest following the steps given in this link ->

https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/

Here is my code

```<code>  1 #include <iostream>
  2 #include <vector>
  3 #include "gtest.h"
  4 //#include <gtest.h>
  5
  6 using namespace std;
  7
  8 void expectEqual(int n1, int n2){
  9         if(n1 != n2){
 10          cerr << "Actual value is " << n1 << ", expected " << n2 <<endl;
 11         }
 12 }
 13
 14 int binarySearch(vector <int> &arr, int key){
 15
 16 int low = 0;
 17 int high = arr.size() -1 ;
 18 while(low <= high){
 19         int mid = (low + high) / 2;
 20         if(arr[mid] == key){
 21                 return mid;
 22         } else if (arr[mid] < key){
 23                 low = mid + 1;
 24         }
 25         else {
 26                 high = mid - 1;
 27         }
 28
 29         }
 58
 59 TEST(BinarySearchTest, EmptyVectorTest) {
 60         vector<int> arr;
 61         arr.push_back(5);
 62         expectEqual(binarySearch(arr, 10), -1);
 63 }
 64
 65
 66 /*int main() {
 67
 68         basicTest();
 69         smallVectorTest();
 70         emptyVectorTest();
 71         return 0;
 72 }*/
 73
 74 int main(int argc, char **argv){
 75         ::testing::InitGoogleTest(&argc, argv);
 76         return RUN_ALL_TESTS();
 77 }
 78
</code>```

This is how I compile it using a bash script ->

```<code>  1 #!/bin/bash
  2
  3 INC_DIR=/usr/include/gtest/
  4 LIB_DIR=/usr/lib/
  5
  6 #g++ -std=c++11 -isystem $INC_DIR -pthread -L$LIB_DIR -lgtest -lgtest_main binarySearch.cpp
    #gives multiple definition of `main'; error

  7 #g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest.a binarySearch.cpp
   #gives undefined reference to `testing::InitGoogleTest(int*, char**)'

  8 g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest_main.a binarySearch.cpp
   #gives multiple definition of `main'; error
</code>```

For reference, I am also pasting how LIB and Include path looks -->

```<code>storm@storm:~/cpp_ut$ ls /usr/lib/
X11                gnupg
accountsservice    gnupg2
apparmor           gold-ld
apt                groff
bfd-plugins        hdparm
binfmt.d           init
bolt               initcpio
byobu              initramfs-tools
cloud-init         kernel
cnf-update-db      klibc
command-not-found  klibc-xcgdUApi-P9SoPhW_fi5gXfvWpw.so
compat-ld          language-selector
console-setup      libDeployPkg.so.0
cpp                libDeployPkg.so.0.0.0
cryptsetup         libdmmp.so
dbus-1.0           libdmmp.so.0.2.0
dpkg               libgtest.a
dracut             libgtest_main.a
</code>```

```<code>storm@storm:~/cpp_ut$ ls /usr/include/gtest/
gtest-death-test.h  gtest-message.h     gtest-printers.h  gtest-test-part.h   gtest.h            gtest_prod.h
gtest-matchers.h    gtest-param-test.h  gtest-spi.h       gtest-typed-test.h  gtest_pred_impl.h  internal
</code>```

Every answer that I found on StackOverflow for a similar issue suggests I use either libgtest.a or libgtest_main.a. Both does not resolve my issue.

I apologize for the long question, but I wanted to include all the possible information.

答:
Turns out that it was a stupid issue that I was missing.  As suggested in comments, I should not put libraries before objects on the command line that calls the linker.

This run command in the script worked -

```<code>  1 #!/bin/bash
  2
  3 INC_DIR=/usr/include/gtest/
  4 LIB_DIR=/usr/lib/
  5
  6 #g++ -std=c++11 -isystem $INC_DIR -pthread -L$LIB_DIR -lgtest -lgtest_main binarySearch.cpp
  7 #g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest.a binarySearch.cpp
  8 g++ -std=c++11 -isystem $INC_DIR -pthread binarySearch.cpp  $LIB_DIR/libgtest.a
~
</code>```

Body:
I built googletest following the steps given in this link ->

https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/

Here is my code

  1 #include <iostream>
  2 #include <vector>
  3 #include "gtest.h"
  4 //#include <gtest.h>
  5
  6 using namespace std;
  7
  8 void expectEqual(int n1, int n2){
  9         if(n1 != n2){
 10          cerr << "Actual value is " << n1 << ", expected " << n2 <<endl;
 11         }
 12 }
 13
 14 int binarySearch(vector <int> &arr, int key){
 15
 16 int low = 0;
 17 int high = arr.size() -1 ;
 18 while(low <= high){
 19         int mid = (low + high) / 2;
 20         if(arr[mid] == key){
 21                 return mid;
 22         } else if (arr[mid] < key){
 23                 low = mid + 1;
 24         }
 25         else {
 26                 high = mid - 1;
 27         }
 28
 29         }
 58
 59 TEST(BinarySearchTest, EmptyVectorTest) {
 60         vector<int> arr;
 61         arr.push_back(5);
 62         expectEqual(binarySearch(arr, 10), -1);
 63 }
 64
 65
 66 /*int main() {
 67
 68         basicTest();
 69         smallVectorTest();
 70         emptyVectorTest();
 71         return 0;
 72 }*/
 73
 74 int main(int argc, char **argv){
 75         ::testing::InitGoogleTest(&argc, argv);
 76         return RUN_ALL_TESTS();
 77 }
 78

This is how I compile it using a bash script ->

  1 #!/bin/bash
  2
  3 INC_DIR=/usr/include/gtest/
  4 LIB_DIR=/usr/lib/
  5
  6 #g++ -std=c++11 -isystem $INC_DIR -pthread -L$LIB_DIR -lgtest -lgtest_main binarySearch.cpp
    #gives multiple definition of `main'; error

  7 #g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest.a binarySearch.cpp
   #gives undefined reference to `testing::InitGoogleTest(int*, char**)'

  8 g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest_main.a binarySearch.cpp
   #gives multiple definition of `main'; error

For reference, I am also pasting how LIB and Include path looks -->

storm@storm:~/cpp_ut$ ls /usr/lib/
X11                gnupg
accountsservice    gnupg2
apparmor           gold-ld
apt                groff
bfd-plugins        hdparm
binfmt.d           init
bolt               initcpio
byobu              initramfs-tools
cloud-init         kernel
cnf-update-db      klibc
command-not-found  klibc-xcgdUApi-P9SoPhW_fi5gXfvWpw.so
compat-ld          language-selector
console-setup      libDeployPkg.so.0
cpp                libDeployPkg.so.0.0.0
cryptsetup         libdmmp.so
dbus-1.0           libdmmp.so.0.2.0
dpkg               libgtest.a
dracut             libgtest_main.a

storm@storm:~/cpp_ut$ ls /usr/include/gtest/
gtest-death-test.h  gtest-message.h     gtest-printers.h  gtest-test-part.h   gtest.h            gtest_prod.h
gtest-matchers.h    gtest-param-test.h  gtest-spi.h       gtest-typed-test.h  gtest_pred_impl.h  internal

Every answer that I found on StackOverflow for a similar issue suggests I use either libgtest.a or libgtest_main.a. Both does not resolve my issue.

I apologize for the long question, but I wanted to include all the possible information.

Body:
Turns out that it was a stupid issue that I was missing.  As suggested in comments, I should not put libraries before objects on the command line that calls the linker.

This run command in the script worked -

  1 #!/bin/bash
  2
  3 INC_DIR=/usr/include/gtest/
  4 LIB_DIR=/usr/lib/
  5
  6 #g++ -std=c++11 -isystem $INC_DIR -pthread -L$LIB_DIR -lgtest -lgtest_main binarySearch.cpp
  7 #g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest.a binarySearch.cpp
  8 g++ -std=c++11 -isystem $INC_DIR -pthread binarySearch.cpp  $LIB_DIR/libgtest.a
~


问:
Bottom part of UISwitch is cut off on the device but displays normal on the Simulator
The UISwitch on my device:    Switch Image with the bottom pixels cut off http://gorgando.com/uiswitch.jpg

The UISwitch on the simulator:  Good UISwitch http://gorgando.com/uiswitch-good.png

As you can see, the bottom pixels are cut off on the device, but not on the simulator. I have tried just about everything I can think of, but nothing has fixed the problem.

Some of the things I've tried:

Changing the UISwitch's frame's height

Changing the UICell's height

Changing the UICell's contentView's height

Adding the UISwitch to the UICell rather than the UICell's contentView

Here is the relevant code:

This is in the viewDidLoad of the uiTableViewController:

```<code>UISwitch *sw =  [[UISwitch alloc] init];
self.contactedSwitch = sw;
[sw release];
self.contactedSwitch = [UISwitch switchWithLeftText:@"YES" andRight:@"NO"];
self.contactedSwitch.center = CGPointMake(230, 22);
self.contactedSwitch.on = [self.contact.contacted boolValue];
</code>```

This is where the switchWithLeftText:andRight method comes from:

```<code>#import "UISwitch-Extended.h"

#define TAG_OFFSET  900

@implementation UISwitch (tagged)
- (void) spelunkAndTag: (UIView *) aView withCount:(int *) count
{
    for (UIView *subview in [aView subviews])
    {
        if ([subview isKindOfClass:[UILabel class]])
        {
            *count += 1;
            [subview setTag:(TAG_OFFSET + *count)];
        }
        else
            [self spelunkAndTag:subview withCount:count];
    }
}

- (UILabel *) label1
{
    return (UILabel *) [self viewWithTag:TAG_OFFSET + 1];
}

- (UILabel *) label2
{
    return (UILabel *) [self viewWithTag:TAG_OFFSET + 2];
}

+ (UISwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2
{
    UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 94, 27)];

    int labelCount = 0;
    [switchView spelunkAndTag:switchView withCount:&labelCount];

    if (labelCount == 2)
    {
        [switchView.label1 setText:tag1];
        [switchView.label2 setText:tag2];
    }

    return [switchView autorelease];
}

@end
</code>```

This is where I add the UISwitch to my tableviewcell:

```<code>[[contactedCell contentView] addSubview:self.contactedSwitch];
</code>```

Thanks so much!

[Update] I thought the tableviewcell's might be the problem, so I added these UISwitches to a regular UIView to see how they looked. I have the exact same problem where they look alright in the simulator and the bottom is chopped in the device. So bizarre!

答:
This is caused of the UISwich's top.
You can use UISwich.origin.y = ceil((height - UISwich.size.height)/2)
to fix it.

Body:
The UISwitch on my device:    Switch Image with the bottom pixels cut off http://gorgando.com/uiswitch.jpg

The UISwitch on the simulator:  Good UISwitch http://gorgando.com/uiswitch-good.png

As you can see, the bottom pixels are cut off on the device, but not on the simulator. I have tried just about everything I can think of, but nothing has fixed the problem.

Some of the things I've tried:

Changing the UISwitch's frame's height

Changing the UICell's height

Changing the UICell's contentView's height

Adding the UISwitch to the UICell rather than the UICell's contentView

Here is the relevant code:

This is in the viewDidLoad of the uiTableViewController:

UISwitch *sw =  [[UISwitch alloc] init];
self.contactedSwitch = sw;
[sw release];
self.contactedSwitch = [UISwitch switchWithLeftText:@"YES" andRight:@"NO"];
self.contactedSwitch.center = CGPointMake(230, 22);
self.contactedSwitch.on = [self.contact.contacted boolValue];

This is where the switchWithLeftText:andRight method comes from:

#import "UISwitch-Extended.h"

#define TAG_OFFSET  900

@implementation UISwitch (tagged)
- (void) spelunkAndTag: (UIView *) aView withCount:(int *) count
{
    for (UIView *subview in [aView subviews])
    {
        if ([subview isKindOfClass:[UILabel class]])
        {
            *count += 1;
            [subview setTag:(TAG_OFFSET + *count)];
        }
        else
            [self spelunkAndTag:subview withCount:count];
    }
}

- (UILabel *) label1
{
    return (UILabel *) [self viewWithTag:TAG_OFFSET + 1];
}

- (UILabel *) label2
{
    return (UILabel *) [self viewWithTag:TAG_OFFSET + 2];
}

+ (UISwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2
{
    UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 94, 27)];

    int labelCount = 0;
    [switchView spelunkAndTag:switchView withCount:&labelCount];

    if (labelCount == 2)
    {
        [switchView.label1 setText:tag1];
        [switchView.label2 setText:tag2];
    }

    return [switchView autorelease];
}

@end

This is where I add the UISwitch to my tableviewcell:

[[contactedCell contentView] addSubview:self.contactedSwitch];

Thanks so much!

[Update] I thought the tableviewcell's might be the problem, so I added these UISwitches to a regular UIView to see how they looked. I have the exact same problem where they look alright in the simulator and the bottom is chopped in the device. So bizarre!


问:
How to make react router protected?
I am just switching from angular to react, i am creating a dynamic routes, but the problem is i don't know how to make it private below is my code.

Please help me to solve this.

```<code>const routes = [
  {
    path: "/",
    children: Dashboard,
    exact: true,
    authGuard: true,
  },
];

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <Route
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        ))}
      </Switch>
    </Router>
  );
};

const PrivateRoute = ({ children, ...rest }) => {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        sessionStorage.getItem("token") ? (
          children
        ) : (
          <Redirect to={{ pathname: "/login", state: { from: location } }} />
        )
      }
    ></Route>
  );
};

export default Routes;

</code>```

Any solution appreciated!

答:
Instead of rendering the Route component while mapping you can render the PrivateRoute which contains your logic

```<code>const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <PrivateRoute
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        ))}
      </Switch>
    </Router>
  );
};
</code>```

Since you specify authGurad as an attribute in json, you can use that to choose which Route to render.

```<code>const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => {
        const Component = route.authGuard? PrivateRoute: Route;
        return (
          <Component
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        )})}
      </Switch>
    </Router>
  );
};
</code>```

Title: How to make react router protected?

Body:
I am just switching from angular to react, i am creating a dynamic routes, but the problem is i don't know how to make it private below is my code.

Please help me to solve this.

const routes = [
  {
    path: "/",
    children: Dashboard,
    exact: true,
    authGuard: true,
  },
];

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <Route
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        ))}
      </Switch>
    </Router>
  );
};

const PrivateRoute = ({ children, ...rest }) => {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        sessionStorage.getItem("token") ? (
          children
        ) : (
          <Redirect to={{ pathname: "/login", state: { from: location } }} />
        )
      }
    ></Route>
  );
};

export default Routes;

Any solution appreciated!

Body:
Instead of rendering the Route component while mapping you can render the PrivateRoute which contains your logic

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <PrivateRoute
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        ))}
      </Switch>
    </Router>
  );
};

Since you specify authGurad as an attribute in json, you can use that to choose which Route to render.

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => {
        const Component = route.authGuard? PrivateRoute: Route;
        return (
          <Component
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        )})}
      </Switch>
    </Router>
  );
};


问:
Overlapping bars in horizontal Bar graph
I am generating horizontal bar graphs using mathplotlib from

SO: How to plot multiple horizontal bars in one chart with matplotlib. The problem is when I have more than 2 horizontal bars, the bars are getting overlapped. Not sure, what I am doing wrong.
Here is the following graph code

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

df = pandas.DataFrame(dict(graph=['q1','q2','q3' , 'q4','q5',' q6'],
                           n=[3, 5, 2,3 ,5 , 2], m=[6, 1, 3, 6 , 1 , 3]))

ind = np.arange(len(df))
width = 0.4
opacity = 0.4
fig, ax = plt.subplots()

ax.barh(ind, df.n, width, alpha=opacity, color='r', label='Existing')
ax.barh(ind + width, df.m, width, alpha=opacity,color='b', label='Community')
ax.barh(ind + 2* width, df.m, width, alpha=opacity,color='g', label='Robust')

ax.set(yticks=ind + width , yticklabels=df.graph, ylim=[2*width - 1, len(df)])
ax.legend()

#plt.xlabel('Queries')
plt.xlabel('Precesion')
plt.title('Precesion for these  queries')

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

Currently, the graph looks like this

答:
ax=df.plot.barh(width=0.85,figsize=(15,15))

adjust width(should be less than 1 otherwise overlaps) and figsize to get the best and clear view of bars. Because if the figure is bigger you can have a clear and bigger view of bars which is the ultimate goal.

Body:
I am generating horizontal bar graphs using mathplotlib from

SO: How to plot multiple horizontal bars in one chart with matplotlib. The problem is when I have more than 2 horizontal bars, the bars are getting overlapped. Not sure, what I am doing wrong.
Here is the following graph code

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

df = pandas.DataFrame(dict(graph=['q1','q2','q3' , 'q4','q5',' q6'],
                           n=[3, 5, 2,3 ,5 , 2], m=[6, 1, 3, 6 , 1 , 3]))

ind = np.arange(len(df))
width = 0.4
opacity = 0.4
fig, ax = plt.subplots()

ax.barh(ind, df.n, width, alpha=opacity, color='r', label='Existing')
ax.barh(ind + width, df.m, width, alpha=opacity,color='b', label='Community')
ax.barh(ind + 2* width, df.m, width, alpha=opacity,color='g', label='Robust')

ax.set(yticks=ind + width , yticklabels=df.graph, ylim=[2*width - 1, len(df)])
ax.legend()

#plt.xlabel('Queries')
plt.xlabel('Precesion')
plt.title('Precesion for these  queries')

plt.show()

Currently, the graph looks like this


问:
Download Image from byte stream c#
I need to save the image from the URL link and display it on UI then

I tried all the approaches I was able to google for that purpose:

```<code> PictureBox pb = new PictureBox();
 pb.Load(imageUrl);
</code>```

and

```<code>using (WebClient wc = new WebClient())
{
        byte[] bytes = wc.DownloadData(imageUrl);
        MemoryStream ms = new MemoryStream(bytes);
        Image img = Image.FromStream(ms);
}
</code>```

and more...

But unfortunately, I'm constantly getting ArgumentExceptiom "Parameter is not valid, no matter what way I use to convert byte stream to the Image

P.S. You can open the link in browser -> it is public.

UPDATE:
Issue was resolved by just removing -rw at the end of the link

答:
Your File is .WebP File, and Bitmap class doesn't support the WebP format.

A bitmap consists of the pixel data for a graphics image and its attributes. There are many standard formats for saving a bitmap to a file. GDI+ supports the following file formats: BMP, GIF, EXIF, JPG, PNG, and TIFF. For more information about supported formats, see Types of Bitmaps.

Title: Download Image from byte stream c#

Body:
I need to save the image from the URL link and display it on UI then

I tried all the approaches I was able to google for that purpose:

 PictureBox pb = new PictureBox();
 pb.Load(imageUrl);

and

using (WebClient wc = new WebClient())
{
        byte[] bytes = wc.DownloadData(imageUrl);
        MemoryStream ms = new MemoryStream(bytes);
        Image img = Image.FromStream(ms);
}

and more...

But unfortunately, I'm constantly getting ArgumentExceptiom "Parameter is not valid, no matter what way I use to convert byte stream to the Image

P.S. You can open the link in browser -> it is public.

UPDATE:
Issue was resolved by just removing -rw at the end of the link


问:
Error while loading shared libraries: /usr/local/lib64/libssl.so.1.1
I’m trying to compile openssl-1.1.0e on Centos 7 (7.3.1611)
but after i successfully compiled everything without any warning, i get an error when i’m trying any openssl command

```<code>[mdm@dev openssl-1.1.0e]$ openssl version
openssl: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory
</code>```

Is it a bug or my mistake?

Here below some info about my system/configuration

Configure:

```<code>[mdm@dev openssl-1.1.0e]$ ./Configure linux-x86_64 --prefix=/usr/local --openssldir=/usr/local
</code>```

Make/Make test:

```<code>...
All tests successful.
Files=91, Tests=486, 44 wallclock secs ( 0.47 usr  0.08 sys + 27.72 cusr 13.41 csys = 41.68 CPU)
Result: PASS
...
</code>```

Make install:

```<code>...
install libcrypto.a -> /usr/local/lib64/libcrypto.a
install libssl.a -> /usr/local/lib64/libssl.a
install libcrypto.so.1.1 -> /usr/local/lib64/libcrypto.so.1.1
link /usr/local/lib64/libcrypto.so -> /usr/local/lib64/libcrypto.so.1.1
install libssl.so.1.1 -> /usr/local/lib64/libssl.so.1.1
link /usr/local/lib64/libssl.so -> /usr/local/lib64/libssl.so.1.1
...
</code>```

But if i check with ldd two libraries are not found despite Make install did its job...

```<code>[mdm@dev openssl-1.1.0e]$ ldd /usr/local/bin/openssl
linux-vdso.so.1 =>  (0x00007fffcfe75000)
/lib/$LIB/liblsp.so => /lib/lib64/liblsp.so (0x00007fa5cd77a000)
libssl.so.1.1 => not found
libcrypto.so.1.1 => not found
libdl.so.2 => /lib64/libdl.so.2 (0x00007fa5cd55d000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fa5cd341000)
libc.so.6 => /lib64/libc.so.6 (0x00007fa5ccf7f000)
/lib64/ld-linux-x86-64.so.2 (0x00007fa5cd981000)
</code>```

I have already installed by distro a version of openssl:

```<code>[mdm@dev]$ openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

[mdm@dev]$ which openssl
/usr/bin/openssl
</code>```

yum info openssl:

```<code>...
Installed Packages
Name        : openssl
Arch        : x86_64
Epoch       : 1
Version     : 1.0.1e
Release     : 60.el7_3.1
Size        : 1.5 M
Repo        : installed
From repo   : updates
...
</code>```

Appreciate any help or suggestion!

答:
For CentOS 7+, Add the following to /etc/environment:

```<code>LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64
</code>```

Body:
I’m trying to compile openssl-1.1.0e on Centos 7 (7.3.1611)
but after i successfully compiled everything without any warning, i get an error when i’m trying any openssl command

[mdm@dev openssl-1.1.0e]$ openssl version
openssl: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory

Is it a bug or my mistake?

Here below some info about my system/configuration

Configure:

[mdm@dev openssl-1.1.0e]$ ./Configure linux-x86_64 --prefix=/usr/local --openssldir=/usr/local

Make/Make test:

...
All tests successful.
Files=91, Tests=486, 44 wallclock secs ( 0.47 usr  0.08 sys + 27.72 cusr 13.41 csys = 41.68 CPU)
Result: PASS
...

Make install:

...
install libcrypto.a -> /usr/local/lib64/libcrypto.a
install libssl.a -> /usr/local/lib64/libssl.a
install libcrypto.so.1.1 -> /usr/local/lib64/libcrypto.so.1.1
link /usr/local/lib64/libcrypto.so -> /usr/local/lib64/libcrypto.so.1.1
install libssl.so.1.1 -> /usr/local/lib64/libssl.so.1.1
link /usr/local/lib64/libssl.so -> /usr/local/lib64/libssl.so.1.1
...

But if i check with ldd two libraries are not found despite Make install did its job...

[mdm@dev openssl-1.1.0e]$ ldd /usr/local/bin/openssl
linux-vdso.so.1 =>  (0x00007fffcfe75000)
/lib/$LIB/liblsp.so => /lib/lib64/liblsp.so (0x00007fa5cd77a000)
libssl.so.1.1 => not found
libcrypto.so.1.1 => not found
libdl.so.2 => /lib64/libdl.so.2 (0x00007fa5cd55d000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fa5cd341000)
libc.so.6 => /lib64/libc.so.6 (0x00007fa5ccf7f000)
/lib64/ld-linux-x86-64.so.2 (0x00007fa5cd981000)

I have already installed by distro a version of openssl:

[mdm@dev]$ openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

[mdm@dev]$ which openssl
/usr/bin/openssl

yum info openssl:

...
Installed Packages
Name        : openssl
Arch        : x86_64
Epoch       : 1
Version     : 1.0.1e
Release     : 60.el7_3.1
Size        : 1.5 M
Repo        : installed
From repo   : updates
...

Appreciate any help or suggestion!

Body:
For CentOS 7+, Add the following to /etc/environment:

LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64


问:
use for loop in flatlist react native
I'm beginner in react native, and I want to use for loop in flatlist to push require data,

```<code>    render() {
  return (
  <View style={styles.container}>
  <FlatList
  data={[
  require("./assest/image1.jpg"),
  require("./assest/image2.jpg"),
  require("./assest/image3.jpg"),
  ]}
  renderItem={({ item }) => {
  return <ListItem image={item} />
  }}
  keyExtractor={
  (index) => {return index}
  }
  />
  </View>
  )
}
}
</code>```

Like when pushing array from state using for loop

```<code>  state ={
  a: [12 , 13 , 14 ,15 , 19 ,21 ]
b: "1"
d = () => {
let c =[];
for (var i =0; i<= this.state.a.length - 1 ; i++) {
c.push( <child text = {this.state.a[i] />);
}
return c;
};
</code>```

Is there anyway to use looping in flatlist or we can't using any looping in list or flatlist in
React Native.

答:
You can define a state (array) and then loop through your required data and push them into the array state. Then, pass that state into the data prop of the FLatlist.

You can do something like this...

```<code>import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import ListItem from '...'; //import the ListItem here

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount = () => {
    let data = [];

    const images = {
      image1: require("./assest/image1.jpg"),
      image2: require("./assest/image2.jpg"),
      image3: require("./assest/image3.jpg"),
    }

    images.forEach(image => {
      data.push(image);
      this.setState({ data })
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => {return <ListItem image={item} />}}
          keyExtractor={(index) => {return index}}
        />
      </View>
    );
  }
}
</code>```

Here, when the component mounts, it loops through the 'images' object and push them into an array called 'data' and store it to the state. Then, that state is passed to the Flatlist as a prop.

Please go through this and ask me if you have any further questions regarding this.

Title: use for loop in flatlist react native

Body:
I'm beginner in react native, and I want to use for loop in flatlist to push require data,

    render() {
  return (
  <View style={styles.container}>
  <FlatList
  data={[
  require("./assest/image1.jpg"),
  require("./assest/image2.jpg"),
  require("./assest/image3.jpg"),
  ]}
  renderItem={({ item }) => {
  return <ListItem image={item} />
  }}
  keyExtractor={
  (index) => {return index}
  }
  />
  </View>
  )
}
}

Like when pushing array from state using for loop

  state ={
  a: [12 , 13 , 14 ,15 , 19 ,21 ]
b: "1"
d = () => {
let c =[];
for (var i =0; i<= this.state.a.length - 1 ; i++) {
c.push( <child text = {this.state.a[i] />);
}
return c;
};

Is there anyway to use looping in flatlist or we can't using any looping in list or flatlist in
React Native.

Body:
You can define a state (array) and then loop through your required data and push them into the array state. Then, pass that state into the data prop of the FLatlist.

You can do something like this...

import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import ListItem from '...'; //import the ListItem here

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount = () => {
    let data = [];

    const images = {
      image1: require("./assest/image1.jpg"),
      image2: require("./assest/image2.jpg"),
      image3: require("./assest/image3.jpg"),
    }

    images.forEach(image => {
      data.push(image);
      this.setState({ data })
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => {return <ListItem image={item} />}}
          keyExtractor={(index) => {return index}}
        />
      </View>
    );
  }
}

Here, when the component mounts, it loops through the 'images' object and push them into an array called 'data' and store it to the state. Then, that state is passed to the Flatlist as a prop.

Please go through this and ask me if you have any further questions regarding this.


问:
Recursive challenge in JS combining all possible array keys in true | false versions, I attach the input and output
I have found many solutions about all posible combinations between array values but I need something different, I hope you could support me. Basically is to create all posible objects that combine array keys with true|false values, something like this:

Input: (Should return an array of 32 objects, 2exp5, two posible values in 5 keys)

```<code>let properties = ['arm','lens','season','food','size'];
</code>```

Output:

```<code>let combinations = [
  {"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
  {"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
  {"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
  {"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
  {"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
  {"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
  and so on...
]
</code>```

Thank you so much!

答:
You could use a 2D matrix with on and off switches for each property. Then create the entries for each key and create the object using Object.fromEntries()

```<code>0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
etc
</code>```

You need a total of 2 ** keys.length objects in the array. So, create that using Array.from({ 2 ** keys.length })

In the map function, create a binary number for the current row using row.toString(2)

Add the leading 0s until the string is keys.length long: ("00001")

split the string to make it an array (["0", "0", "0", "0", "1"])

map this array and create an array of entries for the corresponding key

[["arm","false"],["lens","false"],["season","false"],["food","false"],["size","false"]]

Create an object from the array of entries using Object.fromEntries()

Here's a snippet:

let keys = ['arm', 'lens', 'season', 'food', 'size'];

function combination(keys) {
  return Array.from({ length: 2 ** keys.length }, (_, row) =>
    Object.fromEntries(
      row.toString(2)
          .padStart(keys.length, 0)
          .split('')
          .map((binary, j) => [keys[j], String(Boolean(+binary))])
    )
  )
}

console.log(combination(keys))```

Body:
I have found many solutions about all posible combinations between array values but I need something different, I hope you could support me. Basically is to create all posible objects that combine array keys with true|false values, something like this:

Input: (Should return an array of 32 objects, 2exp5, two posible values in 5 keys)

let properties = ['arm','lens','season','food','size'];

Output:

let combinations = [
  {"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
  {"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
  {"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
  {"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
  {"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
  {"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
  and so on...
]

Thank you so much!

Body:
You could use a 2D matrix with on and off switches for each property. Then create the entries for each key and create the object using Object.fromEntries()

0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
etc

You need a total of 2 ** keys.length objects in the array. So, create that using Array.from({ 2 ** keys.length })

In the map function, create a binary number for the current row using row.toString(2)

Add the leading 0s until the string is keys.length long: ("00001")

split the string to make it an array (["0", "0", "0", "0", "1"])

map this array and create an array of entries for the corresponding key

[["arm","false"],["lens","false"],["season","false"],["food","false"],["size","false"]]

Create an object from the array of entries using Object.fromEntries()

Here's a snippet:

let keys = ['arm', 'lens', 'season', 'food', 'size'];

function combination(keys) {
  return Array.from({ length: 2 ** keys.length }, (_, row) =>
    Object.fromEntries(
      row.toString(2)
          .padStart(keys.length, 0)
          .split('')
          .map((binary, j) => [keys[j], String(Boolean(+binary))])
    )
  )
}

console.log(combination(keys))


问:
How to convert JSON string into integer in python?
How can I convert year and isbn into integers from this json?</p>

```<code>({
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
})
</code>```

答:
You can simply update the values with their corresponding int values</p>

```<code>data = {
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
    }

data["year"] = int(data["year"])
data["isbn"] = int(data["isbn"])

print(data)

OUT: {'title': 'The Notebook', 'author': 'Nicholas Sparks', 'year': 1996, 'isbn': 553816713}
</code>```

Body:
How can I convert year and isbn into integers from this json?

({
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
})

Body:
You can simply update the values with their corresponding int values

data = {
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
    }

data["year"] = int(data["year"])
data["isbn"] = int(data["isbn"])

print(data)

OUT: {'title': 'The Notebook', 'author': 'Nicholas Sparks', 'year': 1996, 'isbn': 553816713}