问:
iOS – Handle OTP (one-time code) in Swift
Is there any way to handle onetime-code tap by restricting other keyboard entries?

I have requirement for an OTP text field to prefill the sms OTP code.
User should not enter the OTP manually using keyboard numeric buttons.

IOS 12 we have the onetime-code option, it will be auto-filled in QuickType bar  & User can tap on it to fill the text field.  I Couldn't find an option to restrict other keyboard entries.

Is there any way we can allow only  Onetime code tap and restricting any entry from the numeric keyboard .

What I have tried is created 6 textfields.
First textfield content type set as One Time code.
UserInteractionEnabled only for the first text field so that user can't enter data onto other fields.
Once I get the OTP & taps QuickType bar - onetime code, I am prefilling all the text fields.

viewdidload>

```<code>otp1TB.addTarget(self, action:#selector(textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {
    if let otpCode = textField.text ,  otpCode.count > 5 {
        otp1TB.text = String(otpCode[otpCode.startIndex])
        otp2TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 1)])
        otp3TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 2)])
        otp4TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 3)])
        otp5TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 4)])
        otp6TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 5)])
        otp1TB.isUserInteractionEnabled = false
        self.view.endEditing(true)
    }
}
</code>```

The issue here is since the first text field is active when the keyboard opens user has the ability to enter numeric data from the keyboard.

I need to allow only onetime code tap when the keyboard opens.

答:
You can try My 3rd party library:-
https://github.com/Datt1994/DPOTPView

For Solution:-

In viewDidLoad add tag & delegate to all textfield

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    otp1TB.delegate = self
    otp1TB.tag = 1000
    otp2TB.delegate = self
    otp2TB.tag = 2000
    otp3TB.delegate = self
    otp3TB.tag = 3000
    otp4TB.delegate = self
    otp4TB.tag = 4000
    otp5TB.delegate = self
    otp5TB.tag = 5000
    otp6TB.delegate = self
    otp6TB.tag = 6000
}
</code>```

In UITextFieldDelegate extension implement shouldChangeCharactersIn function like below, It will also work with textField.textContentType = .oneTimeCode

```<code>extension ViewController : UITextFieldDelegate  {

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.trimmingCharacters(in: CharacterSet.whitespaces).count != 0 {
        textField.text = string
        if textField.tag < count*1000 {
            let next = textField.superview?.viewWithTag((textField.tag/1000 + 1)*1000)
            next?.becomeFirstResponder()
        } else if textField.tag == count*1000 {
            textField.resignFirstResponder()
        }
    } else if string.count == 0 { // is backspace
        textField.text = ""
    }

    return false
}

}
</code>```

Body:
Is there any way to handle onetime-code tap by restricting other keyboard entries?

I have requirement for an OTP text field to prefill the sms OTP code.
User should not enter the OTP manually using keyboard numeric buttons.

IOS 12 we have the onetime-code option, it will be auto-filled in QuickType bar  & User can tap on it to fill the text field.  I Couldn't find an option to restrict other keyboard entries.

Is there any way we can allow only  Onetime code tap and restricting any entry from the numeric keyboard .

What I have tried is created 6 textfields.
First textfield content type set as One Time code.
UserInteractionEnabled only for the first text field so that user can't enter data onto other fields.
Once I get the OTP & taps QuickType bar - onetime code, I am prefilling all the text fields.

viewdidload>

otp1TB.addTarget(self, action:#selector(textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {
    if let otpCode = textField.text ,  otpCode.count > 5 {
        otp1TB.text = String(otpCode[otpCode.startIndex])
        otp2TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 1)])
        otp3TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 2)])
        otp4TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 3)])
        otp5TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 4)])
        otp6TB.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 5)])
        otp1TB.isUserInteractionEnabled = false
        self.view.endEditing(true)
    }
}

The issue here is since the first text field is active when the keyboard opens user has the ability to enter numeric data from the keyboard.

I need to allow only onetime code tap when the keyboard opens.

Body:
You can try My 3rd party library:-
https://github.com/Datt1994/DPOTPView

For Solution:-

In viewDidLoad add tag & delegate to all textfield

override func viewDidLoad() {
    super.viewDidLoad()
    otp1TB.delegate = self
    otp1TB.tag = 1000
    otp2TB.delegate = self
    otp2TB.tag = 2000
    otp3TB.delegate = self
    otp3TB.tag = 3000
    otp4TB.delegate = self
    otp4TB.tag = 4000
    otp5TB.delegate = self
    otp5TB.tag = 5000
    otp6TB.delegate = self
    otp6TB.tag = 6000
}

In UITextFieldDelegate extension implement shouldChangeCharactersIn function like below, It will also work with textField.textContentType = .oneTimeCode

extension ViewController : UITextFieldDelegate  {

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.trimmingCharacters(in: CharacterSet.whitespaces).count != 0 {
        textField.text = string
        if textField.tag < count*1000 {
            let next = textField.superview?.viewWithTag((textField.tag/1000 + 1)*1000)
            next?.becomeFirstResponder()
        } else if textField.tag == count*1000 {
            textField.resignFirstResponder()
        }
    } else if string.count == 0 { // is backspace
        textField.text = ""
    }

    return false
}

}


来源: stackexchange

问:
why does a file written using writfFileSync method is corrupted for a video file in nodejs
I am uploading a video file to my s3 bucket using a presigned URL using the following code

```<code>function postsignedURL(req) {
   return new Promise(function (resolve, reject) {
       const params = {
          Bucket: 'bucket1',
          Expires: 60 * 60, // in seconds,
          Fields: {
             key: req,
             'Content-Type': 'video/'
          },
         Conditions: [
            ['content-length-range', 300, 4000e+7],
            { 'Content-Type': 'video/' },
            ["starts-with", "$Content-Type", "video/"]

        ]
    }
    s3.createPresignedPost(params, (err, data) => {
        if (err) {
            reject(err)
        } else {
            resolve(data);
        }
    })
})

}
</code>```

I am able to upload the file correctly and I can even download it using the following code in

```<code> const video = await readObjectSignedUrl(key)
 console.log(video, " video ");
</code>```

This one returns a presigned url. I can download the video using fetch method below

```<code> const objectResult = await fetchS3Object(video);
 const bufferType = Buffer.from(objectResult);
 const fileTypeResult = await fileType.fromBuffer(bufferTy[e);
 console.log(fileTypeResult )
</code>```

The result of fileTypeResult is the following which is correct

```<code>{ ext: 'mov', mime: 'video/quicktime' }
</code>```

The code for the fetchS3Object is the following

```<code>async function fetchS3Object(key) {
   console.log(key," KEY ")
   const result = await fetch(key, {
       method: 'GET',
       mode: "cors",
       headers: {
         'Access-Control-Allow-Origin': '*',
       }
   })
   const response = await result.text()
   return response
}
</code>```

When i print the objectResult variable it is some gibberish.
I am trying to write the objectResult to file using writeFileSync method.

```<code>fs.writeFileSync('/tmp/file', objectResult);
</code>```

The file is written correctly in the specified location, but the video file is corrupted. When I try to play it, it is not working.

Is there is a reason why the written file is corrupted

答:
I have Managed to solve the problem. Here is the issue. The problem arise from the fact that the original uploaded file which is a video had an encoding of

```<code>windows-1252,
</code>```

However the fetch method return a binary which is encoded with

```<code>UTF-8.
</code>```

As a result when you try to use writeFileSync the output is a corrupted file.
To solve this problem this what has to be done. The fetchS3Object function has to be changed to the following

```<code>async function fetchS3Object(key) {
   console.log(key," KEY ")
   const result = await fetch(key, {
      method: 'GET',
      mode: "cors",
      headers: {
          'Access-Control-Allow-Origin': '*',
      }
   })
   const response = await result.arrayBuffer();
   return response
}
</code>```

then

```<code> const objectResult = await fetchS3Object(video);
 const bufferType = Buffer.from(objectResult);
 fs.writeFileSync('/tmp/file', bufferType);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am uploading a video file to my s3 bucket using a presigned URL using the following code

function postsignedURL(req) {
   return new Promise(function (resolve, reject) {
       const params = {
          Bucket: 'bucket1',
          Expires: 60 * 60, // in seconds,
          Fields: {
             key: req,
             'Content-Type': 'video/'
          },
         Conditions: [
            ['content-length-range', 300, 4000e+7],
            { 'Content-Type': 'video/' },
            ["starts-with", "$Content-Type", "video/"]

        ]
    }
    s3.createPresignedPost(params, (err, data) => {
        if (err) {
            reject(err)
        } else {
            resolve(data);
        }
    })
})

}

I am able to upload the file correctly and I can even download it using the following code in

 const video = await readObjectSignedUrl(key)
 console.log(video, " video ");

This one returns a presigned url. I can download the video using fetch method below

 const objectResult = await fetchS3Object(video);
 const bufferType = Buffer.from(objectResult);
 const fileTypeResult = await fileType.fromBuffer(bufferTy[e);
 console.log(fileTypeResult )

The result of fileTypeResult is the following which is correct

{ ext: 'mov', mime: 'video/quicktime' }

The code for the fetchS3Object is the following

async function fetchS3Object(key) {
   console.log(key," KEY ")
   const result = await fetch(key, {
       method: 'GET',
       mode: "cors",
       headers: {
         'Access-Control-Allow-Origin': '*',
       }
   })
   const response = await result.text()
   return response
}

When i print the objectResult variable it is some gibberish.
I am trying to write the objectResult to file using writeFileSync method.

fs.writeFileSync('/tmp/file', objectResult);

The file is written correctly in the specified location, but the video file is corrupted. When I try to play it, it is not working.

Is there is a reason why the written file is corrupted

Body:
I have Managed to solve the problem. Here is the issue. The problem arise from the fact that the original uploaded file which is a video had an encoding of

windows-1252,

However the fetch method return a binary which is encoded with

UTF-8.

As a result when you try to use writeFileSync the output is a corrupted file.
To solve this problem this what has to be done. The fetchS3Object function has to be changed to the following

async function fetchS3Object(key) {
   console.log(key," KEY ")
   const result = await fetch(key, {
      method: 'GET',
      mode: "cors",
      headers: {
          'Access-Control-Allow-Origin': '*',
      }
   })
   const response = await result.arrayBuffer();
   return response
}

then

 const objectResult = await fetchS3Object(video);
 const bufferType = Buffer.from(objectResult);
 fs.writeFileSync('/tmp/file', bufferType);


问:
IntelliJ Code Completion List Keeps Reloading
I am using IntelliJ Ultimate 2019.3. Recently, I noticed that, frequently, my code completion list continually disappears and reloads. Appears for approximately 1 second, then disappears and reloads, then the cycle repeats.

I am not sure if this is relevant, but I am using Kotlin and Arrow-kt.

Any ideas on what might be causing this?

答:
Just update to Kotlin 1.3.72. In this release this bug was fixed.
https://youtrack.jetbrains.com/issue/KT-37144</p>


问:
Different output on changing the position of fgets() function
The output is correct when fgets() in included in the while loop, but taking it outside makes it an infinite loop. Can anyone explain why?</p>

```<code>main()
{
    FILE *fp=fopen("myfile.txt","r");
    char s[100];
    fgets(s,50,fp);
    while(s!=NULL) //infinte loop
        puts(s);
    /* while((fgets(s,100,fp))!=NULL)
          puts(s);
       This runs fine */
    fclose(fp);
}
</code>```

答:
the following proposed code:

cleanly compiles

performs the desired functionality

properly checks for (and handles) errors from fopen() and from fgets()

Eliminates the use of 'magic' numbers

includes the needed header files

contains a valid signature for main()

passes the proper parameters to fgets()

includes a final call to puts() to assure the output stream buffer is flushed to the terminal

incorporates my comments to the OPs question

and now, the proposed code:

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

#define BUF_LEN 100

int main( void )
{
    FILE *fp = fopen( "myfile.txt", "r" );
    if( ! fp )
    {
        perror( "fopen to read file: myfile.txt failed" );
        exit( EXIT_FAILURE );
    }

    char s[ BUF_LEN ];
    while( fgets( s, sizeof(s), fp ) )
    {
        puts( s );
    }
    puts( "" );
    fclose( fp );
}
</code>```

Body:
The output is correct when fgets() in included in the while loop, but taking it outside makes it an infinite loop. Can anyone explain why?

main()
{
    FILE *fp=fopen("myfile.txt","r");
    char s[100];
    fgets(s,50,fp);
    while(s!=NULL) //infinte loop
        puts(s);
    /* while((fgets(s,100,fp))!=NULL)
          puts(s);
       This runs fine */
    fclose(fp);
}

Body:
the following proposed code:

cleanly compiles

performs the desired functionality

properly checks for (and handles) errors from fopen() and from fgets()

Eliminates the use of 'magic' numbers

includes the needed header files

contains a valid signature for main()

passes the proper parameters to fgets()

includes a final call to puts() to assure the output stream buffer is flushed to the terminal

incorporates my comments to the OPs question

and now, the proposed code:

#include <stdio.h>
#include <stdlib.h>

#define BUF_LEN 100

int main( void )
{
    FILE *fp = fopen( "myfile.txt", "r" );
    if( ! fp )
    {
        perror( "fopen to read file: myfile.txt failed" );
        exit( EXIT_FAILURE );
    }

    char s[ BUF_LEN ];
    while( fgets( s, sizeof(s), fp ) )
    {
        puts( s );
    }
    puts( "" );
    fclose( fp );
}


问:
Sorting the latest added in Django
I am trying to show the 8 most recent scans added by doing this:

```<code>def index(request):
....
recent_scans = Image.objects.filter(category='Scan').order_by('-date_added')[:8]
...
</code>```

It "works," but it is not literally getting the 8 most recent scans. The order is different compared to the order for the def scans. The order is not completely different, it's just that there a few scans misplaced.

What is weird is that it works in this view:

```<code>def scans(request):
    image_list = Image.objects.filter(category='Scan').order_by('-date_added')
</code>```

Taking out the [:8] to see if it'll sort correctly does NOT work, though...so I don't know what it wrong. My only guess is that the Image model is connected through a ManytoMany...

I've also tried this:

```<code>recent_scans = Image.objects.filter(category='Scan').latest('date_added')
</code>```

But it comes with this error:

Caught TypeError while rendering: 'Image' object is not iterable

Here is my model, btw:

```<code>class Image(models.Model):
    CATEGORY_CHOICES = (
    ('Cover', 'Cover'),
    ('Scan', 'Scan'),
    ('Other', 'Other'),
    )
    title = models.CharField(max_length=128)
    image = models.ImageField(upload_to="images/")
    category = models.CharField(max_length=10, choices=CATEGORY_CHOICES)
    contributor = models.ManyToManyField(Contributor, blank=True, null=True)
    date_added = models.DateField(auto_now_add=True)
    def __unicode__(self):
        return self.title
    class Meta:
        ordering = ['title']
</code>```

I've tried adding 'get_latest_by = "date_added"` to the Meta class in my models, but that did not work either.

答:
I do not know why it doesn't correctly order by date_added even though in my Issue model, it does. My only guess is that the database doesn't correctly order by the latest item if it's a DateField and not a DateTimeField. Weird, because, again, the Issue model does the same.

So, I've simply just worked around it by sorting by the id and it works great!

ContentLicense: CC BY-SA 3.0

Title: Sorting the latest added in Django

Body:
I am trying to show the 8 most recent scans added by doing this:

def index(request):
....
recent_scans = Image.objects.filter(category='Scan').order_by('-date_added')[:8]
...

It "works," but it is not literally getting the 8 most recent scans. The order is different compared to the order for the def scans. The order is not completely different, it's just that there a few scans misplaced.

What is weird is that it works in this view:

def scans(request):
    image_list = Image.objects.filter(category='Scan').order_by('-date_added')

Taking out the [:8] to see if it'll sort correctly does NOT work, though...so I don't know what it wrong. My only guess is that the Image model is connected through a ManytoMany...

I've also tried this:

recent_scans = Image.objects.filter(category='Scan').latest('date_added')

But it comes with this error:

Caught TypeError while rendering: 'Image' object is not iterable

Here is my model, btw:

class Image(models.Model):
    CATEGORY_CHOICES = (
    ('Cover', 'Cover'),
    ('Scan', 'Scan'),
    ('Other', 'Other'),
    )
    title = models.CharField(max_length=128)
    image = models.ImageField(upload_to="images/")
    category = models.CharField(max_length=10, choices=CATEGORY_CHOICES)
    contributor = models.ManyToManyField(Contributor, blank=True, null=True)
    date_added = models.DateField(auto_now_add=True)
    def __unicode__(self):
        return self.title
    class Meta:
        ordering = ['title']

I've tried adding 'get_latest_by = "date_added"` to the Meta class in my models, but that did not work either.


问:
Http failure during parsing for - angular http post to php
I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet

php file

```<code><?php
header('Access-Control-Allow-Origin: *');

// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $conn = new db_CONNECT();

    $cone=$conn->con;

    //escpae the strings to be inserted to DB
    $escapedname = mysqli_real_escape_string($cone, $name);
    $escapedemail = mysqli_real_escape_string($cone, $email);
    $escapedsubject= mysqli_real_escape_string($cone, $subject);
    $escapedmessage = mysqli_real_escape_string($cone, $message);

    // mysql inserting a new row
    $sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
    // $result= $cone -> query($sql);
    // $affected = $cone -> affected_rows;

    if (mysqli_query($cone,$sql)) {
        echo "Information saved successfully.";
    } else {
        echo "Not successful";
    }
 } else {
    echo "Some field missing.";
}
?>
</code>```

here is the angular snippet

```<code>saveContactDetails = function () {

    this.proceed = true;
    this.success = false;
    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
    data.append('name', this.contactDeJson.name);
    data.append('email', this.contactDeJson.email);
    data.append('subject', this.contactDeJson.subject);
    data.append('message', this.contactDeJson.message);

    this.http
    .post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})
</code>```

Please why am I getting this error

```<code>{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
</code>```

答:
I believe the issue is that your angular script is expecting a json response (the default responseType), but not receiving the correct headers or data. In stead of just echoing out your result in php, I would make a function that can handle sending the response. Something like this:

```<code>function sendJsonResponse(data, status = 200) {
    header('Content-Type: application/json', true, status);
    echo json_encode($data);
    exit();
}
</code>```

In stead of of doing this:

```<code>echo "Not successful";
</code>```

You can now do this:

```<code>sendJsonResponse("Not successful", 500);
</code>```

This should give you more valuable information in the frontend. And the response should now be formatted correctly, and no longer produce the parse error in angular that you are getting now.

Body:
I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet

php file

<?php
header('Access-Control-Allow-Origin: *');

// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $conn = new db_CONNECT();

    $cone=$conn->con;

    //escpae the strings to be inserted to DB
    $escapedname = mysqli_real_escape_string($cone, $name);
    $escapedemail = mysqli_real_escape_string($cone, $email);
    $escapedsubject= mysqli_real_escape_string($cone, $subject);
    $escapedmessage = mysqli_real_escape_string($cone, $message);

    // mysql inserting a new row
    $sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
    // $result= $cone -> query($sql);
    // $affected = $cone -> affected_rows;

    if (mysqli_query($cone,$sql)) {
        echo "Information saved successfully.";
    } else {
        echo "Not successful";
    }
 } else {
    echo "Some field missing.";
}
?>

here is the angular snippet

saveContactDetails = function () {

    this.proceed = true;
    this.success = false;
    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
    data.append('name', this.contactDeJson.name);
    data.append('email', this.contactDeJson.email);
    data.append('subject', this.contactDeJson.subject);
    data.append('message', this.contactDeJson.message);

    this.http
    .post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})

Please why am I getting this error

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",

Body:
I believe the issue is that your angular script is expecting a json response (the default responseType), but not receiving the correct headers or data. In stead of just echoing out your result in php, I would make a function that can handle sending the response. Something like this:

function sendJsonResponse(data, status = 200) {
    header('Content-Type: application/json', true, status);
    echo json_encode($data);
    exit();
}

In stead of of doing this:

echo "Not successful";

You can now do this:

sendJsonResponse("Not successful", 500);

This should give you more valuable information in the frontend. And the response should now be formatted correctly, and no longer produce the parse error in angular that you are getting now.


问:
I am trying to scrape a wikipedia page in nodejs
I am trying to scrape a wikipedia page https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue. My target is to store all 50 rows in the table to csv file.

But I am not able to do so. Please find the code attached.

```<code>// Importing necessary modules

const request = require("request-promise")
const cheerio = require("cheerio")
const fs      = require("fs")
const json2csv = require("json2csv").Parser

// page which i want to scrape
const wiki = "https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue";

(async () => {

    // this will store the data
    let data = [];

    // making request
    const response = await request({
        uri: wiki,
        headers: {
                        accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "en-US,en;q=0.9"
        },
        gzip: true,
    });

    let $ = cheerio.load(response);

      // Extracting rank and name of the company, it will be only for 1st row
      // I will run a loop 50 times to get 50 rows. But below two lines are not working

     // on testing this line on chrome console, it is giving correct output , but it is not working
     // here, same thing for name
        let rank = $('table[class="wikitable sortable jquery-tablesorter"] tbody tr:nth-child(1) th').text();

        let name = $('table[class="wikitable sortable jquery-tablesorter"] tbody tr:nth-child(1) td:nth-child(2)').text();

     // saving data
        data.push({
            rank,
            name,
        });

    // exporting to csv
    const j2cp = new json2csv()
    const csv = j2cp.parse(data);

    fs.writeFileSync("./imdb1.csv", csv, "utf-8");
}
)();

</code>```

Please let me know where is the mistake. I am following this tutorial in case you want to know something about code. https://www.youtube.com/watch?v=BqGq9MTSt7g
Any help is appreciated. Thanks in advance.

答:
I try your code, and it seems that the jquery selector used is okay, but somehow cheerio returns null. Here is my modified code, updated to get other columns as well:</p>

```

    var req = require("request-promise"),
        cheerio = require("cheerio"),
        fs = require("fs"),
        json2csv = require("json2csv").Parser;

    // page which i want to scrape
    const wiki = "https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue";

    (async () => {
        const response = await req({
            uri: wiki,
            headers: {
                accept:
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "accept-encoding": "gzip, deflate, br",
                "accept-language": "en-US,en;q=0.9"
            },
            gzip: true,
        }).then(function (html) {
            let $ = cheerio.load(html);
            let data = [];
            let data2 = [];
            let name, rank, cols, col;
            let rows = $('table.wikitable tbody tr').each((idx, elem) => {
                rank =$(elem).find('th').text().replace(/[\n\r]+/g,'');
                //name = $(elem).find('td a').html();
                data2 = [];
                cols = $(elem).find('td').each((colidx, colelem) => {
                    col = $(colelem).text().replace(/[\n\r]+/g,'');
                    data2.push(col,);
                });

                data.push({
                    rank,
                    ...data2,
                });
            });

            // exporting to csv
            const j2cp = new json2csv()
            const csv = j2cp.parse(data);

            fs.writeFileSync("./imdb1.csv", csv, "utf-8");
        }).catch(function (err) {
            console.log(err);
        });

    }
    )();

```

Body:
I am trying to scrape a wikipedia page https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue. My target is to store all 50 rows in the table to csv file.

But I am not able to do so. Please find the code attached.

// Importing necessary modules

const request = require("request-promise")
const cheerio = require("cheerio")
const fs      = require("fs")
const json2csv = require("json2csv").Parser

// page which i want to scrape
const wiki = "https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue";

(async () => {

    // this will store the data
    let data = [];

    // making request
    const response = await request({
        uri: wiki,
        headers: {
                        accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "en-US,en;q=0.9"
        },
        gzip: true,
    });

    let $ = cheerio.load(response);

      // Extracting rank and name of the company, it will be only for 1st row
      // I will run a loop 50 times to get 50 rows. But below two lines are not working

     // on testing this line on chrome console, it is giving correct output , but it is not working
     // here, same thing for name
        let rank = $('table[class="wikitable sortable jquery-tablesorter"] tbody tr:nth-child(1) th').text();

        let name = $('table[class="wikitable sortable jquery-tablesorter"] tbody tr:nth-child(1) td:nth-child(2)').text();

     // saving data
        data.push({
            rank,
            name,
        });

    // exporting to csv
    const j2cp = new json2csv()
    const csv = j2cp.parse(data);

    fs.writeFileSync("./imdb1.csv", csv, "utf-8");
}
)();

Please let me know where is the mistake. I am following this tutorial in case you want to know something about code. https://www.youtube.com/watch?v=BqGq9MTSt7g
Any help is appreciated. Thanks in advance.

Body:
I try your code, and it seems that the jquery selector used is okay, but somehow cheerio returns null. Here is my modified code, updated to get other columns as well:

    var req = require("request-promise"),
        cheerio = require("cheerio"),
        fs = require("fs"),
        json2csv = require("json2csv").Parser;

    // page which i want to scrape
    const wiki = "https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue";

    (async () => {
        const response = await req({
            uri: wiki,
            headers: {
                accept:
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "accept-encoding": "gzip, deflate, br",
                "accept-language": "en-US,en;q=0.9"
            },
            gzip: true,
        }).then(function (html) {
            let $ = cheerio.load(html);
            let data = [];
            let data2 = [];
            let name, rank, cols, col;
            let rows = $('table.wikitable tbody tr').each((idx, elem) => {
                rank =$(elem).find('th').text().replace(/[\n\r]+/g,'');
                //name = $(elem).find('td a').html();
                data2 = [];
                cols = $(elem).find('td').each((colidx, colelem) => {
                    col = $(colelem).text().replace(/[\n\r]+/g,'');
                    data2.push(col,);
                });

                data.push({
                    rank,
                    ...data2,
                });
            });

            // exporting to csv
            const j2cp = new json2csv()
            const csv = j2cp.parse(data);

            fs.writeFileSync("./imdb1.csv", csv, "utf-8");
        }).catch(function (err) {
            console.log(err);
        });

    }
    )();


问:
Incorrect usage of UNION and ORDER BY?
how can i use union and order by in mysql ?

```<code>select * from _member_facebook
inner join _member_pts
ON _member_facebook._fb_owner=_member_pts._username
where _member_facebook._promote_point = 9
ORDER BY RAND() limit 2
UNION ALL
select * from _member_facebook
inner join _member_pts
ON _member_facebook._fb_owner=_member_pts._username
where _member_facebook._promote_point = 8 limit 3
</code>```

give me error

```<code>#1221 - Incorrect usage of UNION and ORDER BY
</code>```

any one can help ?

答:
Using parentheses fixed my problem while using Order by and limit clauses in the query. My requirement was to get the top and the bottom row in the table with a certain condition and the following code worked for me:</p>

```<code>(SELECT column1, column2
FROM table1
ORDER BY column1, column2
LIMIT 1)

UNION

(SELECT column1, column2
FROM table2
ORDER BY column1, column2
LIMIT 1)
</code>```

Title: Incorrect usage of UNION and ORDER BY?

Body:
how can i use union and order by in mysql ?

select * from _member_facebook
inner join _member_pts
ON _member_facebook._fb_owner=_member_pts._username
where _member_facebook._promote_point = 9
ORDER BY RAND() limit 2
UNION ALL
select * from _member_facebook
inner join _member_pts
ON _member_facebook._fb_owner=_member_pts._username
where _member_facebook._promote_point = 8 limit 3

give me error

#1221 - Incorrect usage of UNION and ORDER BY

any one can help ?

Body:
Using parentheses fixed my problem while using Order by and limit clauses in the query. My requirement was to get the top and the bottom row in the table with a certain condition and the following code worked for me:

(SELECT column1, column2
FROM table1
ORDER BY column1, column2
LIMIT 1)

UNION

(SELECT column1, column2
FROM table2
ORDER BY column1, column2
LIMIT 1)


问:
Firebase is getting the data letter-by-letter as I'm typing(without clicking the "UPDATE"), instead of a whole string
Hi there I am actually a beginner and working on my React Native project and I also use Firebase within React Native. I got a problem like I've stated in title, the Realtime Database in Firebase gets the "Name", "Surname" and "Birthday" data exactly  like this;

Image

I want the Firebase to get my data only once as a whole string as "Name" when i click "UPDATE", not letter by letter like "N" first then "Na"... etc.(this situaton applies for "Name", "Surname" and "Birthday" data as well.).

And Here's my code:

```<code>class Profile extends Component {
  onChangeName(profile) {
    this.props.updateProfile(profile);
  }

  onChangeSurname(profile) {
    this.props.updateProfile(profile);
  }

  updateProfile() {
    this.props.updateProfile(this.props.profile);
  }

  render() {
    return (
      <View>
        <Profiletext
          placeholder="Name..."
          onChangeText={this.onChangeName.bind(this)}
        />
        <Profiletext
          placeholder="Surname..."
          onChangeText={this.onChangeSurname.bind(this)}
        />
        <Profiletext
          placeholder="Birthday..."
          onChangeText={this.onChangeSurname.bind(this)}
        />
        <MyButton
          spinner={false}
          title="UPDATE"
          onPress={this.updateProfile.bind(this)}
          color="#E87B79"
        />
      </View>
    );
  }
}

const mapStateToProps = state => {
  const {profile} = state.profileForm;
  return {
    profile,
  };
};

export default connect(
  mapStateToProps,
  {
    changeProfile,
    updateProfile,
  },
)(Profile);
</code>```

答:
I am going to assume that your updateProfile is making the database call to update the data. However the issue is that you are making a call to updateProfile every time the input is changing because of onChange functions on inputs.

Instead you can have state that holds Name, Surname, and Birthday and you can update the state on onChange call. And when the user clicks the button, you can update the profile with state and then call updateProfile.

```<code>class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Name: "",
      SurName: "",
      Birthday: "",
    };
  }

  onFieldChange(event) {
    const { name, value } = event.target;
    this.setState({ [name]: value });
  }

  updateProfile() {
    // update profile with new Name, Surname, and Birthday
    this.props.profile.name = this.state.Name;
    this.props.profile.surName = this.state.SurName;
    this.props.profile.birthday = this.state.Birthday;
    this.props.updateProfile(this.props.profile);
  }

  render() {
    return (
      <View>
        <Profiletext
          name="Name"
          placeholder="Name..."
          onChangeText={this.onFieldChange.bind(this)}
        />
        <Profiletext
          name="SurName"
          placeholder="Surname..."
          onChangeText={this.onFieldChange.bind(this)}
        />
        <Profiletext
          name="Birthday"
          placeholder="Birthday..."
          onChangeText={this.onFieldChange.bind(this)}
        />
        <MyButton
          spinner={false}
          title="UPDATE"
          onPress={this.updateProfile.bind(this)}
          color="#E87B79"
        />
      </View>
    );
  }
}

</code>```

Body:
Hi there I am actually a beginner and working on my React Native project and I also use Firebase within React Native. I got a problem like I've stated in title, the Realtime Database in Firebase gets the "Name", "Surname" and "Birthday" data exactly  like this;

Image

I want the Firebase to get my data only once as a whole string as "Name" when i click "UPDATE", not letter by letter like "N" first then "Na"... etc.(this situaton applies for "Name", "Surname" and "Birthday" data as well.).

And Here's my code:

class Profile extends Component {
  onChangeName(profile) {
    this.props.updateProfile(profile);
  }

  onChangeSurname(profile) {
    this.props.updateProfile(profile);
  }

  updateProfile() {
    this.props.updateProfile(this.props.profile);
  }

  render() {
    return (
      <View>
        <Profiletext
          placeholder="Name..."
          onChangeText={this.onChangeName.bind(this)}
        />
        <Profiletext
          placeholder="Surname..."
          onChangeText={this.onChangeSurname.bind(this)}
        />
        <Profiletext
          placeholder="Birthday..."
          onChangeText={this.onChangeSurname.bind(this)}
        />
        <MyButton
          spinner={false}
          title="UPDATE"
          onPress={this.updateProfile.bind(this)}
          color="#E87B79"
        />
      </View>
    );
  }
}

const mapStateToProps = state => {
  const {profile} = state.profileForm;
  return {
    profile,
  };
};

export default connect(
  mapStateToProps,
  {
    changeProfile,
    updateProfile,
  },
)(Profile);

Body:
I am going to assume that your updateProfile is making the database call to update the data. However the issue is that you are making a call to updateProfile every time the input is changing because of onChange functions on inputs.

Instead you can have state that holds Name, Surname, and Birthday and you can update the state on onChange call. And when the user clicks the button, you can update the profile with state and then call updateProfile.

class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Name: "",
      SurName: "",
      Birthday: "",
    };
  }

  onFieldChange(event) {
    const { name, value } = event.target;
    this.setState({ [name]: value });
  }

  updateProfile() {
    // update profile with new Name, Surname, and Birthday
    this.props.profile.name = this.state.Name;
    this.props.profile.surName = this.state.SurName;
    this.props.profile.birthday = this.state.Birthday;
    this.props.updateProfile(this.props.profile);
  }

  render() {
    return (
      <View>
        <Profiletext
          name="Name"
          placeholder="Name..."
          onChangeText={this.onFieldChange.bind(this)}
        />
        <Profiletext
          name="SurName"
          placeholder="Surname..."
          onChangeText={this.onFieldChange.bind(this)}
        />
        <Profiletext
          name="Birthday"
          placeholder="Birthday..."
          onChangeText={this.onFieldChange.bind(this)}
        />
        <MyButton
          spinner={false}
          title="UPDATE"
          onPress={this.updateProfile.bind(this)}
          color="#E87B79"
        />
      </View>
    );
  }
}


问:
Query to extract only records which have failed
I need a help in writing a SQL for the below table. I have a table with two columns (Name and Status). </p>

```<code>Name    Status
Kevin   success
Mark    fail
Mark    success
Mike    success
Yann    fail
Yann    success
George  fail
Boi     Fail
</code>```

<p>From the above table, I would like to extract only records which have failed and also which are failed then succeeded. Basically I would like to exclude the records which are just succeeded. </p>

答:
Basically I would like to exclude the records which are just succeeded.

If you want all records whose name has at least one non-'success' status, you can use exists:

```<code>select t.*
from mytable t
where exists(
    select 1 from mytable t1 where t1.name = t.name and t1.status <> 'success'
)
</code>```

Alternatively, if you want a list of names that have at least one non-'success' status, then you can use aggregation and filter with a having clause:

```<code>select name
from mytable
group by name
having max(case when status <> 'success' then 1 else 0 end) = 1
</code>```

Body:
I need a help in writing a SQL for the below table. I have a table with two columns (Name and Status).

Name    Status
Kevin   success
Mark    fail
Mark    success
Mike    success
Yann    fail
Yann    success
George  fail
Boi     Fail

From the above table, I would like to extract only records which have failed and also which are failed then succeeded. Basically I would like to exclude the records which are just succeeded.

Body:
Basically I would like to exclude the records which are just succeeded.

If you want all records whose name has at least one non-'success' status, you can use exists:

select t.*
from mytable t
where exists(
    select 1 from mytable t1 where t1.name = t.name and t1.status <> 'success'
)

Alternatively, if you want a list of names that have at least one non-'success' status, then you can use aggregation and filter with a having clause:

select name
from mytable
group by name
having max(case when status <> 'success' then 1 else 0 end) = 1


问:
Best way to save SQL versions while working on Tableau?
I am working using Tableau and have to write down multiple different SQL each time, while making new data sources.
I have to save all changes on SQL for every data source.
Currently I would paste the SQL on notepad and save them on separate folder in my computer, along with description of the changes.
Is there any better way to do this?</p>

答:
Assuming you have permission to create objects in the database, begin by creating database views, As @Nick.McDermaid commented.

Then, instead of using Custom SQL data source in Tableau, just connect to the View as if it were a table.

If you need to track the changes to these SQL views of your data, you will need to learn how to use source control for the .sql files that can be scripted from within SQL Server Management Studio:

Your company or school may have a preferred source control system already in use, in which case you should use that. If they don't, or if you are learning at home, then Git and Subversion are popular open source choices.

There are many courses available on learning platforms like Coursera that will teach you how to learn how to use those systems.


问:
Trimming GPS information with awk
In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

```<code>  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude
</code>```

But what I get out seems to confuse the +/- signs in front of each component:

```<code>-04.7367+055.5230
-04.7367
-055.5230
</code>```

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?

答:
grep solution:

```<code>$ geo_data=-04.7367+055.5230

$ echo $geo_data
-04.7367+055.5230

$ GPS_latitude=$(grep -o '^[+-][^+-]*' <<< $geo_data)
$ GPS_longitude=$(grep -o '[+-][^+-]*$' <<< $geo_data)

$ echo "GPS Latitude: $GPS_latitude; GPS Longitude: $GPS_longitude"
GPS Latitude: -04.7367; GPS Longitude: +055.5230
</code>```

Title: Trimming GPS information with awk

Body:
In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude

But what I get out seems to confuse the +/- signs in front of each component:

-04.7367+055.5230
-04.7367
-055.5230

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?

Body:
grep solution:

$ geo_data=-04.7367+055.5230

$ echo $geo_data
-04.7367+055.5230

$ GPS_latitude=$(grep -o '^[+-][^+-]*' <<< $geo_data)
$ GPS_longitude=$(grep -o '[+-][^+-]*$' <<< $geo_data)

$ echo "GPS Latitude: $GPS_latitude; GPS Longitude: $GPS_longitude"
GPS Latitude: -04.7367; GPS Longitude: +055.5230


问:
How to sanitize an object on create in Rails 2.3.x?
In my search I mainly found ways to sanitize data when outputting OR sanitizing single input boxes using:

```<code><%=h @name %> OR ['name = ?', params[:name]]
</code>```

However, I'm creating an object like so:

```<code>@user = User.new( params[:user] )
</code>```

Now, I could sanitize each key in the params[:user] hash one by one, but I'm sure there is a more elegant technique.

答: If this is for optimization reasons, use the 'Sanitize' gem.  However, since you talk about doing it for every single field, something smells a little wrong here.  ActiveRecord already escapes input to avoid SQL injection problems, but you shouldn't need to HTML-escape every single thing that goes into your database (and doing so could cause issues later down the line if you want to process the original data in some way).  The only things you may want to sanitize before they go into the database, for performance reasons, are things like Rich Text Editor input fields, such as data coming from TinyMCE, where you actually want to filter the data against a white-list, not just escape it with simple string conversions.</p>

Body:
In my search I mainly found ways to sanitize data when outputting OR sanitizing single input boxes using:

<%=h @name %> OR ['name = ?', params[:name]]

However, I'm creating an object like so:

@user = User.new( params[:user] )

Now, I could sanitize each key in the params[:user] hash one by one, but I'm sure there is a more elegant technique.


问:
NativeScript : custom camera view
I am working on an iOS and Android application with a custom camera view (that's why I won't use camera module http://docs.nativescript.org/ApiReference/camera/README)

I need to have my own UI above the camera preview.

Can I do this with Nativescript ?

I could not find any module/plugin with this feature.
Is this hard to write my own module?

答:
I don't understand exactly your scenario, but what I have in one of my apps that has a barcode scanner (that uses a custom camera view as in your question?) which I wanted to have a laser beam line in the middle of the camera view-port, is this:

<GridLayout>
  <YourCameraView />

   <StackLayout id="laser"></StackLayout>
</GridLayout>
```

This enables you to have the laser on top of the YourCameraView element and you can position the laser element using vertical-align and horizontal-align CSS properties.

If you want more freedom, substitute the GridLayout with AbsoluteLayout, so then you can position the overlay elements (i.e. the laser element) using top and left CSS properties.

Title: NativeScript : custom camera view

Body:
I don't understand exactly your scenario, but what I have in one of my apps that has a barcode scanner (that uses a custom camera view as in your question?) which I wanted to have a laser beam line in the middle of the camera view-port, is this:

<GridLayout>
  <YourCameraView />

   <StackLayout id="laser"></StackLayout>
</GridLayout>

This enables you to have the laser on top of the YourCameraView element and you can position the laser element using vertical-align and horizontal-align CSS properties.

If you want more freedom, substitute the GridLayout with AbsoluteLayout, so then you can position the overlay elements (i.e. the laser element) using top and left CSS properties.


问:
How to create a multistage dockerfile for a python app?
Below is the directory structure and the dockerfile for my python application. In order to run the main.py, I need to create a data set by running generate_data.py, which is in the data directory. How can I create a multistage dockerfile in order to first create the data and then run the main.py file? I'm new to using docker and I feel overwhelmed.

```<code>FROM python:3.7.2-slim
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . /usr/src/app
CMD ["python", "./src/main.py"]
</code>```

答:
A key point of using docker might be to isolate your programs, so at first glance, you might want to move them to separate containers and talk to each other using a shared volume or a docker network, but if you really need them to run in the same container, you can achieve this by using a bash script. and replacing CMD  with:

```<code>COPY run.sh
RUN chmod a+x run.sh
CMD ["./run.sh"]
</code>```

You can also include if statements into a bash script and pass arguments to the bash script through docker.

Body:
Below is the directory structure and the dockerfile for my python application. In order to run the main.py, I need to create a data set by running generate_data.py, which is in the data directory. How can I create a multistage dockerfile in order to first create the data and then run the main.py file? I'm new to using docker and I feel overwhelmed.

FROM python:3.7.2-slim
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . /usr/src/app
CMD ["python", "./src/main.py"]

Body:
A key point of using docker might be to isolate your programs, so at first glance, you might want to move them to separate containers and talk to each other using a shared volume or a docker network, but if you really need them to run in the same container, you can achieve this by using a bash script. and replacing CMD  with:

COPY run.sh
RUN chmod a+x run.sh
CMD ["./run.sh"]

You can also include if statements into a bash script and pass arguments to the bash script through docker.


问:
Recursive function with two inputs
Write a recursive function called print_num_pattern() to output the following number pattern.

Given a positive integer as input (Ex: 12), subtract another positive integer (Ex: 3) continually until 0 or a negative value is reached, and then continually add the second integer until the first integer is again reached.

Ex. If the input is:

12
3

the output is:

12 9 6 3 0 3 6 9 12

Here's what I tried:

```<code>num1 = 12

num2 = 3

def print_num_pattern(num1,num2):

    if (num1 == 0 or num1 < 0):
        print(num1, end = ' ')
        return

    print(num1, end = ' ')
    print_num_pattern(num1 - num2)

    print(num1, end = ' ')

print_num_pattern(num1,num2)
</code>```

答:
The most obvious error is that you're calling print_num_pattern(num1 - num2) with only one out of two parameters

def print_num_pattern(num1,num2):

    if (num1 == 0 or num1 < 0):
        print(num1, end = ' ')
        return

    print(num1, end = ' ')
    print_num_pattern(num1 - num2, num2)

    print(num1, end = ' ')
```

<p>It works fine after that</p>

<pre class="lang-py prettyprint-override"><code>>>> print_num_pattern(12, 3)
12 9 6 3 0 3 6 9 12
</code>```

Title: Recursive function with two inputs

Body:
Write a recursive function called print_num_pattern() to output the following number pattern.

Given a positive integer as input (Ex: 12), subtract another positive integer (Ex: 3) continually until 0 or a negative value is reached, and then continually add the second integer until the first integer is again reached.

Ex. If the input is:

12
3

the output is:

12 9 6 3 0 3 6 9 12

Here's what I tried:

num1 = 12

num2 = 3

def print_num_pattern(num1,num2):

    if (num1 == 0 or num1 < 0):
        print(num1, end = ' ')
        return

    print(num1, end = ' ')
    print_num_pattern(num1 - num2)

    print(num1, end = ' ')

print_num_pattern(num1,num2)

Body:
The most obvious error is that you're calling print_num_pattern(num1 - num2) with only one out of two parameters

def print_num_pattern(num1,num2):

    if (num1 == 0 or num1 < 0):
        print(num1, end = ' ')
        return

    print(num1, end = ' ')
    print_num_pattern(num1 - num2, num2)

    print(num1, end = ' ')

It works fine after that

>>> print_num_pattern(12, 3)
12 9 6 3 0 3 6 9 12


问:
Listview.setOnItemclicklistener with Searchview
I've a problem with my ListView onClick. I try to explain u by a particule of my code.

So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?

```<code>
private SearchView sv;

Protected void onCreate........

String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);

sv=findViewById(R.id.searchview);

ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
   if(position == 0){
     Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
  }

  if(position == 1){
     Intent b = new Intent  (getApplicationContext(),AtivityB.class);
startActivity(b)
  }

 if(position == 2){
     Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
  }
}```
```

答:
As position will always return the first position of the list (which is 0) when you've a single filtered out item as in your case; in order to get the actual position you can search for the first index of the item in the list using .indexOf() method. This requires you to convert your array into a an ArrayList

```<code>final String[] Values = {"a", "b", "c"};
final ArrayList<String> list = Arrays.asList(Values);

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int pos = list.indexOf(myListAdapter.getItem(position));

        switch (pos) {
            case 0:
                Intent a = new Intent(getApplicationContext(), AtivityA.class);
                startActivity(a);
                return;
            case 1:
                Intent b = new Intent(getApplicationContext(), AtivityB.class);
                startActivity(b);
                return;
            case 2:
                Intent c = new Intent(getApplicationContext(), AtivityC.class);
                startActivity(c);

        }

    }
});
</code>```

Body:
I've a problem with my ListView onClick. I try to explain u by a particule of my code.

So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?

private SearchView sv;

Protected void onCreate........

String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);

sv=findViewById(R.id.searchview);

ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
   if(position == 0){
     Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
  }

  if(position == 1){
     Intent b = new Intent  (getApplicationContext(),AtivityB.class);
startActivity(b)
  }

 if(position == 2){
     Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
  }
}```

Body:
As position will always return the first position of the list (which is 0) when you've a single filtered out item as in your case; in order to get the actual position you can search for the first index of the item in the list using .indexOf() method. This requires you to convert your array into a an ArrayList

final String[] Values = {"a", "b", "c"};
final ArrayList<String> list = Arrays.asList(Values);

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int pos = list.indexOf(myListAdapter.getItem(position));

        switch (pos) {
            case 0:
                Intent a = new Intent(getApplicationContext(), AtivityA.class);
                startActivity(a);
                return;
            case 1:
                Intent b = new Intent(getApplicationContext(), AtivityB.class);
                startActivity(b);
                return;
            case 2:
                Intent c = new Intent(getApplicationContext(), AtivityC.class);
                startActivity(c);

        }

    }
});


问:
moviepy ruining video after combining them
I'm trying to make a program that downloads videos from TikTok and combines all the separate videos into one .mp4 file and moves the final video to a folder on my desktop. I've been able to make it download all the videos and when I watch the separate videos they play fine however when I combine the videos some of the videos are messed up and look like this but the audio is fine.

```<code>#slecting all .mp4 files
    video_files = glob.iglob("*.mp4")

    print(video_files)
    clips = []

    for clip in video_files:  # For each mp4 file name
        clips.append(VideoFileClip(clip))  # Store them as a VideoFileClip and add to the clips list

    today = date.today()

    final = concatenate_videoclips(clips)  # Concatenate the VideoFileClips
    final.write_videofile(f"{today}.mp4", codec="libx264")

#moving completed video to folder on desktop
    shutil.move(f'{today}.mp4', '/Users/jacobmarrandio/Desktop/done_videos/')
</code>```

thanks for any help

答:
You want to ensure that all of your videos are of the same size before concatenating. Or, you could modify the smaller clips to have a black margin by filling up space by making this change:</p>

```<code>final = concatenate_videoclips(clips, method='compose')
</code>```

Body:
I'm trying to make a program that downloads videos from TikTok and combines all the separate videos into one .mp4 file and moves the final video to a folder on my desktop. I've been able to make it download all the videos and when I watch the separate videos they play fine however when I combine the videos some of the videos are messed up and look like this but the audio is fine.

#slecting all .mp4 files
    video_files = glob.iglob("*.mp4")

    print(video_files)
    clips = []

    for clip in video_files:  # For each mp4 file name
        clips.append(VideoFileClip(clip))  # Store them as a VideoFileClip and add to the clips list

    today = date.today()

    final = concatenate_videoclips(clips)  # Concatenate the VideoFileClips
    final.write_videofile(f"{today}.mp4", codec="libx264")

#moving completed video to folder on desktop
    shutil.move(f'{today}.mp4', '/Users/jacobmarrandio/Desktop/done_videos/')

thanks for any help

Body:
You want to ensure that all of your videos are of the same size before concatenating. Or, you could modify the smaller clips to have a black margin by filling up space by making this change:

final = concatenate_videoclips(clips, method='compose')


问:
Does boost asio ssl::stream<tcp::socket> supports multiple pending http::async_write calls?
I have a http client that performs http::async_write() with a callback that performs http::async_read() on ssl::stream. All the async operations are wrapped in the same explicit strand.

The simplified code looks like this

```<code>http::async_write(
        *tcp_session_->tcp_stream(), *request,
        boost::asio::bind_executor(
            tcp_session_strand_,
            [request, this](
                boost::system::error_code ec,
                std::size_t /* bytes_transferred */) {
              if (ec) {
                return;
              }
              auto response_buffer =
                  std::make_shared<boost::beast::flat_buffer>();
              auto response = std::make_shared<HttpResponse>();
              http::async_read(
                  *tcp_session_->tcp_stream(), *response_buffer, *response,
                  boost::asio::bind_executor(
                      tcp_session_strand_,
                      [request, done, response_buffer, response](
                          boost::system::error_code ec,
                          std::size_t /*bytes_transferred*/) {
                        if (ec) {
                          // log error
                          return;
                        }
                      }));
            }));
</code>```

I call the async_write like this two times in a row. I don't wait for the first async_write handler completion before the second write is performed.

The behavior that I see is. The first async_write is completed, then the second async_write is completed, then the first async_read is invoked with the error: "Operation canceled". This reproduces quite consistently, so I assume ssl::stream does not support multiple pending http requests. Basically one has to wait for the response before sending next request.

Is my assumption correct? I read the documentation for ssl::stream but it does not say anything about that (only that async operations have to be serialized by strand).

答:
Per Beast documentation for async_write:

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other writes until this operation completes.

Body:
I have a http client that performs http::async_write() with a callback that performs http::async_read() on ssl::stream. All the async operations are wrapped in the same explicit strand.

The simplified code looks like this

http::async_write(
        *tcp_session_->tcp_stream(), *request,
        boost::asio::bind_executor(
            tcp_session_strand_,
            [request, this](
                boost::system::error_code ec,
                std::size_t /* bytes_transferred */) {
              if (ec) {
                return;
              }
              auto response_buffer =
                  std::make_shared<boost::beast::flat_buffer>();
              auto response = std::make_shared<HttpResponse>();
              http::async_read(
                  *tcp_session_->tcp_stream(), *response_buffer, *response,
                  boost::asio::bind_executor(
                      tcp_session_strand_,
                      [request, done, response_buffer, response](
                          boost::system::error_code ec,
                          std::size_t /*bytes_transferred*/) {
                        if (ec) {
                          // log error
                          return;
                        }
                      }));
            }));

I call the async_write like this two times in a row. I don't wait for the first async_write handler completion before the second write is performed.

The behavior that I see is. The first async_write is completed, then the second async_write is completed, then the first async_read is invoked with the error: "Operation canceled". This reproduces quite consistently, so I assume ssl::stream does not support multiple pending http requests. Basically one has to wait for the response before sending next request.

Is my assumption correct? I read the documentation for ssl::stream but it does not say anything about that (only that async operations have to be serialized by strand).


答:
You are missing an argument in your recursive call. You need to replace this:

```<code>print_num_pattern(num1 - num2)
</code>```

with this:

```<code>print_num_pattern(num1 - num2, num2)
</code>```

Title: Recursive function with two inputs

Body:
You are missing an argument in your recursive call. You need to replace this:

print_num_pattern(num1 - num2)

with this:

print_num_pattern(num1 - num2, num2)


问:
Does adding [DataContract] and [DataMember] to all classes impact performance
Lets say we got a code generating tool that creates thousands of C# classes, and we sometimes need to add those attributes to them.

We are considering whether it is better to put [DataContract] and [DataMember] on all appropriate classes or we need to create a special strategy that will determine whether to do so in order to save up some possible? performance lost in AtribbuteAll approach.

In the end the question is whether adding attributes can somehow affect performance?

I am thinking that adding an attribute on a class will simply stay with its type information and should not affect any performance but would like to be 100% certain here

答:
impact performance is unavoidable.
but if you need attribute to complete your attention, you have not other choice.
if you do not need, you may remove it.</p>


问:
Divergence Funtion result issue
I try to implement a function to find short term RSI divergences. I want it to work like this:

Find last RSI pivot

Compare it to previous Pivots

If there is a Divergence, set counter plus one

And if my counter over 0 - show a divergence char at bar.

But it doesn't work.

```<code>study("RSI short term divergence", overlay=true)

//Inputs
lookback = input(defval=34, title='Lookback for RSI divergence, bars', minval=1, type=input.integer)
len = input(defval=3, title='Pivot confirmation, bars', minval=1, type=input.integer)

//RSI
rsi = rsi(close, 14)

//Variables
pivotLow = pivotlow(rsi, len, 1)

//Function

func_short(pivsback) =>
    count_s = 0
    for i = 1 to pivsback
        rsiLast_s = valuewhen(pivotLow, rsi[1], 0)
        priceLast_s = valuewhen(pivotLow, close[1], 0)
        barLast_s = valuewhen(pivotLow, bar_index[1], 0)
        rsiWas_s = valuewhen(pivotLow, rsi[1], i)
        priceWas_s = valuewhen(pivotLow, close[1], i)
        barWas_s = valuewhen(pivotLow, bar_index[1], i)
        count_s = if (rsiLast_s > rsiWas_s) and (priceWas_s > priceLast_s) and (barLast_s-barWas_s)<lookback
            count_s := count_s + 1
    count_s

divShort = func_short(3)>0

plotchar(divShort, location=location.abovebar, color=color.white, size=size.small)
</code>```

答:
valuewhen(), like many other built-ins, can't be used in for loops with variable arguments. See this usrman section for an explanation.

Your options are:

Use a structure like this to pre-evaluate a preset quantity of pivots and then run your logic on them:

```<code>//@version=4
study("Max Pivots", "", true)
legs = input(4)
pH = pivothigh(legs, legs)
newPH = not na(pH)
p00 = valuewhen(newPH, high[legs], 00)
p01 = valuewhen(newPH, high[legs], 01)
p02 = valuewhen(newPH, high[legs], 02)
maxPH = max(p00, p01, p02)
plot(maxPH)
plotchar(newPH, "newPH", "•", location.abovebar, offset = - legs)
plotchar(newPH, "newPH", "▲", location.top)
</code>```

Run an embedded for loop to hunt past bars for past pivot values, which I don't recommend as it will be very slow.

Title: Divergence Funtion result issue

Body:
I try to implement a function to find short term RSI divergences. I want it to work like this:

Find last RSI pivot

Compare it to previous Pivots

If there is a Divergence, set counter plus one

And if my counter over 0 - show a divergence char at bar.

But it doesn't work.

study("RSI short term divergence", overlay=true)

//Inputs
lookback = input(defval=34, title='Lookback for RSI divergence, bars', minval=1, type=input.integer)
len = input(defval=3, title='Pivot confirmation, bars', minval=1, type=input.integer)

//RSI
rsi = rsi(close, 14)

//Variables
pivotLow = pivotlow(rsi, len, 1)

//Function

func_short(pivsback) =>
    count_s = 0
    for i = 1 to pivsback
        rsiLast_s = valuewhen(pivotLow, rsi[1], 0)
        priceLast_s = valuewhen(pivotLow, close[1], 0)
        barLast_s = valuewhen(pivotLow, bar_index[1], 0)
        rsiWas_s = valuewhen(pivotLow, rsi[1], i)
        priceWas_s = valuewhen(pivotLow, close[1], i)
        barWas_s = valuewhen(pivotLow, bar_index[1], i)
        count_s = if (rsiLast_s > rsiWas_s) and (priceWas_s > priceLast_s) and (barLast_s-barWas_s)<lookback
            count_s := count_s + 1
    count_s

divShort = func_short(3)>0

plotchar(divShort, location=location.abovebar, color=color.white, size=size.small)

Body:
valuewhen(), like many other built-ins, can't be used in for loops with variable arguments. See this usrman section for an explanation.

Your options are:

Use a structure like this to pre-evaluate a preset quantity of pivots and then run your logic on them:

//@version=4
study("Max Pivots", "", true)
legs = input(4)
pH = pivothigh(legs, legs)
newPH = not na(pH)
p00 = valuewhen(newPH, high[legs], 00)
p01 = valuewhen(newPH, high[legs], 01)
p02 = valuewhen(newPH, high[legs], 02)
maxPH = max(p00, p01, p02)
plot(maxPH)
plotchar(newPH, "newPH", "•", location.abovebar, offset = - legs)
plotchar(newPH, "newPH", "▲", location.top)

Run an embedded for loop to hunt past bars for past pivot values, which I don't recommend as it will be very slow.


问:
Django send data to Javascript File
I know how to send data from Django to html with the view

```<code>def index(request):
    coord = "[[1, 2], [2, 1]"
    return render(request, 'index.html', {'coord': coord})
</code>```

In the html I able to use it any where like this {{ coord }}, example :

```<code><script type="text/javascript">
     var geojsonObject = {
         "coordinates": {{ coord }}
     };
</script>
</code>```

But when I try to do this in my 'index.js' I get an error:

Uncaught SyntaxError: Unexpected token '{'

index.html

```<code><script src="{% static 'index.js'%}"></script>
</code>```

index.js

```<code>var geojsonObject = {
         "coordinates": {{ coord }}
};
</code>```

I could keep everything in index.html, but I find it not practical to debug. How can I pass my coor object to the JavaScript through html?

答:
Are you sure you wanna "render" your index.js? I guess a better approach would be to modify your index.js so that if accepts the templated value as a variable. For example:

index.html

```<code><button onclick="doStuff({{ coord }})">Button</button>
</code>```

index.js

function doStuff(coord) {
    var geojsonObject = {
         "coordinates": coord,
    };
}
```

In this way you don't need to copy all your code to the index.html file either.

Otherwise, you could just pass an ID to the element you are templating the value into, and then use document.getElementById("myElement").innerHTML to access it's value.

Title: Django send data to Javascript File

Body:
I know how to send data from Django to html with the view

def index(request):
    coord = "[[1, 2], [2, 1]"
    return render(request, 'index.html', {'coord': coord})

In the html I able to use it any where like this {{ coord }}, example :

But when I try to do this in my 'index.js' I get an error:

Uncaught SyntaxError: Unexpected token '{'

index.html

index.js

var geojsonObject = {
         "coordinates": {{ coord }}
};

I could keep everything in index.html, but I find it not practical to debug. How can I pass my coor object to the JavaScript through html?

Body:
Are you sure you wanna "render" your index.js? I guess a better approach would be to modify your index.js so that if accepts the templated value as a variable. For example:

index.html

<button onclick="doStuff({{ coord }})">Button</button>

index.js

function doStuff(coord) {
    var geojsonObject = {
         "coordinates": coord,
    };
}

In this way you don't need to copy all your code to the index.html file either.

Otherwise, you could just pass an ID to the element you are templating the value into, and then use document.getElementById("myElement").innerHTML to access it's value.


问:
How to get data from textview and checkboxes from dialog?
I have create an EditText button which opens a dialog with bunch of checkboxes and one EditText. In the OnCreate method:

```<code>        skillsEditText = findViewById(R.id.edit_skills);
        skillsEditText.setClickable(true);
        skillsEditText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_skills,null);
                mBuilder.setView(mView);
                specialSkillsDialog = mBuilder.create();
                specialSkillsDialog.setCanceledOnTouchOutside(false);
                specialSkillsDialog.show();
            }
        });

</code>```

After the users clicks Done, I execute the onDoneClick method:

```<code>    public void onProfessionsDoneClick(View view) {
        CheckBox skillCheckBox1 = findViewById(R.id.checkbox_skill1);
        if (skillCheckBox1.isChecked()) {
            allSkills.add(skillCheckBox1.getText().toString());
        }

        // Other checkboxes
        // ...
        TextView textInDialog = findViewById(R.id.edit_custom_text);
        // more code
    }
</code>```

When I run it I get the following error:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
</code>```

From previous threads I learn that those checkboxes and edittext are in the dialog so I can't get them from the MainActivity. What is the best way there to change so it will work?

答:
you need link the view to your checkbox</p>

```<code>CheckBox skillCheckBox1 = view.findViewById(R.id.checkbox_skill1);
</code>```

Body:
I have create an EditText button which opens a dialog with bunch of checkboxes and one EditText. In the OnCreate method:

        skillsEditText = findViewById(R.id.edit_skills);
        skillsEditText.setClickable(true);
        skillsEditText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_skills,null);
                mBuilder.setView(mView);
                specialSkillsDialog = mBuilder.create();
                specialSkillsDialog.setCanceledOnTouchOutside(false);
                specialSkillsDialog.show();
            }
        });

After the users clicks Done, I execute the onDoneClick method:

    public void onProfessionsDoneClick(View view) {
        CheckBox skillCheckBox1 = findViewById(R.id.checkbox_skill1);
        if (skillCheckBox1.isChecked()) {
            allSkills.add(skillCheckBox1.getText().toString());
        }

        // Other checkboxes
        // ...
        TextView textInDialog = findViewById(R.id.edit_custom_text);
        // more code
    }

When I run it I get the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference

From previous threads I learn that those checkboxes and edittext are in the dialog so I can't get them from the MainActivity. What is the best way there to change so it will work?

Body:
you need link the view to your checkbox

CheckBox skillCheckBox1 = view.findViewById(R.id.checkbox_skill1);


问:
How to handle streaming data using fetch?
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.

This works great to async'ly handle chunks of output streaming from a process:

```<code>for await (const out of proc.child.stdout) {
  ...
}
</code>```

(in an async function context here of course)

I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.

```<code>for await (const chunk of (await fetch('/data.jsonl')).body) {
  console.log('got', chunk);
}
</code>```

This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).

For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.

I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?

If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?

答:
Unfortunately async iterable support is not yet implemented, despite being in the spec. Instead you can manually iterate, as shown in this example from the spec. (I'll convert examples to async/await for you in this answer.)

const reader = response.body.getReader();
const { value, done } = await reader.read();

if (done) {
  console.log("The stream was already closed!");
} else {
  console.log(value);
}
```
<p>You can use recursion or a loop to do this repeatedly, as in this other example:</p>
<pre class="lang-js prettyprint-override"><code>async function readAllChunks(readableStream) {
  const reader = readableStream.getReader();
  const chunks = [];

  let done, value;
  while (!done) {
    ({ value, done } = await reader.read());
    if (done) {
      return chunks;
    }
    chunks.push(value);
  }
}

console.log(await readAllChunks(response.body));
</code>```

Body:
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.

This works great to async'ly handle chunks of output streaming from a process:

for await (const out of proc.child.stdout) {
  ...
}

(in an async function context here of course)

I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.

for await (const chunk of (await fetch('/data.jsonl')).body) {
  console.log('got', chunk);
}

This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).

For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.

I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?

If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?

Body:
Unfortunately async iterable support is not yet implemented, despite being in the spec. Instead you can manually iterate, as shown in this example from the spec. (I'll convert examples to async/await for you in this answer.)

const reader = response.body.getReader();
const { value, done } = await reader.read();

if (done) {
  console.log("The stream was already closed!");
} else {
  console.log(value);
}

You can use recursion or a loop to do this repeatedly, as in this other example:

async function readAllChunks(readableStream) {
  const reader = readableStream.getReader();
  const chunks = [];

  let done, value;
  while (!done) {
    ({ value, done } = await reader.read());
    if (done) {
      return chunks;
    }
    chunks.push(value);
  }
}

console.log(await readAllChunks(response.body));


问:
Running a PHP with a HTML button click
I am setting up a basic webpage that will perform a stress test and simulate a load on my web server.  The stress PHP works, but when I click the button nothing happens.

```<code><?php

$urlRoot="http://169.254.169.254/latest/meta-data/";
$instance = file_get_contents($urlRoot . 'instance-id');
$az = file_get_contents($urlRoot . 'placement/availability-zone');
?>
<center>This page was generated by instance <b><?= $instance ?></b> in Availability Zone
<b>.   <?= $az ?></b>.</center>
<form action="stress.php" method="get">
<input type="submit" value="Buy A lot">
</form>
</code>```

Here is the stress php as well

```<code><?php
$output = shell_exec('stress --cpu 8 --timeout 120 > output.txt &');
echo "```$output```";
?>
</code>```

答:
Style your input like this:
<input type="submit" value="Buy A lot" name="clickme">

Than put the following code in your php text outside of any function:

```<code><?php
if(array_key_exists('clickme',$_POST)){
    functionToExecute();
}
?>
</code>```

Put all the stuff you want to execute if the button get clicked in a function, and insert the function-name instead of "functionToExecute".

Title: Running a PHP with a HTML button click

Body:
I am setting up a basic webpage that will perform a stress test and simulate a load on my web server.  The stress PHP works, but when I click the button nothing happens.

<?php

$urlRoot="http://169.254.169.254/latest/meta-data/";
$instance = file_get_contents($urlRoot . 'instance-id');
$az = file_get_contents($urlRoot . 'placement/availability-zone');
?>
This page was generated by instance <?= $instance ?> in Availability Zone
.   <?= $az ?>.
<form action="stress.php" method="get">
<input type="submit" value="Buy A lot">
</form>

Here is the stress php as well

<?php
$output = shell_exec('stress --cpu 8 --timeout 120 > output.txt &');
echo "
$output
";
?>

Body:
Style your input like this:
<input type="submit" value="Buy A lot" name="clickme">

Than put the following code in your php text outside of any function:

<?php
if(array_key_exists('clickme',$_POST)){
    functionToExecute();
}
?>

Put all the stuff you want to execute if the button get clicked in a function, and insert the function-name instead of "functionToExecute".


问:
How to add external jar or zip file in the Blackberry project
I want to add a jar file to my BlackBerry project. I have tried adding the jar file by the following manner ->

Right click on project  -> properties -> Build -> Imported jar files -> Add

But after that, whenever I try to run the application I get "Module abc.jar not found error".

How do I add a jar file to a BlackBerry project?

答: Right click on project->BuildPath->Libraries->Addexternaljar and then press ok it will solved your problem it is for if you are using eclipseplugins.you can see the details here


问:
LiveData's Transformations.map not being triggered in, and only in, Unit Tests
I have a ViewModel like this one:

class MyViewModel {
    val title = MutableLiveData<String>()
    val onTitleError: LiveData<Int?> = Transformations.map(title, this::validateTitle)
}
```

<p>The problem is when executing during Unit Tests <code>Transformations.map</code> is never triggered by a <code>title</code> value change. As example:</p>

<pre class="lang-kotlin prettyprint-override"><code>val viewModel = MyViewModel()
viewModel.title.value = "123"

Assert.assertEquals(viewModel.onTitleError.value, R.string.myError)
</code>```

I'm using this rule for LiveData tests:

@Rule
var liveDataRule: TestRule = InstantTaskExecutorRule()
```

<p>When executing during Instrumented Tests, or normal running, everything works just fine.</p>

<p>Just exemplifying @ianhanniballake answer, i just added <code>viewModel.onTitleError.observeForever { }</code>, then above snippet should look like this:</p>

<pre class="lang-kotlin prettyprint-override"><code>val viewModel = MyViewModel()

viewModel.onTitleError.observeForever { }
viewModel.title.value = "123"

Assert.assertEquals(viewModel.onTitleError.value, R.string.myError)
</code>```

答: You need to observe your onTitleError LiveData to have it populate its value.

Body:
I have a ViewModel like this one:

class MyViewModel {
    val title = MutableLiveData<String>()
    val onTitleError: LiveData<Int?> = Transformations.map(title, this::validateTitle)
}

The problem is when executing during Unit Tests Transformations.map is never triggered by a title value change. As example:

val viewModel = MyViewModel()
viewModel.title.value = "123"

Assert.assertEquals(viewModel.onTitleError.value, R.string.myError)

I'm using this rule for LiveData tests:

@Rule
var liveDataRule: TestRule = InstantTaskExecutorRule()

When executing during Instrumented Tests, or normal running, everything works just fine.

Just exemplifying @ianhanniballake answer, i just added viewModel.onTitleError.observeForever { }, then above snippet should look like this:

val viewModel = MyViewModel()

viewModel.onTitleError.observeForever { }
viewModel.title.value = "123"

Assert.assertEquals(viewModel.onTitleError.value, R.string.myError)


问:
Need to add multiple items in list - decision table - Drools
I need to create a new multiple instance of objects for the Pojo class in drools decision table. I have implemented using two facts Student fact and subject fact class. I need to fire all the rules in the decision table and I need to add all the values into array-list of the objects. But I'm getting only last rule values of decision table. It seems like decision table values are getting overridden.

Fact 1

```<code>Class StudentFact{

 private int id;
 private String name;
 private List<SubejctFact> subjectList;

 public void setId(int id){
    this.id = id;
 }

 public int getId(){
    return id;
 }

 public void setName(String name){
    this.Name = name;
 }

 public String getName(){
    return name;
 }

     public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public int getSubjectList() {
        return subjectList;
    }

}
</code>```

Fact 2

```<code>Class SubjectFact{
 private int subId;
 private String subjectName;

 public void setSubId(int subId){
     this.subId= subId;
 }

 public int getSubId(){
   return subId;
 }

 public void setSubjectName(String subjectName){
      this.subjectName = subjectName;
 }

 public int getSubejctName(){
      return subjectName;
 }

}
</code>```

Current Response

```<code>{
  "id":123,
  "name": "xyz",
  "subjectList": [
     {
        "id": 6,
        "name":"Hindi"
     },
     {
        "id": 6,
        "name":"Hindi"
     }
}
</code>```

Expected Response

```<code> {
      "id":123,
      "name": "xyz",
      "subjectList": [
         {
            "id": 5,
            "name":"English"
         },
         {
            "id": 6,
            "name":"Hindi"
         }
    }
</code>```

My Decision Table  looks like

Any one pls advise to achieve the expected response?

答:
Each row in a table becomes a rule, each action column becomes a row in then block.

For each rule you need a statement to create Subject, statements to populate it and statement to add it to matching student.

Values in 'CREATE' and 'COLLECT' are needed, otherwise action will be skipped.

; is required in a cell without 'target object' and it is not required when you provide '$subject' and '$student' objects. Don't ask me why. Just analyzed generated drl.

You may want to hide two 'technical columns'.

This will generate two rules like below

```<code>package draft;
//generated from Decision Table
import draft.Student;
import draft.Subject;
// rule values at A9, header at A4
rule "Rule 1"
    when
        $student:Student(id == "123")
    then
        Subject $subject = new Subject();
        $subject.setSubId(5);
        $subject.setSubjectName('English');
        $student.addSubject($subject);
end

// rule values at A10, header at A4
rule "Rule 2"
    when
        $student:Student(id == "123")
    then
        Subject $subject = new Subject();
        $subject.setSubId(6);
        $subject.setSubjectName('Hindi');
        $student.addSubject($subject);
end
</code>```

PS: I was struggling with " being automatically replaced by Calc editor to `` which was not valid symbol for drools parser, so I used single quotes, which appeared to be special symbol at the start of a cell in the editor and skipped. So actual cell value which finally worked for me was ''English'.

Here are my models

```<code>public class Student {
    private int id;
    private String name;
    private List<Subject> subjectList = new ArrayList<>();

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void addSubject(Subject subject) {
        subjectList.add(subject);
    }

    public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public List<Subject> getSubjectList() {
        return subjectList;
    }
}

public class Subject {
    private int subId;
    private String subjectName;

    public void setSubId(int subId) {
        this.subId = subId;
    }

    public int getSubId() {
        return subId;
    }

    public void setSubjectName(String subjectName) {
        this.subjectName = subjectName;
    }

    public String getSubejctName() {
        return subjectName;
    }
}
</code>```

test

```<code>@DroolsSession(resources = "draft/ApplicableSubjects.xls",
        builderProperties = "drools.dump.dir = target/dump")
public class PlaygroundTest {

    @Rule
    public DroolsAssert drools = new DroolsAssert();

    @Test
    public void testIt() {
        drools.insertAndFire(new Student(123, "Student 123"));
        drools.printFacts();
    }
}
</code>```

test output

```<code>00:00:00 --> inserted: Student[id=123,name=Student 123,subjectList=[]]
00:00:00 --> fireAllRules
00:00:00 <-- 'Rule 1' has been activated by the tuple [Student]
00:00:00 <-- 'Rule 2' has been activated by the tuple [Student]
00:00:00 Facts (1):
Student[id=123,name=Student 123,subjectList=[draft.Subject@1ded7b14, draft.Subject@29be7749]]
</code>```

Body:
I need to create a new multiple instance of objects for the Pojo class in drools decision table. I have implemented using two facts Student fact and subject fact class. I need to fire all the rules in the decision table and I need to add all the values into array-list of the objects. But I'm getting only last rule values of decision table. It seems like decision table values are getting overridden.

Fact 1

Class StudentFact{

 private int id;
 private String name;
 private List<SubejctFact> subjectList;

 public void setId(int id){
    this.id = id;
 }

 public int getId(){
    return id;
 }

 public void setName(String name){
    this.Name = name;
 }

 public String getName(){
    return name;
 }

     public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public int getSubjectList() {
        return subjectList;
    }

}

Fact 2

Class SubjectFact{
 private int subId;
 private String subjectName;

 public void setSubId(int subId){
     this.subId= subId;
 }

 public int getSubId(){
   return subId;
 }

 public void setSubjectName(String subjectName){
      this.subjectName = subjectName;
 }

 public int getSubejctName(){
      return subjectName;
 }

}

Current Response

{
  "id":123,
  "name": "xyz",
  "subjectList": [
     {
        "id": 6,
        "name":"Hindi"
     },
     {
        "id": 6,
        "name":"Hindi"
     }
}

Expected Response

 {
      "id":123,
      "name": "xyz",
      "subjectList": [
         {
            "id": 5,
            "name":"English"
         },
         {
            "id": 6,
            "name":"Hindi"
         }
    }

My Decision Table  looks like

Any one pls advise to achieve the expected response?

Body:
Each row in a table becomes a rule, each action column becomes a row in then block.

For each rule you need a statement to create Subject, statements to populate it and statement to add it to matching student.

Values in 'CREATE' and 'COLLECT' are needed, otherwise action will be skipped.

; is required in a cell without 'target object' and it is not required when you provide '$subject' and '$student' objects. Don't ask me why. Just analyzed generated drl.

You may want to hide two 'technical columns'.

This will generate two rules like below

package draft;
//generated from Decision Table
import draft.Student;
import draft.Subject;
// rule values at A9, header at A4
rule "Rule 1"
    when
        $student:Student(id == "123")
    then
        Subject $subject = new Subject();
        $subject.setSubId(5);
        $subject.setSubjectName('English');
        $student.addSubject($subject);
end

// rule values at A10, header at A4
rule "Rule 2"
    when
        $student:Student(id == "123")
    then
        Subject $subject = new Subject();
        $subject.setSubId(6);
        $subject.setSubjectName('Hindi');
        $student.addSubject($subject);
end

PS: I was struggling with " being automatically replaced by Calc editor to `` which was not valid symbol for drools parser, so I used single quotes, which appeared to be special symbol at the start of a cell in the editor and skipped. So actual cell value which finally worked for me was ''English'.

Here are my models

public class Student {
    private int id;
    private String name;
    private List<Subject> subjectList = new ArrayList<>();

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void addSubject(Subject subject) {
        subjectList.add(subject);
    }

    public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public List<Subject> getSubjectList() {
        return subjectList;
    }
}

public class Subject {
    private int subId;
    private String subjectName;

    public void setSubId(int subId) {
        this.subId = subId;
    }

    public int getSubId() {
        return subId;
    }

    public void setSubjectName(String subjectName) {
        this.subjectName = subjectName;
    }

    public String getSubejctName() {
        return subjectName;
    }
}

test

@DroolsSession(resources = "draft/ApplicableSubjects.xls",
        builderProperties = "drools.dump.dir = target/dump")
public class PlaygroundTest {

    @Rule
    public DroolsAssert drools = new DroolsAssert();

    @Test
    public void testIt() {
        drools.insertAndFire(new Student(123, "Student 123"));
        drools.printFacts();
    }
}

test output

00:00:00 --> inserted: Student[id=123,name=Student 123,subjectList=[]]
00:00:00 --> fireAllRules
00:00:00 <-- 'Rule 1' has been activated by the tuple [Student]
00:00:00 <-- 'Rule 2' has been activated by the tuple [Student]
00:00:00 Facts (1):
Student[id=123,name=Student 123,subjectList=[draft.Subject@1ded7b14, draft.Subject@29be7749]]


问:
Build json from ValueObjects in Rails 3?
i was wondering how i can build a json response from a value object?

Situation?

I want to return clear json, only the field i need in the front-end. Which means: All associations should be included in the json. But again: only the fields I need. This i why i would like to use a special value object (defining the field) on top of my models.

Problem?

Is this a good idea? How to build value objects (VOs) with rails?

Thanks for helping

答:
Of course it's possible. Look here:

Here is an example:

```<code>konata.to_json(:only => [ :id, :name ])
# => {"id": 1, "name": "Konata Izumi"}
</code>```

As you're talking about associations:

```<code>konata.to_json(:include => :posts)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
  "created_at": "2006/08/01", "awesome": true,
  "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
            {"id": 2, author_id: 1, "title": "So I was thinking"}]}
</code>```

Body:
Of course it's possible. Look here:

Here is an example:

konata.to_json(:only => [ :id, :name ])
# => {"id": 1, "name": "Konata Izumi"}

As you're talking about associations:

konata.to_json(:include => :posts)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
  "created_at": "2006/08/01", "awesome": true,
  "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
            {"id": 2, author_id: 1, "title": "So I was thinking"}]}