问:
Android: onDestroy not executed after calling stopSelf
I have a QtAndroid application with a service implemented using QtService. If I want to quit the service, I do it like this:

In C++:

```<code>QtAndroid::androidService().callMethod<void>("quit");
</code>```

In Java service:

```<code>public void quit() {
    stopSelf();
}
</code>```

Then there is an onDestroy function:

```<code>@Override
public void onDestroy() {
    Log.d("MyService", "Called onDestroy");
    super.onDestroy();
}
</code>```

The log message is never shown and I suppose the onDestroy function gets not called. In my application the service is not even stopped. I tried a minimal example based on this guide. With this minimal implementation the service is stopped but the onDestroy function is not called neither.

To demonstrate the problem I took the example source code and modified it like this:

server.cpp

```<code>#include <QAndroidService>
#include <QtAndroid>
#include "rep_pingpong_source.h"

class PingPong : public PingPongSource {
public slots:
    // PingPongSource interface
    void ping(const QString &msg) override {
        qDebug() << "KDAB: Message "+msg;
        emit pong(msg + " from server");
        if (msg == "Quit") {
            qDebug() << "MyService: C++ quit";
            QtAndroid::androidService().callMethod<void>("quit");
        }
    }
};

int main(int argc, char *argv[])
{
    QAndroidService app(argc, argv);

    QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica")));
    PingPong pingPongServer;
    srcNode.enableRemoting(&pingPongServer);

    return app.exec();
}
</code>```

MyService.java

```<code>// java file android/src/com/kdab/training/MyService.java
package com.kdab.training;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.qtproject.qt5.android.bindings.QtService;

public class MyService extends QtService
{
    public static void startMyService(Context ctx) {
        ctx.startService(new Intent(ctx, MyService.class));
    }

    @Override
    public void onDestroy() {
        Log.d("MyService", "Called onDestroy");
        super.onDestroy();
    }

    public void quit() {
        Log.d("MyService", "Called quit");
        stopSelf();
    }
}
</code>```

If I check the log, the Called quit message appears but the Called onDestroy never. Do you have any idea why this happens and how can I debug the behavior? Also what could be the reason that my service won't stop? How can I find out what is preventing it from quitting?

Thank you!

答:
Call stopService with intent will call onDestroy method from activity or fragment

```<code>stopService(Intent(this, MyService.class))
</code>```

Body:
I have a QtAndroid application with a service implemented using QtService. If I want to quit the service, I do it like this:

In C++:

QtAndroid::androidService().callMethod<void>("quit");

In Java service:

public void quit() {
    stopSelf();
}

Then there is an onDestroy function:

@Override
public void onDestroy() {
    Log.d("MyService", "Called onDestroy");
    super.onDestroy();
}

The log message is never shown and I suppose the onDestroy function gets not called. In my application the service is not even stopped. I tried a minimal example based on this guide. With this minimal implementation the service is stopped but the onDestroy function is not called neither.

To demonstrate the problem I took the example source code and modified it like this:

server.cpp

#include <QAndroidService>
#include <QtAndroid>
#include "rep_pingpong_source.h"

class PingPong : public PingPongSource {
public slots:
    // PingPongSource interface
    void ping(const QString &msg) override {
        qDebug() << "KDAB: Message "+msg;
        emit pong(msg + " from server");
        if (msg == "Quit") {
            qDebug() << "MyService: C++ quit";
            QtAndroid::androidService().callMethod<void>("quit");
        }
    }
};

int main(int argc, char *argv[])
{
    QAndroidService app(argc, argv);

    QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica")));
    PingPong pingPongServer;
    srcNode.enableRemoting(&pingPongServer);

    return app.exec();
}

MyService.java

// java file android/src/com/kdab/training/MyService.java
package com.kdab.training;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.qtproject.qt5.android.bindings.QtService;

public class MyService extends QtService
{
    public static void startMyService(Context ctx) {
        ctx.startService(new Intent(ctx, MyService.class));
    }

    @Override
    public void onDestroy() {
        Log.d("MyService", "Called onDestroy");
        super.onDestroy();
    }

    public void quit() {
        Log.d("MyService", "Called quit");
        stopSelf();
    }
}

If I check the log, the Called quit message appears but the Called onDestroy never. Do you have any idea why this happens and how can I debug the behavior? Also what could be the reason that my service won't stop? How can I find out what is preventing it from quitting?

Thank you!

Body:
Call stopService with intent will call onDestroy method from activity or fragment

stopService(Intent(this, MyService.class))


来源: stackexchange

问:
How to join the same table twice and assign table aliases in Codeigniter?
I'm trying to make a mail system in Codeigniter with the PyroCms.
In my mail table, I have a "recipent" row and a "sender" row which contains the user id of the sender and recipient. To retrieve usernames from the ids, I'm trying to join the table together, but it simply returns me this error:

Error Number: 1066

Not unique table/alias: 'default_users'

```<code>SELECT `default_mailsystem`.*, `default_users`.`username` AS modtager, `default_users`.`username` as afsender
FROM (`default_mailsystem`)
LEFT JOIN `default_users` ON `default_mailsystem`.`recipent` = `default_modtager`.`id`
LEFT JOIN `default_users` ON `default_mailsystem`.`sender` = `default_afsender`.`id`
ORDER BY `id` DESC
</code>```

Filename: /hsphere/local/home/brightmedia/reuseable.dk/modules/mail/models/mail_m.php

Line Number: 13

My code is as follows:

```<code>$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
    ->join('users', 'mailsystem.recipent = modtager.id', 'left')
    ->join('users', 'mailsystem.sender = afsender.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
</code>```

The funny thing is, that if I remove the last "join" operation and leave it to only join the recipient of the mail it all works out well.

答:
Use alias like this - </p>

```<code>$this->db->select('mailsystem.*, users_table_a.username AS modtager, users_table_b.username as afsender')
$this->db->join('users users_table_a', 'mailsystem.recipent = users_table_a.id', 'left');
$this->db->join('users users_table_b', 'mailsystem.sender = users_table_b.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a mail system in Codeigniter with the PyroCms.
In my mail table, I have a "recipent" row and a "sender" row which contains the user id of the sender and recipient. To retrieve usernames from the ids, I'm trying to join the table together, but it simply returns me this error:

Error Number: 1066

Not unique table/alias: 'default_users'

SELECT `default_mailsystem`.*, `default_users`.`username` AS modtager, `default_users`.`username` as afsender
FROM (`default_mailsystem`)
LEFT JOIN `default_users` ON `default_mailsystem`.`recipent` = `default_modtager`.`id`
LEFT JOIN `default_users` ON `default_mailsystem`.`sender` = `default_afsender`.`id`
ORDER BY `id` DESC

Filename: /hsphere/local/home/brightmedia/reuseable.dk/modules/mail/models/mail_m.php

Line Number: 13

My code is as follows:

$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
    ->join('users', 'mailsystem.recipent = modtager.id', 'left')
    ->join('users', 'mailsystem.sender = afsender.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();

The funny thing is, that if I remove the last "join" operation and leave it to only join the recipient of the mail it all works out well.

Body:
Use alias like this -

$this->db->select('mailsystem.*, users_table_a.username AS modtager, users_table_b.username as afsender')
$this->db->join('users users_table_a', 'mailsystem.recipent = users_table_a.id', 'left');
$this->db->join('users users_table_b', 'mailsystem.sender = users_table_b.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();


问:
How to prevent `GET /favicon.ico HTTP/1.1` from being called after GET request
I have a Python Flask web app. Whenever I visit any of the endpoints via my chrome browser, a GET request is invoked to retrieve the webpage (this is expected), but then, it appears Chrome sends a follow-up GET request for a favicon.ico to the same endpoint Chrome just hit.

For example, my app exoses the following endpoint at route / (shown below):

# General Landing Page
@app.route('/')
def index():
    return render_template("index.html", title="Home")
```

<p>When I hit this endpoint with my Google Chrome, the <code>index.html</code> page is returned just fine. But my log messages show the following:</p>

<pre class="lang-sh prettyprint-override"><code> env FLASK_APP=app/routes.py flask run --port 5001
 * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
127.0.0.1 - - [18/Feb/2020 23:15:23] "GET / HTTP/1.1" 200 -
[2020-02-18 23:15:23,647] ERROR in app: Exception on /favicon.ico [GET]
Traceback (most recent call last):
</code>```

As you can see, the / endpoint is hit and returns a status code of 200 OK, but then a subsequent call to favicon.ico errors out.  How does one handle this?

答:
The favicon.ico is the default file name for an icon used to display on the browser tabs or bookmarks.

If you want to put an icon, you can create one with the name favicon.ico and place it in the static directory of the application. And put a link tag in your html file.

```<code><link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</code>```

Follow this link for more info from flask docs.

And follow this question if you are looking for skipping this GET request

Body:
I have a Python Flask web app. Whenever I visit any of the endpoints via my chrome browser, a GET request is invoked to retrieve the webpage (this is expected), but then, it appears Chrome sends a follow-up GET request for a favicon.ico to the same endpoint Chrome just hit.

For example, my app exoses the following endpoint at route / (shown below):

# General Landing Page
@app.route('/')
def index():
    return render_template("index.html", title="Home")

When I hit this endpoint with my Google Chrome, the index.html page is returned just fine. But my log messages show the following:

 env FLASK_APP=app/routes.py flask run --port 5001
 * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
127.0.0.1 - - [18/Feb/2020 23:15:23] "GET / HTTP/1.1" 200 -
[2020-02-18 23:15:23,647] ERROR in app: Exception on /favicon.ico [GET]
Traceback (most recent call last):

As you can see, the / endpoint is hit and returns a status code of 200 OK, but then a subsequent call to favicon.ico errors out.  How does one handle this?

Body:
The favicon.ico is the default file name for an icon used to display on the browser tabs or bookmarks.

If you want to put an icon, you can create one with the name favicon.ico and place it in the static directory of the application. And put a link tag in your html file.

<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">

Follow this link for more info from flask docs.

And follow this question if you are looking for skipping this GET request


问:
how to change part of argument passed to a function in C?
I have function

Oled_logo(const unsigned char *image)

so if i pass

unsigned char giphy_0 [] = {  0x80, 0x81, 0x03, 0x07,
  0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };

e.g. -

Oled_logo(giphy_0);

it works

but i got 14 such images naming giphy_0 ,giphy_1 ... giphy_14

so i want to run these one by one to get an animation

i just want to pass arguments to Oled_logo like Oled_logo(giphy_0)  or Oled_log(giphy_1) or Oleg_logo(giphy_2) ,so instead of doing it for 14 times ,i want to call Oled_logo function in loop and change part of argument giphy_imagenumber in loop.

So instead of writing code to call Oled_logo function for 14 times ,i want a loop where i pass giphy_imagenumber to function Oled_logo and this imagenumber is replaced by loop variable ,so i have to write only few lines in a loop.
following i tried

```<code>unsigned char x[] = "giphy_0";
    volatile unsigned char y ;
    while(1)
    {
        for(int image_gif = 0 ; image_gif<=14;image_gif++)
        {

            x[6] = image_gif + 0x30;

        Oled_logo(x);

        ssd1306_UpdateScreen();
        HAL_Delay(4000);
        }
}
</code>```

No error came ,but output is some garbage

I tried with strcat ,converted loop variable to string and concatanate with giphy_ and passed to Oled_logo function
Same problem

What i am doing wrong ?

答:
{ 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 }

is different from

"giphy_0"

What you are trying to achieve seems wrong or you are missing a piece.

My guess is you want an array like { giphy_0, giphy_1, ... } and then use the index in this array.

Body:
I have function

Oled_logo(const unsigned char *image)

so if i pass

unsigned char giphy_0 [] = {  0x80, 0x81, 0x03, 0x07,
  0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };

e.g. -

Oled_logo(giphy_0);

it works

but i got 14 such images naming giphy_0 ,giphy_1 ... giphy_14

so i want to run these one by one to get an animation

i just want to pass arguments to Oled_logo like Oled_logo(giphy_0)  or Oled_log(giphy_1) or Oleg_logo(giphy_2) ,so instead of doing it for 14 times ,i want to call Oled_logo function in loop and change part of argument giphy_imagenumber in loop.

So instead of writing code to call Oled_logo function for 14 times ,i want a loop where i pass giphy_imagenumber to function Oled_logo and this imagenumber is replaced by loop variable ,so i have to write only few lines in a loop.
following i tried

unsigned char x[] = "giphy_0";
    volatile unsigned char y ;
    while(1)
    {
        for(int image_gif = 0 ; image_gif<=14;image_gif++)
        {

            x[6] = image_gif + 0x30;

        Oled_logo(x);

        ssd1306_UpdateScreen();
        HAL_Delay(4000);
        }
}

No error came ,but output is some garbage

I tried with strcat ,converted loop variable to string and concatanate with giphy_ and passed to Oled_logo function
Same problem

What i am doing wrong ?


问:
How to prevent events from acting in nested divs when using React Hooks
I have nested div elements. Outside there should be events to move and to click. I want to enable a nested element to act as a button and to prevent the event from outside to act. In the example when we click on the red part, both events are happening. How can I stop the event from the green part when we click on the red part? stopPropagation() did not do the job. I am using React and my structure is more complex than in the example. But I wanted to reduce for reasons of clarity.

I would be happy if someone can help.

#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: green;
}

#smallCircle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
  <div id="bigCircle">
    <div id="smallCircle"></div>
  </div>

  <script>
  document.getElementById("bigCircle").addEventListener("click",myBigCircle);

    document.getElementById("smallCircle").addEventListener("click",mySmallCircle);

  function myBigCircle(){
  console.log("Hello");}

    function mySmallCircle(){
  console.log("Bye");}
  </script>
</body>

</html></code>```

I think it is related to React Hooks. Here you see the example with stopPropagation not working:

```<code>import React, { useState } from 'react';

function Test() {
    let [test, setTest] = useState(false);

    return (
        <div id="wrapper"
            style={styleBigCircle}
            onMouseUp={() => {
                setTest(false);
                console.log("Hello", test)
            }
            }>

            <div id="center"
                style={styleSmallCircle}
                onClick={(e) => {
                    e.stopPropagation();
                    setTest(!test);
                    console.log("Bye", test)
                }}
            >

            </div>

        </div>

    );
}

const styleBigCircle = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: "180px",
    height: "180px",
    borderRadius: "50%",
    backgroundColor: "green"
}

const styleSmallCircle = {
    width: "40px",
    height: "40px",
    borderRadius: "50%",
    backgroundColor: "red"
}

export default Test;
</code>```

I would be happy if someone knows how to fix this.

答:
You are dealing with different events, so to prevent the child element from trigger the parent you would need to add the same event and stopPropagation() on that one instead:

```<code><div
    id="center"
    style={styleSmallCircle}
    onMouseUp={e => {
      e.stopPropagation();
    }}
    onClick={e => {
      setTest(!test);
      console.log("Bye");
    }}
/>
</code>```

Here is a fully working example:

const Test = () => {
  let [test, setTest] = React.useState(false);

  return (

 {
        console.log("Hello");
      }}
    >

 {
          e.stopPropagation();
        }}
        onClick={e => {
          console.log("Bye");
        }}
      />

  );
};

const styleBigCircle = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  width: "180px",
  height: "180px",
  borderRadius: "50%",
  backgroundColor: "green"
};

const styleSmallCircle = {
  width: "40px",
  height: "40px",
  borderRadius: "50%",
  backgroundColor: "red"
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Test />, rootElement);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

<div id="root"></div></code>```

Body:
I have nested div elements. Outside there should be events to move and to click. I want to enable a nested element to act as a button and to prevent the event from outside to act. In the example when we click on the red part, both events are happening. How can I stop the event from the green part when we click on the red part? stopPropagation() did not do the job. I am using React and my structure is more complex than in the example. But I wanted to reduce for reasons of clarity.

I would be happy if someone can help.

#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: green;
}

#smallCircle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
}

<!DOCTYPE html>

I think it is related to React Hooks. Here you see the example with stopPropagation not working:

import React, { useState } from 'react';

function Test() {
    let [test, setTest] = useState(false);

    return (

 {
                setTest(false);
                console.log("Hello", test)
            }
            }>

 {
                    e.stopPropagation();
                    setTest(!test);
                    console.log("Bye", test)
                }}
            >

    );
}

const styleBigCircle = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: "180px",
    height: "180px",
    borderRadius: "50%",
    backgroundColor: "green"
}

const styleSmallCircle = {
    width: "40px",
    height: "40px",
    borderRadius: "50%",
    backgroundColor: "red"
}

export default Test;

I would be happy if someone knows how to fix this.

Body:
You are dealing with different events, so to prevent the child element from trigger the parent you would need to add the same event and stopPropagation() on that one instead:

<div
    id="center"
    style={styleSmallCircle}
    onMouseUp={e => {
      e.stopPropagation();
    }}
    onClick={e => {
      setTest(!test);
      console.log("Bye");
    }}
/>

Here is a fully working example:

const Test = () => {
  let [test, setTest] = React.useState(false);

  return (
    <div
      id="wrapper"
      style={styleBigCircle}
      onMouseUp={() => {
        console.log("Hello");
      }}
    >
      <div
        id="center"
        style={styleSmallCircle}
        onMouseUp={e => {
          e.stopPropagation();
        }}
        onClick={e => {
          console.log("Bye");
        }}
      />
    </div>
  );
};

const styleBigCircle = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  width: "180px",
  height: "180px",
  borderRadius: "50%",
  backgroundColor: "green"
};

const styleSmallCircle = {
  width: "40px",
  height: "40px",
  borderRadius: "50%",
  backgroundColor: "red"
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Test />, rootElement);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>


问:
Is this boolean conversion correct?
I have a boolean expression that looks like this

```<code>(!B and !C) or (B and !D) or (A and !C)
</code>```

And I need to convert it so that it only has and operations. So I came up with this result

```<code>(B and C) and (!B and D) and (!A and C)
</code>```

Is this correct or am I doing something wrong? I just want to make it sure.

I also know that

```<code>A or B
</code>```

Is equilevant to

```<code>!(!A and !B)
</code>```

答: The two expressions are not equivalent. The second one is the dual of the first one. The expression is already in the minimal Sum-of-Product form.</p>

Title: Is this boolean conversion correct?

Body:
I have a boolean expression that looks like this

(!B and !C) or (B and !D) or (A and !C)

And I need to convert it so that it only has and operations. So I came up with this result

(B and C) and (!B and D) and (!A and C)

Is this correct or am I doing something wrong? I just want to make it sure.

I also know that

A or B

Is equilevant to

!(!A and !B)


问:
How to convert a Latex into formulas in Mathematica notebook, the environment is in text, not in input
I paste a latex format equations into notebook, but it can't transform into a equation.</p>

答:
Note, backslashes in a text string need to be elided (escaped) with a prior backslash.

```<code>equation = "\\[ x^n + y^n = z^n \\]";

NotebookWrite[SelectedNotebook[], ImportString[equation, "LaTeX"]]
</code>```

The output is in 'traditional form'.  To convert to Mathematica 'input form' select and Copy As > Plain Text, and paste into a new cell.

Body:
Note, backslashes in a text string need to be elided (escaped) with a prior backslash.

equation = "\\[ x^n + y^n = z^n \\]";

NotebookWrite[SelectedNotebook[], ImportString[equation, "LaTeX"]]

The output is in 'traditional form'.  To convert to Mathematica 'input form' select and Copy As > Plain Text, and paste into a new cell.


问:
The POST Method Is Not Supported For This Route. Supported methods: GET, HEAD In laravel 5.8
I'm saving my data to the user table in laravel using ajax. I create API and it's run in the post it gives a success message. But when I'm trying to save data using Ajax it gives this message

"The POST method is not supported for this route. Supported methods: GET, HEAD."

My Controller Code is

```<code>public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required',
        'phone' => 'required',
        'country' => 'required',
        'state' => 'required',
        'purpose' => 'required',
        'package' => 'required',
        'months' => 'required',
        'quantity' => 'required',
        'amount' => 'required',
        'user_status' => 'required',
    ]);
    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] =  $user->createToken('MyApp')-> accessToken;
    $success['name'] =  $user->name;
    return response()->json(['success'=>$success], $this-> successStatus);
}
</code>```

My route is

```<code>Route::post('register', 'API\UserController@register');
</code>```

Blade file code is

```<code><form id="frmAddTask" action="#" method="post" enctype="multipart/form-data" action="javascript:void(0)">
         @csrf
        <h2>Order Information</h2>
            <div class="row">

                <div class="col-md-3">

                    <div class="form-group">
                        <label class="control-label required" for="package">Package</label>
                        <select id="package" name="package" class="form-control">
                            <option value="basic" selected="selected">Basic</option>
                            <option value="regular">Regular</option>
                            <option value="infinite">Infinite</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="control-label required" for="months">Months</label>
                        <select id="months" name="months" class="form-control">
                            <option value="1" selected="">1 months</option>
                            <option value="4">4 months</option>
                            <option value="12">12 months</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="control-label required" for="quantity">Quantity</label>
                        <select id="quantity" name="quantity" class="form-control">
                            <option value="1" selected="selected">1</option>
                            <option value="2">2</option><option value="3">3</option>
                            <option value="4">4</option><option value="5">5</option>
                            <option value="6">6</option><option value="7">7</option>
                            <option value="8">8</option><option value="9">9</option>
                            <option value="10">10</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3 ">
                    <label class="control-label required" for="amount">Amount</label>
                    <div class="input-group">
                        <span class="input-group-addon">INR</span>
                        <select id="amount" name="amount" class="form-control">
                            <option value="1" selected="">2500</option>
                            <option value="4">4000</option>
                            <option value="12">7000</option>
                        </select>
                    </div>
                </div>
                </div>
            </div>
         <hr>
         <h2>Billing Information</h2>
         <div class="row">
          <div class="col-md-6 form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name" id="name">
          </div>
          <div class="col-md-6 form-group">
            <label for="email">Email:</label>
            <input type="text" class="form-control" name="email" id="email">
          </div>
          <div class="col-md-6 form-group">
            <label for="confirm">Confirm Email:</label>
            <input type="text" class="form-control" name="confirm" id="confirm">
          </div>
          <div class="col-md-6 form-group">
            <label for="phone">Phone:</label>
            <input type="text" class="form-control" name="phone" id="phone">
          </div>
          <div class="col-md-6 form-group">
            <label for="country">Country:</label>
            <input type="text" class="form-control" name="country" id="country">
          </div>
          <div class="col-md-6 form-group">
            <label for="state">State:</label>
            <input type="text" class="form-control" name="state" id="state">
          </div>
          <div class="col-md-6 form-group">
            <label for="phone">Address:</label>
            <textarea class="form-control"></textarea>
          </div>
          <div class="col-md-6 form-group">
            <label for="purpose">Purpose</label>
            <select id="purpose" name="purpose" value="" class="form-control ">
            <option>Select Purpose</option>
            <option value="parent">Parent</option>
            <option value="employmee">Employmee</option>
            </select>
          </div>
          <div class="col-md-12 form-group">
            <input id="btn-add" type="submit" value="Make Payment" class="btn-success">
          </div>
          <!--button type="submit" class="btn btn-default">Submit</button--->
         </div>
        </form>
</code>```

My ajax request is

```<code><script>
  $(document).ready(function(){
  $('#btn-add').click(function(e){
  e.preventDefault();

  $.ajaxSetup({
  headers: {

      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
  }
 });
 $('#btn-add').html('Sending..');
 /* Submit form data using ajax*/
 $.ajax({
  url: "http://localhost:8000/api/register",
  method: 'post',
  data: $('#frmAddTask').serialize(),
  success: function(response){
      $('#exampleModalCenter').modal('hide')
  }});
 });
});
</script>
</code>```

Please suggest me where I'm wrong and try to help me to solve my issue.

Thanks in advance

答:
here is your solution</p>

```<code>Route::post('/api/register', 'API\UserController@register');
</code>```

Body:
I'm saving my data to the user table in laravel using ajax. I create API and it's run in the post it gives a success message. But when I'm trying to save data using Ajax it gives this message

"The POST method is not supported for this route. Supported methods: GET, HEAD."

My Controller Code is

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required',
        'phone' => 'required',
        'country' => 'required',
        'state' => 'required',
        'purpose' => 'required',
        'package' => 'required',
        'months' => 'required',
        'quantity' => 'required',
        'amount' => 'required',
        'user_status' => 'required',
    ]);
    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] =  $user->createToken('MyApp')-> accessToken;
    $success['name'] =  $user->name;
    return response()->json(['success'=>$success], $this-> successStatus);
}

My route is

Route::post('register', 'API\UserController@register');

Blade file code is

<form id="frmAddTask" action="#" method="post" enctype="multipart/form-data" action="javascript:void(0)">
         @csrf

Order Information

                        Package
                        <select id="package" name="package" class="form-control">
                            <option value="basic" selected="selected">Basic</option>
                            <option value="regular">Regular</option>
                            <option value="infinite">Infinite</option>
                        </select>

                        Months
                        <select id="months" name="months" class="form-control">
                            <option value="1" selected="">1 months</option>
                            <option value="4">4 months</option>
                            <option value="12">12 months</option>
                        </select>

                        Quantity
                        <select id="quantity" name="quantity" class="form-control">
                            <option value="1" selected="selected">1</option>
                            <option value="2">2</option><option value="3">3</option>
                            <option value="4">4</option><option value="5">5</option>
                            <option value="6">6</option><option value="7">7</option>
                            <option value="8">8</option><option value="9">9</option>
                            <option value="10">10</option>
                        </select>

                    Amount

                        INR
                        <select id="amount" name="amount" class="form-control">
                            <option value="1" selected="">2500</option>
                            <option value="4">4000</option>
                            <option value="12">7000</option>
                        </select>

Billing Information

            Name:
            <input type="text" class="form-control" name="name" id="name">

            Email:
            <input type="text" class="form-control" name="email" id="email">

            Confirm Email:
            <input type="text" class="form-control" name="confirm" id="confirm">

            Phone:
            <input type="text" class="form-control" name="phone" id="phone">

            Country:
            <input type="text" class="form-control" name="country" id="country">

            State:
            <input type="text" class="form-control" name="state" id="state">

            Address:
            <textarea class="form-control"></textarea>

            Purpose
            <select id="purpose" name="purpose" value="" class="form-control ">
            <option>Select Purpose</option>
            <option value="parent">Parent</option>
            <option value="employmee">Employmee</option>
            </select>

            <input id="btn-add" type="submit" value="Make Payment" class="btn-success">

        </form>

My ajax request is

Please suggest me where I'm wrong and try to help me to solve my issue.

Thanks in advance

Body:
here is your solution

Route::post('/api/register', 'API\UserController@register');


问:
SMS Message not sent to Etisalat United Arab Emirates Number
I'm trying to send SMS messages to multiple numbers with different providers, I do receive the message an Etisalat Egypt phone number but do not receive it on an Etisalat UAE number.

How can I pass spam filtering for Etisalat UAE numbers on Twilio?

My code is simply:

```<code>async sendSMSBatch(content, phoneNumbers) {
    return Promise.all(_.map(phoneNumbers, (phoneNumber) => {
      return client.messages
                   .create({
                     body: content,
                     from: messagingServiceSid,
                     to: phoneNumber,
                   });
    }));
  }
</code>```

and I've enabled Advanced Opt-Out. I've even attached

```<code>To stop receiving SMS reply “b +31 [number] to 7726"

Reply STOP to unsubscribe.
</code>```

to the message itself. Is there something I'm missing?

答:
This is the recommended approach to sending SMS to United Arab Emirates.

United Arab Emirates - Guidelines
https://www.twilio.com/guidelines/ae/sms

Body:
I'm trying to send SMS messages to multiple numbers with different providers, I do receive the message an Etisalat Egypt phone number but do not receive it on an Etisalat UAE number.

How can I pass spam filtering for Etisalat UAE numbers on Twilio?

My code is simply:

async sendSMSBatch(content, phoneNumbers) {
    return Promise.all(_.map(phoneNumbers, (phoneNumber) => {
      return client.messages
                   .create({
                     body: content,
                     from: messagingServiceSid,
                     to: phoneNumber,
                   });
    }));
  }

and I've enabled Advanced Opt-Out. I've even attached

To stop receiving SMS reply “b +31 [number] to 7726"

Reply STOP to unsubscribe.

to the message itself. Is there something I'm missing?


问:
Google Places Nearby API Success 200, but returns "INVALID_REQUEST" in Laravel
I'm trying to make an iterative crawler for the Google Places API. As anyone who has used their API knows, the response only contains 20 results per page and I'm attempting to get the full list of results so I've created an loop which will execute a function if the next_page_token field is present. The most peculiar thing happens because it successfully retrieves and echos the first 20 results but fails to perform the second search, but doesn't throw any errors in Laravel. The code for this looks as follows (this is in Laravel)

```<code>public function getAllPlaces(){
        if (Auth::user()->id != '5') {
            return redirect('/userlanding')->with('error', 'Denied access');
        } else {
            $client = new Client();

            $types = 'park';

            $radius = '50000';

            $location = [

                'latitude' => '36.187740',

                'longitude' => '-92.731422'

            ];

            $keyword = '';

            $requestQuery = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={$location['latitude']},{$location['longitude']}&radius={$radius}&type={$types}{$keyword}&key=MYSUPERSECRETKEY";

            $response = $client->request('GET', $requestQuery);
            $statusCode = $response->getStatusCode();
            $body = $response->getBody()->getContents();

            $body = json_decode($body);

            $numofrecordspresent = 0;

            $data = $body->results;

            $results = collect();
            foreach($data as $result) {
                 $results->push($result;
                 $numofrecordspresent = $numofrecordspresent + 1;
                }
            }

            if(isset($body->next_page_token)) {
                $loopData = [

                    'nexttoken' => $body->next_page_token,

                    'locationData' => $location,

                    'numofrecordspresent' => $numofrecordspresent,

                    'radius' => $radius,

                    'types' => $types,

                    'keyword' => $keyword,

                    'client' => $client,

                ];

                $this->loopedPlaceSearch($loopData);
            } else {
                return view('apireturnpage')->with('numofrecordspresent', $numofrecordspresent);
            }
        }
    }

    public function loopedPlaceSearch($loopData) {
        $client = new Client();

        $location = $loopData['locationData'];
        $numofrecordspresent = $loopData['numofrecordspresent'];
        $pagetoken = $loopData['nexttoken'];
        $radius = $loopData['radius'];
        $types = $loopData['types'];
        $keyword = $loopData['keyword'];

        $requestQuery = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={$location['latitude']},{$location['longitude']}&radius={$radius}&type={$types}{$keyword}&pagetoken={$pagetoken}&key=MYSUPERSECRETKEY";

        $response = $client->request('GET', $requestQuery);
        $statusCode = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        $body = json_decode($body);

        $data = $body->results;

        $results = collect();
        foreach($data as $result) {
             $results->push($result;
             $numofrecordspresent = $numofrecordspresent + 1;
            }
        }

        if (isset($body->next_page_token)) {
            $loopData = [

                'nexttoken' => $body->next_page_token,

                'locationData' => $location,

                'numofrecordspresent' => $numofrecordspresent,

            ];

            $this->loopedPlaceSearch($loopData);
        } else {
            return view('apireturnpage')->with('numofrecordspresent', $numofrecordspresent);
        }
    }
</code>```

At the moment, to elaborate on what I said earlier, the first function which is the one called from web.php works just fine, pushing all 20 results onto the results collection, but when there is more results (i.e. the next_page_token is present), the second function gets called but returns "INVALID_REQUEST" in the body. This is extremely weird because taking the exact actual query string from the second function that gets used but fails and putting it into my URL bar returns the proper response, ruling out any typos in the API call.

Any help would be greatly appreciated, seems to be a bug and I can't figure out why it isn't working.

答:
You seem to be missing a closing parenthesis on both of your result pushes:

```<code>$results->push($result;
</code>```

I do not know if this will fix it, but it bothers me!

Body:
I'm trying to make an iterative crawler for the Google Places API. As anyone who has used their API knows, the response only contains 20 results per page and I'm attempting to get the full list of results so I've created an loop which will execute a function if the next_page_token field is present. The most peculiar thing happens because it successfully retrieves and echos the first 20 results but fails to perform the second search, but doesn't throw any errors in Laravel. The code for this looks as follows (this is in Laravel)

public function getAllPlaces(){
        if (Auth::user()->id != '5') {
            return redirect('/userlanding')->with('error', 'Denied access');
        } else {
            $client = new Client();

            $types = 'park';

            $radius = '50000';

            $location = [

                'latitude' => '36.187740',

                'longitude' => '-92.731422'

            ];

            $keyword = '';

            $requestQuery = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={$location['latitude']},{$location['longitude']}&radius={$radius}&type={$types}{$keyword}&key=MYSUPERSECRETKEY";

            $response = $client->request('GET', $requestQuery);
            $statusCode = $response->getStatusCode();
            $body = $response->getBody()->getContents();

            $body = json_decode($body);

            $numofrecordspresent = 0;

            $data = $body->results;

            $results = collect();
            foreach($data as $result) {
                 $results->push($result;
                 $numofrecordspresent = $numofrecordspresent + 1;
                }
            }

            if(isset($body->next_page_token)) {
                $loopData = [

                    'nexttoken' => $body->next_page_token,

                    'locationData' => $location,

                    'numofrecordspresent' => $numofrecordspresent,

                    'radius' => $radius,

                    'types' => $types,

                    'keyword' => $keyword,

                    'client' => $client,

                ];

                $this->loopedPlaceSearch($loopData);
            } else {
                return view('apireturnpage')->with('numofrecordspresent', $numofrecordspresent);
            }
        }
    }

    public function loopedPlaceSearch($loopData) {
        $client = new Client();

        $location = $loopData['locationData'];
        $numofrecordspresent = $loopData['numofrecordspresent'];
        $pagetoken = $loopData['nexttoken'];
        $radius = $loopData['radius'];
        $types = $loopData['types'];
        $keyword = $loopData['keyword'];

        $requestQuery = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={$location['latitude']},{$location['longitude']}&radius={$radius}&type={$types}{$keyword}&pagetoken={$pagetoken}&key=MYSUPERSECRETKEY";

        $response = $client->request('GET', $requestQuery);
        $statusCode = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        $body = json_decode($body);

        $data = $body->results;

        $results = collect();
        foreach($data as $result) {
             $results->push($result;
             $numofrecordspresent = $numofrecordspresent + 1;
            }
        }

        if (isset($body->next_page_token)) {
            $loopData = [

                'nexttoken' => $body->next_page_token,

                'locationData' => $location,

                'numofrecordspresent' => $numofrecordspresent,

            ];

            $this->loopedPlaceSearch($loopData);
        } else {
            return view('apireturnpage')->with('numofrecordspresent', $numofrecordspresent);
        }
    }

At the moment, to elaborate on what I said earlier, the first function which is the one called from web.php works just fine, pushing all 20 results onto the results collection, but when there is more results (i.e. the next_page_token is present), the second function gets called but returns "INVALID_REQUEST" in the body. This is extremely weird because taking the exact actual query string from the second function that gets used but fails and putting it into my URL bar returns the proper response, ruling out any typos in the API call.

Any help would be greatly appreciated, seems to be a bug and I can't figure out why it isn't working.

Body:
You seem to be missing a closing parenthesis on both of your result pushes:

$results->push($result;

I do not know if this will fix it, but it bothers me!


问:
Retrive data from Firebase and output in a textview
I need some help with my android Project. I try to make an Android forum ("student edition") but my lack of knowledge catch up with me.
I have the fallowing Firebase database structure:

My Forum.class looks like this:

```<code>Button post_btn,fetch;
EditText message;
DatabaseReference forum1, comments;
TextView  post_update;

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

    post_btn = findViewById(R.id.post_btn);
    message = findViewById(R.id.comment_area);
    fetch=findViewById(R.id.btnFetch);
    post_update=findViewById(R.id.tvValue);
    final String post_title = "Student " + Session.LiveSession.user.getFn() + " " + Session.LiveSession.user.getSn() + " says: ";

    forum1 = FirebaseDatabase.getInstance().getReference("_forum1_");

    post_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          ;
            Message comment = new Message( post_title,message.getText().toString());
            forum1.child(forum1.push().getKey()).setValue(comment);

        }
    });

    fetch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            forum1.child("_forum1_").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String value = dataSnapshot.getValue(String.class);
                    post_update.setText(value);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
    });

  }//end of onCreate
} //end of Class
</code>```

pst_btn is working and when a student is posting, I push the data from "message" alongside with "post_title"(witch is constructed according to user) into the Firebase.

I will like some help with my "fetch" method. I try to make a button that extracts the data from firebase into a "textview"

My question is: How can I place following inside my textview: "post_title"+"message"??

Example of desired output:

Student Willy Weiss says: ssss

Student Willy Weiss says: qqq

Student Willy Weiss says: dfsfsfsf

Can some one help me with this? I have zero knowledge about Arrays or HashMaps, so if you recommend something like this , please leave some example code so I can learn/figure out what you recommend.

Thank you so much.

答:
Try the following:

```<code> fetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                forum1.child("_forum1_").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                      for(DataSnapshot ds : dataSnapshot.getChildren()){
                        String msg = ds.child("message").getValue(String.class);
                        String value = ds.child("post_title").getValue(String.class);
                        post_update.setText(value +" "+ msg);
                     }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            }
        });
</code>```

Iterate using dataSnapshot.getChildren() and then retrieve both the message and post_title and pass them to setText()

Body:
I need some help with my android Project. I try to make an Android forum ("student edition") but my lack of knowledge catch up with me.
I have the fallowing Firebase database structure:

My Forum.class looks like this:

Button post_btn,fetch;
EditText message;
DatabaseReference forum1, comments;
TextView  post_update;

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

    post_btn = findViewById(R.id.post_btn);
    message = findViewById(R.id.comment_area);
    fetch=findViewById(R.id.btnFetch);
    post_update=findViewById(R.id.tvValue);
    final String post_title = "Student " + Session.LiveSession.user.getFn() + " " + Session.LiveSession.user.getSn() + " says: ";

    forum1 = FirebaseDatabase.getInstance().getReference("_forum1_");

    post_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          ;
            Message comment = new Message( post_title,message.getText().toString());
            forum1.child(forum1.push().getKey()).setValue(comment);

        }
    });

    fetch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            forum1.child("_forum1_").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String value = dataSnapshot.getValue(String.class);
                    post_update.setText(value);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
    });

  }//end of onCreate
} //end of Class

pst_btn is working and when a student is posting, I push the data from "message" alongside with "post_title"(witch is constructed according to user) into the Firebase.

I will like some help with my "fetch" method. I try to make a button that extracts the data from firebase into a "textview"

My question is: How can I place following inside my textview: "post_title"+"message"??

Example of desired output:

Student Willy Weiss says: ssss

Student Willy Weiss says: qqq

Student Willy Weiss says: dfsfsfsf

Can some one help me with this? I have zero knowledge about Arrays or HashMaps, so if you recommend something like this , please leave some example code so I can learn/figure out what you recommend.

Thank you so much.

Body:
Try the following:

 fetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                forum1.child("_forum1_").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                      for(DataSnapshot ds : dataSnapshot.getChildren()){
                        String msg = ds.child("message").getValue(String.class);
                        String value = ds.child("post_title").getValue(String.class);
                        post_update.setText(value +" "+ msg);
                     }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            }
        });

Iterate using dataSnapshot.getChildren() and then retrieve both the message and post_title and pass them to setText()


问:
TClientDataSet - how to 'cancel' loadfromfile?
I have a TClientDataSet that stores data in .cds format.

Let's say i did this :

```<code>clientDataSet1.loadFromFile('myclient.cds');
</code>```

After i did this, is there a way to revert the loading and put the component in the state it was BEFORE i called this method, so i can add / delete fields that are not related to the .cds file ?

I suppose i need to use 'clearData' option , but i only can do this at design time, i did not found a way to call it in run time.

答:
As you may know, SaveToFile and LoadFromFile exist mainly to support the CDS's
"Briefcase" mode of operation whereby you can work on a local copy of database records
while disconnected from the records' source database, save the changes locally
and then apply them once you reconnect to it. The saved file includes the change cache
of the CDS, so that you can do something like this:

```<code> clientDataSet1.LoadFromFile('myclient.cds');
 clientDataSet1.UndoLastChange;
</code>```

and that will revert the CDS's records to the state they were in prior to the
last change saved to the CDS before SaveToFile was called.

However, that is not quite what you asked, which seemed to me to be how to revert
the CDS to whatever state it was in prior to LoadFromFile being called, and at that
point it may have contained entirely different data.

If you want to be able to restore this prior state, you can do, provided
you take steps to save it before calling LoadFromFile.

Simplest would be

```<code>clientDataSet1.SaveToFile('myclient.prv');
clientDataSet1.loadFromFile('myclient.cds');

if ReloadPreviousVersion then
  clientDataSet1.loadFromFile('myclient.prv');
</code>```

or, if you want to avoid saving to disk

```<code>var
  PrvData : OleVariant;
[...]
  PrvData := clientDataSet1.Data;
  clientDataSet1.loadFromFile('myclient.cds');

  if ReloadPreviousVersion then
    clientDataSet1.Data := PrvData;
</code>```

(or you could save to/load from an in-memory stream).

Btw, I don't know whether you are familar with it, but CDSs have a SavePoint property which is very handy for backtracking and undoing changes; unfortunately SavePoints do not allow backtracking past operations like LoadFromFile and ApplyUpdates because these clear out the CDS's change cache.

Regarding your 'clearData' query, if you just want to clear out the CDS's data, just do

```<code>clientDataSet1.EmptyDataSet;
</code>```

Body:
I have a TClientDataSet that stores data in .cds format.

Let's say i did this :

clientDataSet1.loadFromFile('myclient.cds');

After i did this, is there a way to revert the loading and put the component in the state it was BEFORE i called this method, so i can add / delete fields that are not related to the .cds file ?

I suppose i need to use 'clearData' option , but i only can do this at design time, i did not found a way to call it in run time.

Body:
As you may know, SaveToFile and LoadFromFile exist mainly to support the CDS's
"Briefcase" mode of operation whereby you can work on a local copy of database records
while disconnected from the records' source database, save the changes locally
and then apply them once you reconnect to it. The saved file includes the change cache
of the CDS, so that you can do something like this:

 clientDataSet1.LoadFromFile('myclient.cds');
 clientDataSet1.UndoLastChange;

and that will revert the CDS's records to the state they were in prior to the
last change saved to the CDS before SaveToFile was called.

However, that is not quite what you asked, which seemed to me to be how to revert
the CDS to whatever state it was in prior to LoadFromFile being called, and at that
point it may have contained entirely different data.

If you want to be able to restore this prior state, you can do, provided
you take steps to save it before calling LoadFromFile.

Simplest would be

clientDataSet1.SaveToFile('myclient.prv');
clientDataSet1.loadFromFile('myclient.cds');

if ReloadPreviousVersion then
  clientDataSet1.loadFromFile('myclient.prv');

or, if you want to avoid saving to disk

var
  PrvData : OleVariant;
[...]
  PrvData := clientDataSet1.Data;
  clientDataSet1.loadFromFile('myclient.cds');

  if ReloadPreviousVersion then
    clientDataSet1.Data := PrvData;

(or you could save to/load from an in-memory stream).

Btw, I don't know whether you are familar with it, but CDSs have a SavePoint property which is very handy for backtracking and undoing changes; unfortunately SavePoints do not allow backtracking past operations like LoadFromFile and ApplyUpdates because these clear out the CDS's change cache.

Regarding your 'clearData' query, if you just want to clear out the CDS's data, just do

clientDataSet1.EmptyDataSet;


问:
Is there a limit on how much JSON can hold?
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON?  Like if a user types a large amount and I send it through JSON is there some sort of maximum limit?

Also can any kind of text be sent through JSON.  for example sometime I allow users to use html, will this be ok?

答:
Surely everyone's missed a trick here. The current file size limit of a json file is 18,446,744,073,709,551,616 characters or if you prefer bytes, or even 2^64 bytes if you're looking at 64 bit infrastructures at least.

For all intents, and purposes we can assume it's unlimited as you'll probably have a hard time hitting this issue...

ContentLicense: CC BY-SA 2.5


问:
How to convert list of pixel into image using python
I want to change specific pixel value in whole image.I have converted image into List using img.getdata() function.now after processing i want to convert that list into image format.please suggest me if you know any way to do so.

```<code>import cv2
import numpy as np

from PIL import Image
img = Image.open('test.jpg','r')
pix=list(img.getdata())
for i in pix:
    if i ==(254,0,0):
        print("found",i)
        pi=np.array(pix)
        pi=Image.fromarray(pi)
        cv2.imshow("img",pi)
</code>```

Error is

```<code>
Traceback (most recent call last):
  File "C:\Python38\pixels.py", line 19, in <module>
    cv2.imshow("img",pi)
TypeError: Expected Ptr<cv::UMat> for argument 'mat'

</code>```

i have tried some other way also but not able to see image.

答:
This should help:

```<code>#!/usr/bin/env python3

import numpy as np
import cv2

# Open an image
im = cv2.imread('image.png')

# Count RGB(254,0 ,0) pixels
sought = [254,0,0]
total  = np.count_nonzero(np.all(im==sought,axis=2))
print(f'Total before: {total}')

# Draw a rectangle 10x10 that colour
im[0:10,0:10] = sought

# Count pixels that colour
total  = np.count_nonzero(np.all(im==sought,axis=2))
print(f'Total after: {total}')

# Save
cv2.imwrite('result.png',im)
</code>```

Sample Output

```<code>Total before: 0
Total after: 100
</code>```

Body:
I want to change specific pixel value in whole image.I have converted image into List using img.getdata() function.now after processing i want to convert that list into image format.please suggest me if you know any way to do so.

import cv2
import numpy as np

from PIL import Image
img = Image.open('test.jpg','r')
pix=list(img.getdata())
for i in pix:
    if i ==(254,0,0):
        print("found",i)
        pi=np.array(pix)
        pi=Image.fromarray(pi)
        cv2.imshow("img",pi)

Error is

Traceback (most recent call last):
  File "C:\Python38\pixels.py", line 19, in <module>
    cv2.imshow("img",pi)
TypeError: Expected Ptr<cv::UMat> for argument 'mat'

i have tried some other way also but not able to see image.

Body:
This should help:

#!/usr/bin/env python3

import numpy as np
import cv2

# Open an image
im = cv2.imread('image.png')

# Count RGB(254,0 ,0) pixels
sought = [254,0,0]
total  = np.count_nonzero(np.all(im==sought,axis=2))
print(f'Total before: {total}')

# Draw a rectangle 10x10 that colour
im[0:10,0:10] = sought

# Count pixels that colour
total  = np.count_nonzero(np.all(im==sought,axis=2))
print(f'Total after: {total}')

# Save
cv2.imwrite('result.png',im)

Sample Output

Total before: 0
Total after: 100


问:
SessionNotCreatedException: Message: session not created from disconnected: unable to connect to renderer using Chromedriver on Linux Centos 7 Server
I am trying to use headless chrome on a Linux Centos 7 server with selenium and python. I am getting the following error when trying to activate the driver:

```<code>Traceback (most recent call last):
  File "send_notif_marktplaats.py", line 128, in <module>
    main()
  File "send_notif_marktplaats.py", line 117, in main
    driver = activate_driver()
  File "send_notif_marktplaats.py", line 42, in activate_driver
    driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver", chrome_options=optionsChrome)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from disconnected: unable to connect to renderer
  (Session info: headless chrome=80.0.3987.116)
</code>```

My versions:

Chromedriver version 80.0.3987.106

Google chrome 80.0.3987.116

Can someone help me out?

答:
This error message...

```<code>selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from disconnected: unable to connect to renderer
  (Session info: headless chrome=80.0.3987.116)
</code>```

...implies that the ChromeDriver v80.0 was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser session.

As per the discussion WebDriver 80.0.3987.16 can't open Chrome on Linux @triciac updated that, the implementation of ChromeDriver v80.0 looks for Chrome in the following order:

locations->push_back(base::FilePath("/usr/local/sbin"));

locations->push_back(base::FilePath("/usr/local/bin"));

locations->push_back(base::FilePath("/usr/sbin"));

locations->push_back(base::FilePath("/usr/bin"));

locations->push_back(base::FilePath("/sbin"));

locations->push_back(base::FilePath("/bin"));

locations->push_back(base::FilePath("/opt/google/chrome")); // last try with the default installation location.

@johnchen, confirmed that, the binary search order on Linux was accidentally changed by r708243, which was intended to make it easier to configure the name of the Chrome binary, but accidentally changed the search order as well.

ChromeDriver team have updated ChromeDriver to fix this issue through this revision / commit.

Solution

The above mentioned solution is available with:

ChromeDriver v80.0.3987.106

ChromeDriver v81.0.4044.20

Interim solution

An interim solution would be using the binary_location attribute and you can find a detailed discussion in Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Body:
I am trying to use headless chrome on a Linux Centos 7 server with selenium and python. I am getting the following error when trying to activate the driver:

Traceback (most recent call last):
  File "send_notif_marktplaats.py", line 128, in <module>
    main()
  File "send_notif_marktplaats.py", line 117, in main
    driver = activate_driver()
  File "send_notif_marktplaats.py", line 42, in activate_driver
    driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver", chrome_options=optionsChrome)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from disconnected: unable to connect to renderer
  (Session info: headless chrome=80.0.3987.116)

My versions:

Chromedriver version 80.0.3987.106

Google chrome 80.0.3987.116

Can someone help me out?

Body:
This error message...

selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from disconnected: unable to connect to renderer
  (Session info: headless chrome=80.0.3987.116)

...implies that the ChromeDriver v80.0 was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser session.

As per the discussion WebDriver 80.0.3987.16 can't open Chrome on Linux @triciac updated that, the implementation of ChromeDriver v80.0 looks for Chrome in the following order:

locations->push_back(base::FilePath("/usr/local/sbin"));

locations->push_back(base::FilePath("/usr/local/bin"));

locations->push_back(base::FilePath("/usr/sbin"));

locations->push_back(base::FilePath("/usr/bin"));

locations->push_back(base::FilePath("/sbin"));

locations->push_back(base::FilePath("/bin"));

locations->push_back(base::FilePath("/opt/google/chrome")); // last try with the default installation location.

@johnchen, confirmed that, the binary search order on Linux was accidentally changed by r708243, which was intended to make it easier to configure the name of the Chrome binary, but accidentally changed the search order as well.

ChromeDriver team have updated ChromeDriver to fix this issue through this revision / commit.

Solution

The above mentioned solution is available with:

ChromeDriver v80.0.3987.106

ChromeDriver v81.0.4044.20

Interim solution

An interim solution would be using the binary_location attribute and you can find a detailed discussion in Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed


问:
How to display a div area when page loads
Suppose i have a div id=x which reside in the middle of the page and i want when that page load content in div x to be shown instead of showing the page from top. Its like appending div id at the end of the url to go for a given div area instead this time no url and i want it when page loads

Thank You.

答:
The easiest way would be to add #x to the end of your URL:

```<code>window.location.hash = 'x';
</code>```

You could put this in a script tag at the end of your content, so that the content loads first, then the javascript is executed.

E.g.:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Hash test</title>
        <meta charset="UTF-8"/>
    </head>
    <body>
        <br/>
        ...
        <br/>
        <div id="x">test!</div>
        <script>
            window.location.hash = 'x';
        </script>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The easiest way would be to add #x to the end of your URL:

window.location.hash = 'x';

You could put this in a script tag at the end of your content, so that the content loads first, then the javascript is executed.

E.g.:

<!DOCTYPE html>
<html>
    <head>
        <title>Hash test</title>
        <meta charset="UTF-8"/>
    </head>
    <body>
        <br/>
        ...
        <br/>
        <div id="x">test!</div>
        <script>
            window.location.hash = 'x';
        </script>
    </body>
</html>


问:
how to get consol output as csv
```<code>import csv
from bs4 import BeautifulSoup
from urllib.request import urlopen
import xml.etree.ElementTree as ET
import flickrapi
import xml
api_key='xxxxxxxxxxxxxxxx'
api_secret ='xxxxxxxxxxxx'

flickr = flickrapi.FlickrAPI(api_key,secret=api_secret)
r = flickr.photos_search(advanced= '1&text=agriculture%20%20south%20africa', has_geo="1", per_page='1')
a=ET.tostring(r)
print(str(a))

with open('farms.docx', 'w',newline='') as f:
    print('a', a, file=f)
</code>```

i have this output in my python shell how can i only print the value of id in the csv file

```<code>b'<rsp stat="ok">\n<photos page="1" pages="34486" perpage="10" total="344856">\n\t<photo farm="66" id="49560152912" isfamily="0" isfriend="0" ispublic="1" owner="97099263@N03" secret="a331bfa2a0" server="65535" title="ha_2020-02-20-1600" />\n\t<photo farm="66" id="49559914451" isfamily="0" isfriend="0" ispublic="1" owner="97099263@N03" secret="02c4fd38c6" server="65535" title="wh_2020-02-20-1600" />\n\t<photo farm="66" id="49559914351" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="ffe5ddcfe1" server="65535" title="2020-01-22_13-01-20_ILCE-6500_DSC08328_DxO" />\n\t<photo farm="66" id="49559913241" isfamily="0" isfriend="0" ispublic="1" owner="150156215@N05" secret="de69ab61f1" server="65535" title="JOB-451" />\n\t<photo farm="66" id="49559417633" isfamily="0" isfriend="0" ispublic="1" owner="150156215@N05" secret="12da8bd740" server="65535" title="JOM-903" />\n\t<photo farm="66" id="49559912936" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="d7a95cf7f4" server="65535" title="2020-01-22_13-01-08_ILCE-6500_DSC08325_DxO" />\n\t<photo farm="66" id="49560151342" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="00c2f047a0" server="65535" title="2020-01-22_12-57-04_ILCE-6500_DSC08297_DxO" />\n\t<photo farm="66" id="49560151272" isfamily="0" isfriend="0" ispublic="1" owner="153308157@N06" secret="2ff11eacd7" server="65535" title="Anole" />\n\t<photo farm="66" id="49559417108" isfamily="0" isfriend="0" ispublic="1" owner="40103142@N07" secret="90732e6b57" server="65535" title="FlowingWater" />\n\t<photo farm="66" id="49559417018" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="a49159382b" server="65535" title="2020-01-22_12-58-23_ILCE-6500_DSC08308_DxO" />\n</photos>\n</rsp>'
</code>```

答:
It should be pretty simple, so try modifying your code along these lines:

```<code>my_str = """
<rsp stat="ok">\n<photos page="1" pages="349322" perpage="1" total="349322">\n\t<photo farm="66" id="49556518667" isfamily="0" isfriend="0" ispublic="1" owner="36925516@N05" secret="25b43dbf77" server="65535" title="Petra Royal Tombs" />\n</photos>\n</rsp>
"""

target = etree.fromstring(my_str)
target.xpath('//@id')
</code>```

Output:

['49556518667']

Title: how to get consol output as csv

Body:
import csv
from bs4 import BeautifulSoup
from urllib.request import urlopen
import xml.etree.ElementTree as ET
import flickrapi
import xml
api_key='xxxxxxxxxxxxxxxx'
api_secret ='xxxxxxxxxxxx'

flickr = flickrapi.FlickrAPI(api_key,secret=api_secret)
r = flickr.photos_search(advanced= '1&text=agriculture%20%20south%20africa', has_geo="1", per_page='1')
a=ET.tostring(r)
print(str(a))

with open('farms.docx', 'w',newline='') as f:
    print('a', a, file=f)

i have this output in my python shell how can i only print the value of id in the csv file

b'<rsp stat="ok">\n<photos page="1" pages="34486" perpage="10" total="344856">\n\t<photo farm="66" id="49560152912" isfamily="0" isfriend="0" ispublic="1" owner="97099263@N03" secret="a331bfa2a0" server="65535" title="ha_2020-02-20-1600" />\n\t<photo farm="66" id="49559914451" isfamily="0" isfriend="0" ispublic="1" owner="97099263@N03" secret="02c4fd38c6" server="65535" title="wh_2020-02-20-1600" />\n\t<photo farm="66" id="49559914351" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="ffe5ddcfe1" server="65535" title="2020-01-22_13-01-20_ILCE-6500_DSC08328_DxO" />\n\t<photo farm="66" id="49559913241" isfamily="0" isfriend="0" ispublic="1" owner="150156215@N05" secret="de69ab61f1" server="65535" title="JOB-451" />\n\t<photo farm="66" id="49559417633" isfamily="0" isfriend="0" ispublic="1" owner="150156215@N05" secret="12da8bd740" server="65535" title="JOM-903" />\n\t<photo farm="66" id="49559912936" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="d7a95cf7f4" server="65535" title="2020-01-22_13-01-08_ILCE-6500_DSC08325_DxO" />\n\t<photo farm="66" id="49560151342" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="00c2f047a0" server="65535" title="2020-01-22_12-57-04_ILCE-6500_DSC08297_DxO" />\n\t<photo farm="66" id="49560151272" isfamily="0" isfriend="0" ispublic="1" owner="153308157@N06" secret="2ff11eacd7" server="65535" title="Anole" />\n\t<photo farm="66" id="49559417108" isfamily="0" isfriend="0" ispublic="1" owner="40103142@N07" secret="90732e6b57" server="65535" title="FlowingWater" />\n\t<photo farm="66" id="49559417018" isfamily="0" isfriend="0" ispublic="1" owner="69506664@N06" secret="a49159382b" server="65535" title="2020-01-22_12-58-23_ILCE-6500_DSC08308_DxO" />\n</photos>\n</rsp>'

Body:
It should be pretty simple, so try modifying your code along these lines:

my_str = """
<rsp stat="ok">\n<photos page="1" pages="349322" perpage="1" total="349322">\n\t<photo farm="66" id="49556518667" isfamily="0" isfriend="0" ispublic="1" owner="36925516@N05" secret="25b43dbf77" server="65535" title="Petra Royal Tombs" />\n</photos>\n</rsp>
"""

target = etree.fromstring(my_str)
target.xpath('//@id')

Output:

['49556518667']


问:
Django/PostgreSQL manage.py flush error. look at output of 'django-admin sqlflush'
Build: Heroku Python server, Postgresql 10.4, Django 2, wagtail 2.1

I'm trying to essentially destroy and recreate my app DB on Heroku. Here are the steps I've followed:

create db dump (success)

rm all migrations and recreated the 'initial' migrations (success)

run `heroku pg:reset DATABASE` (success)

push new migrations and db dump (success)

run `heroku run python manage.py migrate` (success)

run `heroku run python manage.py flush` (**failed**)

```<code>JVsquad$ heroku run python manage.py flush
Running python manage.py flush on ⬢ my_app... up, run.2459 (Hobby)
You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the 'my_app_db' database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: yes
CommandError: Database my_app_db couldn't be flushed. Possible
reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run.
</code>```

My 7th step was going to be heroku run python manage.py loaddata db_dump.json but it also failed, because the flush won't work.

HELP PLEASE

答:
I had the same issue after moving from Mysql to PostgresQL.

The issue with TRUNCATE tablename CASCADE was that I couldn't set the allow_cascade=True in the flush method (that is run after each test case method)

I override the Transaction class used in my tests: APITransactionTestCase

```<code>class PostgresTestCase(APITransactionTestCase):
"""
Override APITransactionTestCase class so the TRUNCATE table_name CASCADE is enabled

"""
def _fixture_teardown(self):

    # Allow TRUNCATE ... CASCADE and dont emit the post_migrate signal
    # when flushing only a subset of the apps
    for db_name in self._databases_names(include_mirrors=False):
        # Flush the database
        inhibit_post_migrate = (
                self.available_apps is not None or
                (  # Inhibit the post_migrate signal when using serialized
                    # rollback to avoid trying to recreate the serialized data.
                        self.serialized_rollback and
                        hasattr(connections[db_name], '_test_serialized_contents')
                )
        )
        call_command('flush', verbosity=3, interactive=False,
                     database=db_name, reset_sequences=False,
                     allow_cascade=True,
                     inhibit_post_migrate=True)
</code>```

Now the flush works in Postgres too.

Body:
Build: Heroku Python server, Postgresql 10.4, Django 2, wagtail 2.1

I'm trying to essentially destroy and recreate my app DB on Heroku. Here are the steps I've followed:

create db dump (success)

rm all migrations and recreated the 'initial' migrations (success)

run `heroku pg:reset DATABASE` (success)

push new migrations and db dump (success)

run `heroku run python manage.py migrate` (success)

run `heroku run python manage.py flush` (**failed**)

JVsquad$ heroku run python manage.py flush
Running python manage.py flush on ⬢ my_app... up, run.2459 (Hobby)
You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the 'my_app_db' database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: yes
CommandError: Database my_app_db couldn't be flushed. Possible
reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run.

My 7th step was going to be heroku run python manage.py loaddata db_dump.json but it also failed, because the flush won't work.

HELP PLEASE

Body:
I had the same issue after moving from Mysql to PostgresQL.

The issue with TRUNCATE tablename CASCADE was that I couldn't set the allow_cascade=True in the flush method (that is run after each test case method)

I override the Transaction class used in my tests: APITransactionTestCase

class PostgresTestCase(APITransactionTestCase):
"""
Override APITransactionTestCase class so the TRUNCATE table_name CASCADE is enabled

"""
def _fixture_teardown(self):

    # Allow TRUNCATE ... CASCADE and dont emit the post_migrate signal
    # when flushing only a subset of the apps
    for db_name in self._databases_names(include_mirrors=False):
        # Flush the database
        inhibit_post_migrate = (
                self.available_apps is not None or
                (  # Inhibit the post_migrate signal when using serialized
                    # rollback to avoid trying to recreate the serialized data.
                        self.serialized_rollback and
                        hasattr(connections[db_name], '_test_serialized_contents')
                )
        )
        call_command('flush', verbosity=3, interactive=False,
                     database=db_name, reset_sequences=False,
                     allow_cascade=True,
                     inhibit_post_migrate=True)

Now the flush works in Postgres too.


问:
Set videoview position in constraint layout
main_acitivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
    <!--suppress ALL -->
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:id="@+id/main"
        tools:context=".MainActivity"
        android:layout_gravity="center"
        android:gravity="center">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Then in java I do the next

```<code>vv = (VideoView) findViewById(R.id.videoView1);

ConstraintLayout.LayoutParams pararams = (ConstraintLayout.LayoutParams) vv.getLayoutParams();
int ch=vv.getHeight();
pararams.height = vv.getWidth();

vv.setLayoutParams(pararams);
</code>```

HOW TO MAKE ELEMENT VERTICALLY CENTERED AFTER THAT? I did vv.setY, I did margins, I tried do stuff with xml - nothing work, video either in the top or stretched through all window

Currently :

I need :

答:
Use this code</p>

```<code><?xml version="1.0" encoding="utf-8"?>

    <!--suppress ALL -->
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:id="@+id/main"
    tools:context=".MainActivity"
    android:layout_gravity="center"
    android:gravity="center"
   android:background="#000000">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
    </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
main_acitivity.xml

<?xml version="1.0" encoding="utf-8"?>

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:id="@+id/main"
        tools:context=".MainActivity"
        android:layout_gravity="center"
        android:gravity="center">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

Then in java I do the next

vv = (VideoView) findViewById(R.id.videoView1);

ConstraintLayout.LayoutParams pararams = (ConstraintLayout.LayoutParams) vv.getLayoutParams();
int ch=vv.getHeight();
pararams.height = vv.getWidth();

vv.setLayoutParams(pararams);

HOW TO MAKE ELEMENT VERTICALLY CENTERED AFTER THAT? I did vv.setY, I did margins, I tried do stuff with xml - nothing work, video either in the top or stretched through all window

Currently :

I need :

Body:
Use this code

<?xml version="1.0" encoding="utf-8"?>

    <!--suppress ALL -->
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:id="@+id/main"
    tools:context=".MainActivity"
    android:layout_gravity="center"
    android:gravity="center"
   android:background="#000000">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
    </androidx.constraintlayout.widget.ConstraintLayout>


问:
change UIAlertcontroller background Color
Ok so I have this alert that I am using and I want the background of it to be black not grey like it is. I have managed to change the colour of the text for the title and the message but not the background colour. Well to the desired colour I want. I have changed it to green blue and white, but not black. When I try to change it to black it turns grey. Any suggestions will help and be appreciated. I tried this here How to change the background color of the UIAlertController? and that is how I got to where I am now.

Here is what I have going now:

```<code>func showAlert(title:String, message:String) {

    //Set up for the title color
    let attributedString = NSAttributedString(string: title, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])
    //Set up for the Message Color
    let attributedString2 = NSAttributedString(string: message, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])

    let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert)

    alert.setValue(attributedString, forKey: "attributedTitle")
    alert.setValue(attributedString2, forKey: "attributedMessage")
    //alert.view.tintColor = UIColor.whiteColor()
    let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
        alert.addAction(dismissAction)
    self.presentViewController(alert, animated: true, completion: nil)
    //set the color of the Alert
    let subview = alert.view.subviews.first! as UIView
    let alertContentView = subview.subviews.first! as UIView
    alertContentView.backgroundColor = UIColor.blackColor()
    //alertContentView.backgroundColor = UIColor.greenColor()
    //Changes is to a grey color :(
    /*
    alertContentView.backgroundColor = UIColor(
        red: 0,
        green: 0,
        blue: 0,
        alpha: 1.0)
    //Also another Grey Color Not batman black
    */

    //alertContentView.backgroundColor = UIColor.blueColor()
    //turns into a purple

}
</code>```

答:
let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
    subview.layer.cornerRadius = 1
    subview.backgroundColor = UIColor.white</p>

Body:
Ok so I have this alert that I am using and I want the background of it to be black not grey like it is. I have managed to change the colour of the text for the title and the message but not the background colour. Well to the desired colour I want. I have changed it to green blue and white, but not black. When I try to change it to black it turns grey. Any suggestions will help and be appreciated. I tried this here How to change the background color of the UIAlertController? and that is how I got to where I am now.

Here is what I have going now:

func showAlert(title:String, message:String) {

    //Set up for the title color
    let attributedString = NSAttributedString(string: title, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])
    //Set up for the Message Color
    let attributedString2 = NSAttributedString(string: message, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])

    let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert)

    alert.setValue(attributedString, forKey: "attributedTitle")
    alert.setValue(attributedString2, forKey: "attributedMessage")
    //alert.view.tintColor = UIColor.whiteColor()
    let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
        alert.addAction(dismissAction)
    self.presentViewController(alert, animated: true, completion: nil)
    //set the color of the Alert
    let subview = alert.view.subviews.first! as UIView
    let alertContentView = subview.subviews.first! as UIView
    alertContentView.backgroundColor = UIColor.blackColor()
    //alertContentView.backgroundColor = UIColor.greenColor()
    //Changes is to a grey color :(
    /*
    alertContentView.backgroundColor = UIColor(
        red: 0,
        green: 0,
        blue: 0,
        alpha: 1.0)
    //Also another Grey Color Not batman black
    */

    //alertContentView.backgroundColor = UIColor.blueColor()
    //turns into a purple

}


问:
Python - IndexError: list index out of range while running python code
Please I need assistance with this code. I keep getting the error message above on line 5 and 35 of the code shown below. What is wrong?</p>

```<code>output = sys.argv[1]
main()
</code>```

答:
you need to pass argument by running file name like below

```<code>python file_name arg1
</code>```

then only it will work

Body:
Please I need assistance with this code. I keep getting the error message above on line 5 and 35 of the code shown below. What is wrong?

output = sys.argv[1]
main()

Body:
you need to pass argument by running file name like below

python file_name arg1

then only it will work


问:
How to make an object move in increments
I'm stuck at how to write code to make an object move in increments to the desired amount and not just jump straight to the end goal.

e.g.

Move an object from 1 - 500 (x,y, coordinates [0,1] to [0,500]) by going 1, 2, 3, 4, 5........
and not 1 to 500 in one movement?

```<code>      else if(direction == 'D'){
         xInc = 0;
         yInc = 1;
         this.setXPos(this.xPos +(distance * xInc));
         this.setYPos(this.yPos +(distance * yInc));
         this.alignAll();
         this.delay(20);
      }

   }
</code>```

Here is my full code I have so far any help would be greatly appreciated TIA.

答:
you can add a loop between your assignment something like : </p>

```<code>  if(direction == 'R'){
  xInc = 1;
  yInc = 0;
  for(int index= 0; index <= distance;index ++){
    this.setXPos(this.xPos +(xInc));
    this.setYPos(this.yPos +(yInc));
    this.alignAll();
    this.delay(20);
  }

}
</code>```

<p>I also strongly recommend you to externalize this function, since it will be almost the same depending on your direction. </p>

Body:
I'm stuck at how to write code to make an object move in increments to the desired amount and not just jump straight to the end goal.

e.g.

Move an object from 1 - 500 (x,y, coordinates [0,1] to [0,500]) by going 1, 2, 3, 4, 5........
and not 1 to 500 in one movement?

      else if(direction == 'D'){
         xInc = 0;
         yInc = 1;
         this.setXPos(this.xPos +(distance * xInc));
         this.setYPos(this.yPos +(distance * yInc));
         this.alignAll();
         this.delay(20);
      }

   }

Here is my full code I have so far any help would be greatly appreciated TIA.

Body:
you can add a loop between your assignment something like :

  if(direction == 'R'){
  xInc = 1;
  yInc = 0;
  for(int index= 0; index <= distance;index ++){
    this.setXPos(this.xPos +(xInc));
    this.setYPos(this.yPos +(yInc));
    this.alignAll();
    this.delay(20);
  }

}

I also strongly recommend you to externalize this function, since it will be almost the same depending on your direction.


问:
Convert to Date Time Format "2020-02-11T17:26:31-05:00"
Hi I am not able to understand what time format we need to use  in order to parse this date2020-02-11T17:26:31-05:00  I have tried using Date formatter and simple date format but its not working

Date is coming in this form ->2020-02-11T17:26:31-05:00 I am not able to identify the type of this date

Below is snippet of code i have tried but its throwing exception

```<code>DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
                              Locale.ENGLISH);
                     responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);
</code>```

答:
Notice that your date string has an offset -05:00 in it. Thus, your string does not represent a LocalDateTime, but an OffsetDateTime, and should be parsed by OffsetDateTime.parse (not everything is a LocalDateTime!):

```<code>// the format is ISO 8601, so it can be parsed directly without a DateTimeFormatter
OffsetDateTime odt = OffsetDateTime.parse("2020-02-11T17:26:31-05:00");
</code>```

If you only want the local date time part of it, then you can call toLocalDateTime afterwards:

```<code>LocalDateTime ldt = odt.toLocalDateTime();
</code>```

Body:
Hi I am not able to understand what time format we need to use  in order to parse this date2020-02-11T17:26:31-05:00  I have tried using Date formatter and simple date format but its not working

Date is coming in this form ->2020-02-11T17:26:31-05:00 I am not able to identify the type of this date

Below is snippet of code i have tried but its throwing exception

DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
                              Locale.ENGLISH);
                     responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);

Body:
Notice that your date string has an offset -05:00 in it. Thus, your string does not represent a LocalDateTime, but an OffsetDateTime, and should be parsed by OffsetDateTime.parse (not everything is a LocalDateTime!):

// the format is ISO 8601, so it can be parsed directly without a DateTimeFormatter
OffsetDateTime odt = OffsetDateTime.parse("2020-02-11T17:26:31-05:00");

If you only want the local date time part of it, then you can call toLocalDateTime afterwards:

LocalDateTime ldt = odt.toLocalDateTime();


问:
Mention multiple path based on existence in Linux
I have two different servers - core and bpm. I will be writing common script. In this case the path just varies on the name of the server as,

In Core server --> /apps/core/SharedLib/
and

In BPM server --> /apps/bpm/SharedLib/

So i have to mention path in same line and the server should decide based on the paths existence.

So i need something like,

```<code>cd /apps/<core|bpm>/SharedLib/
</code>```

How to mention it in correct way?

答:
if hostname command returns the server names as it appears in your dir structure, you could also do

```<code>cd /apps/$(hostname)/SharedLib/
</code>```

Otherwise you could also simply have a variable with the actual host name in your script and use the variable in your cd command :

```<code>cd /apps/$your_var/SharedLib/
</code>```

Body:
I have two different servers - core and bpm. I will be writing common script. In this case the path just varies on the name of the server as,

In Core server --> /apps/core/SharedLib/
and

In BPM server --> /apps/bpm/SharedLib/

So i have to mention path in same line and the server should decide based on the paths existence.

So i need something like,

cd /apps/<core|bpm>/SharedLib/

How to mention it in correct way?

Body:
if hostname command returns the server names as it appears in your dir structure, you could also do

cd /apps/$(hostname)/SharedLib/

Otherwise you could also simply have a variable with the actual host name in your script and use the variable in your cd command :

cd /apps/$your_var/SharedLib/


问:
sql server 2005 'update from' query
I'm trying to update a table based upon the user id from another table.  I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do.  When i run it i get 0 rows affected.

```<code>    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid
</code>```

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work.  However I'd be interested if a where is better than a from in this instance for optimisations.

答:
You don't seem to be establishing any relationship between the table "jared_test" and the two tables that you are selecting by, "new_user/nuj" and "users/us".

Did you mean this?

```<code>update nuj
set user_count  = 1
from new_user nuj
inner join (select us.userID
            from users us
            where us.email = 'j@j.co.uk') u on nuj.userid = u.userid
</code>```

(if so, a standard update as @Devan suggested would make more sense)

Title: sql server 2005 'update from' query

Body:
I'm trying to update a table based upon the user id from another table.  I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do.  When i run it i get 0 rows affected.

    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work.  However I'd be interested if a where is better than a from in this instance for optimisations.

Body:
You don't seem to be establishing any relationship between the table "jared_test" and the two tables that you are selecting by, "new_user/nuj" and "users/us".

Did you mean this?

update nuj
set user_count  = 1
from new_user nuj
inner join (select us.userID
            from users us
            where us.email = 'j@j.co.uk') u on nuj.userid = u.userid

(if so, a standard update as @Devan suggested would make more sense)