问:
Sending multiple attachements dynamically using nodemailer
I am trying to use nodemailer to send emails in nodejs. Currently I configured handlebars as the template and use nodemailer-express-handlebars as the template engine. I wanted to dynamically read the files that are available in my upload folder and send them as attachments. But I could not figure out how. Please help me  out

```<code>import { FeedbackFileEntity } from
 '../../shared/entities/feedback.file.entity';
import hbs = require('nodemailer-express-handlebars');

import fs = require('fs');
import { getConnection } from 'typeorm';
import { DaoException } from '../../shared/exceptionHandler/dao.exception';
import { AppEnvServiceInstance } from
     '../../shared/services/app.env.service';
import nodemailer = require('nodemailer');
import * as path from 'path';
import { promisify } from 'util';

// This is the router to upload files to database
// this works fine
export const feedbackFileUploadDataLayer = async(fileMeta, fileBody) => {
    console.log('file buffer is', fileMeta);
    console.log('file meta path', fileMeta.path);

    fileEntity.$fileName = fileBody.fileName;
    const manager =  await getConnection('postgresConnection').manager;
    console.log('before triggering save');
    return new Promise((resolve, reject) => {
        manager.save(fileEntity).then(data => {
            console.log('Saved the data successfully', data);
            resolve('Saved the fileContent');
        }).catch(err => {
            console.log('error saving thge data', err);
            reject(new DaoException(481, 'Error in saving the file',
           'DaoException'));
        });
    });

};

// this is the place where I will be implementing logic to generate new
  files
// currently I am trying to read the files that was uploaded above from
 ./uploads folder
export const generateFilesAndEmailDataLayer = async () => {

    console.log('inside data layer');
    // console.log("Preview URL: %s",
    nodemailer.getTestMessageUrl(transportObject));
    const result = sendEmail();
    console.log('returned result', result);
    return result;
};

const sendEmail = () => {

    // create mail account -  in ethereal
    const accnt = {
        user: 'XXXX',
        pass: 'XXXXX'
    }

    // configure smptp
    const transport = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false,
        auth: {
           user: accnt.user,
           pass: accnt.pass
        }
    });
    const emailTemplateOptions = {
        defaultLayout: 'email.default',
        layoutDir:
  path.resolve(__dirname+'./../../../../views/email/layouts/'),
        partialsDir:
   path.resolve(__dirname+'./../../../../views/email/partials/'),
        extName: 'hbs'
    }
    let options = {
        viewEngine: {

            extname: '.handlebars',
            layoutsDir:
    path.resolve(__dirname+'./../../../../views/email/'),
            defaultLayout : 'template',
            partialsDir :
    path.resolve(__dirname+'./../../../../views/email/partials/')
        },
        viewPath: path.resolve(__dirname+'./../../../../views/email/'),
        extName: '.handlebars'

    };

    transport.use('compile', hbs(options));
    var mail = {
        from: 'XXXX',
        to:

   AppEnvServiceInstance.getConfigurationSettings().$SMTP_MAIL_RECEIPIENTS,
        subject: 'Feedback Generated Files',
        template: 'email.body',
        attachments: fileArrayFunction,
        context: {
            variable1 : 'value1',
            variable2 : 'value2',
            array1: ['JOhn', 'som', 'tet']
       }
     }
    console.log('evfore sending email', fileArrayFunction);

        transport.sendMail(mail, (err, info) => {
            if(!err) {
                console.log('info', info);
                return(info);
            }else {
                console.log('err', err);
                return(err);
            }
        });

    // e
}

const fileArrayFunction =  () => {
    const dirPath = path.join(__dirname+'./../../../../assests/uploads/');
    const filesArray = [];
    const rAsync = promisify(fs.readFile);
    const rAsyncDir = promisify(fs.readdir);
    // return new Promise((resolve, reject) => {
    //     rAsyncDir(dirPath).then(data => {
    //         console.log('durectory parth read', data);
    //         data.array.forEach(element => {
    //             console.log('each element is', element);
    //             rAsync(element).then(content => {
    //                 filesArray.push({fileName: element,
    content:content});
    //             })
    //         });
    //         resolve(filesArray);
    //     }).catch(err => {
    //         console.log(err);
    //         reject(err);
    //     });
    // });
    fs.readdirSync(dirPath).forEach(item => {
        console.log('each item dur', item);
        const content = fs.readFileSync(dirPath+item);
        filesArray.push({filename: item, content:content});
    })

    return filesArray;
}
</code>```

The partials directory , the default layput all work fine. They are very basic. Here is the main email template
email.body.handlebars

```<code><h4>Main Body Here</h4>
{{variable1}} <br/>
{{variable2}}
</code>```

I could send email without attachments, but if you add this file , you could see that there is a compile time error stating that transport.sendEmail() cannot make use of mail constant because it contains attachments as a function and not a constant array. Please help me on this. I would want to read the files as they grow and send it out dynamically

答:
I found the answer to it.

So I write a util service like this

```<code>retrieveMailConstants(data) {
        this.mailConstants = {
            from: 'a634885.fmr.com',
            to: AppEnvServiceInstance.getConfigurationSettings().$SMTP_MAIL_RECEIPIENTS,
            subject: 'Test files - Feedback Generated Files',
            template: 'email.body',
            attachments: data,
            context: {
                variable1 : 'value1',
                variable2 : 'value2',
                array1: ['JOhn', 'som', 'tet']
           }
         }

         return this.mailConstants;
    }
</code>```

Now the data to the attachments property should be a resolved data either a Promise resolved one or an observable resolved array of data. I chose to use observables.
Now my use case is that I need to generate many files based on the configuration info from DB and store those generated files either in DB or in a seperate server. For now I chose to save them in the local disk. Then I read all the files from the location , save that in an array and finally push that array to the behavior subject

(Note that I have written them in ts, You can easily convert that to a js file or transpile them)

```<code>import * as path from 'path';
import { Attachment } from 'nodemailer/lib/mailer';
import * as fs from 'fs';
import * as _ from 'lodash';
import { NodemailerAttachmentModel } from '../models/nodemailer.attachment.model';
import { BehaviorSubject, Observable, of, ConnectableObservable } from 'rxjs';
import {tap, map, filter, switchMap, share, publish, refCount, last, shareReplay}
 from 'rxjs/operators';

let fileAttachmentSubject = new BehaviorSubject<Attachment[]>([]);

export const readFilesAndCreateAttachments = () => {
    console.log('ibside create attachments');
    console.log('dirname', __dirname);
    const dirPath = path.join(__dirname+'./../../../../assests/uploads/');
    console.log('dirparh is', dirPath);
    const filesArray =  new Array<Attachment>();
    const fileList = fs.readdirSync(dirPath);
    console.log('filelist is', fileList);
    _.each(fileList, (filePath, i) => {
        console.log('filepath in each is', filePath, 'index is', i, 'filelist each index', fileList[i]);
        if(i+1 >= fileList.length){
            // then it reached the end, time to call the observable list
            console.log('before sending', filesArray);
            setBehaviorSubject(filesArray);
        } else {
            console.log('path to read file is', dirPath+fileList[i]);
            fs.readFile(dirPath+fileList[i], (err, data) => {
                if(!err){
                    const fileInDir = new NodemailerAttachmentModel;
                    fileInDir.$content = data;
                    fileInDir.$filename = filePath;
                    filesArray.push(fileInDir);
                    console.log('inside else', filesArray.length, i,
               fileList.length);
                }
            });

        }
    });
};

export const setBehaviorSubject = (filesArray: Attachment[]) => {
 //fileAttachmentObs = from(filesArray).;
 fileAttachmentSubject.next(filesArray);
 console.log('subject is set', filesArray.length);
}

export const getBehaviorSubject = () => {
    console.log('call to get subject');
    return fileAttachmentSubject.asObservable();
}
</code>```

Now I make use of the transport configured mail options to send an email. The transport configuration is not shown here. It is a basic config info which can be obtained from the nodemailer site

```<code>getBehaviorSubject().subscribe(data => {
            console.log('data subscribed from subject', data);
            console.log('only then going to mail');
            let mailOptions  = nodemailerConstantInstance.retrieveMailConstants(data);

            console.log('before sending email');
            transport.sendMail(mailOptions, (err, info) => {
            if(!err) {
                console.log('info', info);
                resolve(info);
            }else {
                console.log('err', err);
                reject(err);
            }
        });
</code>```

Hope it is of beneficial to someone.

Body:
I am trying to use nodemailer to send emails in nodejs. Currently I configured handlebars as the template and use nodemailer-express-handlebars as the template engine. I wanted to dynamically read the files that are available in my upload folder and send them as attachments. But I could not figure out how. Please help me  out

import { FeedbackFileEntity } from
 '../../shared/entities/feedback.file.entity';
import hbs = require('nodemailer-express-handlebars');

import fs = require('fs');
import { getConnection } from 'typeorm';
import { DaoException } from '../../shared/exceptionHandler/dao.exception';
import { AppEnvServiceInstance } from
     '../../shared/services/app.env.service';
import nodemailer = require('nodemailer');
import * as path from 'path';
import { promisify } from 'util';

// This is the router to upload files to database
// this works fine
export const feedbackFileUploadDataLayer = async(fileMeta, fileBody) => {
    console.log('file buffer is', fileMeta);
    console.log('file meta path', fileMeta.path);

    fileEntity.$fileName = fileBody.fileName;
    const manager =  await getConnection('postgresConnection').manager;
    console.log('before triggering save');
    return new Promise((resolve, reject) => {
        manager.save(fileEntity).then(data => {
            console.log('Saved the data successfully', data);
            resolve('Saved the fileContent');
        }).catch(err => {
            console.log('error saving thge data', err);
            reject(new DaoException(481, 'Error in saving the file',
           'DaoException'));
        });
    });

};

// this is the place where I will be implementing logic to generate new
  files
// currently I am trying to read the files that was uploaded above from
 ./uploads folder
export const generateFilesAndEmailDataLayer = async () => {

    console.log('inside data layer');
    // console.log("Preview URL: %s",
    nodemailer.getTestMessageUrl(transportObject));
    const result = sendEmail();
    console.log('returned result', result);
    return result;
};

const sendEmail = () => {

    // create mail account -  in ethereal
    const accnt = {
        user: 'XXXX',
        pass: 'XXXXX'
    }

    // configure smptp
    const transport = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false,
        auth: {
           user: accnt.user,
           pass: accnt.pass
        }
    });
    const emailTemplateOptions = {
        defaultLayout: 'email.default',
        layoutDir:
  path.resolve(__dirname+'./../../../../views/email/layouts/'),
        partialsDir:
   path.resolve(__dirname+'./../../../../views/email/partials/'),
        extName: 'hbs'
    }
    let options = {
        viewEngine: {

            extname: '.handlebars',
            layoutsDir:
    path.resolve(__dirname+'./../../../../views/email/'),
            defaultLayout : 'template',
            partialsDir :
    path.resolve(__dirname+'./../../../../views/email/partials/')
        },
        viewPath: path.resolve(__dirname+'./../../../../views/email/'),
        extName: '.handlebars'

    };

    transport.use('compile', hbs(options));
    var mail = {
        from: 'XXXX',
        to:

   AppEnvServiceInstance.getConfigurationSettings().$SMTP_MAIL_RECEIPIENTS,
        subject: 'Feedback Generated Files',
        template: 'email.body',
        attachments: fileArrayFunction,
        context: {
            variable1 : 'value1',
            variable2 : 'value2',
            array1: ['JOhn', 'som', 'tet']
       }
     }
    console.log('evfore sending email', fileArrayFunction);

        transport.sendMail(mail, (err, info) => {
            if(!err) {
                console.log('info', info);
                return(info);
            }else {
                console.log('err', err);
                return(err);
            }
        });

    // e
}

const fileArrayFunction =  () => {
    const dirPath = path.join(__dirname+'./../../../../assests/uploads/');
    const filesArray = [];
    const rAsync = promisify(fs.readFile);
    const rAsyncDir = promisify(fs.readdir);
    // return new Promise((resolve, reject) => {
    //     rAsyncDir(dirPath).then(data => {
    //         console.log('durectory parth read', data);
    //         data.array.forEach(element => {
    //             console.log('each element is', element);
    //             rAsync(element).then(content => {
    //                 filesArray.push({fileName: element,
    content:content});
    //             })
    //         });
    //         resolve(filesArray);
    //     }).catch(err => {
    //         console.log(err);
    //         reject(err);
    //     });
    // });
    fs.readdirSync(dirPath).forEach(item => {
        console.log('each item dur', item);
        const content = fs.readFileSync(dirPath+item);
        filesArray.push({filename: item, content:content});
    })

    return filesArray;
}

The partials directory , the default layput all work fine. They are very basic. Here is the main email template
email.body.handlebars

Main Body Here

{{variable1}}

{{variable2}}

I could send email without attachments, but if you add this file , you could see that there is a compile time error stating that transport.sendEmail() cannot make use of mail constant because it contains attachments as a function and not a constant array. Please help me on this. I would want to read the files as they grow and send it out dynamically

Body:
I found the answer to it.

So I write a util service like this

retrieveMailConstants(data) {
        this.mailConstants = {
            from: 'a634885.fmr.com',
            to: AppEnvServiceInstance.getConfigurationSettings().$SMTP_MAIL_RECEIPIENTS,
            subject: 'Test files - Feedback Generated Files',
            template: 'email.body',
            attachments: data,
            context: {
                variable1 : 'value1',
                variable2 : 'value2',
                array1: ['JOhn', 'som', 'tet']
           }
         }

         return this.mailConstants;
    }

Now the data to the attachments property should be a resolved data either a Promise resolved one or an observable resolved array of data. I chose to use observables.
Now my use case is that I need to generate many files based on the configuration info from DB and store those generated files either in DB or in a seperate server. For now I chose to save them in the local disk. Then I read all the files from the location , save that in an array and finally push that array to the behavior subject

(Note that I have written them in ts, You can easily convert that to a js file or transpile them)

import * as path from 'path';
import { Attachment } from 'nodemailer/lib/mailer';
import * as fs from 'fs';
import * as _ from 'lodash';
import { NodemailerAttachmentModel } from '../models/nodemailer.attachment.model';
import { BehaviorSubject, Observable, of, ConnectableObservable } from 'rxjs';
import {tap, map, filter, switchMap, share, publish, refCount, last, shareReplay}
 from 'rxjs/operators';

let fileAttachmentSubject = new BehaviorSubject<Attachment[]>([]);

export const readFilesAndCreateAttachments = () => {
    console.log('ibside create attachments');
    console.log('dirname', __dirname);
    const dirPath = path.join(__dirname+'./../../../../assests/uploads/');
    console.log('dirparh is', dirPath);
    const filesArray =  new Array<Attachment>();
    const fileList = fs.readdirSync(dirPath);
    console.log('filelist is', fileList);
    _.each(fileList, (filePath, i) => {
        console.log('filepath in each is', filePath, 'index is', i, 'filelist each index', fileList[i]);
        if(i+1 >= fileList.length){
            // then it reached the end, time to call the observable list
            console.log('before sending', filesArray);
            setBehaviorSubject(filesArray);
        } else {
            console.log('path to read file is', dirPath+fileList[i]);
            fs.readFile(dirPath+fileList[i], (err, data) => {
                if(!err){
                    const fileInDir = new NodemailerAttachmentModel;
                    fileInDir.$content = data;
                    fileInDir.$filename = filePath;
                    filesArray.push(fileInDir);
                    console.log('inside else', filesArray.length, i,
               fileList.length);
                }
            });

        }
    });
};

export const setBehaviorSubject = (filesArray: Attachment[]) => {
 //fileAttachmentObs = from(filesArray).;
 fileAttachmentSubject.next(filesArray);
 console.log('subject is set', filesArray.length);
}

export const getBehaviorSubject = () => {
    console.log('call to get subject');
    return fileAttachmentSubject.asObservable();
}

Now I make use of the transport configured mail options to send an email. The transport configuration is not shown here. It is a basic config info which can be obtained from the nodemailer site

getBehaviorSubject().subscribe(data => {
            console.log('data subscribed from subject', data);
            console.log('only then going to mail');
            let mailOptions  = nodemailerConstantInstance.retrieveMailConstants(data);

            console.log('before sending email');
            transport.sendMail(mailOptions, (err, info) => {
            if(!err) {
                console.log('info', info);
                resolve(info);
            }else {
                console.log('err', err);
                reject(err);
            }
        });

Hope it is of beneficial to someone.


来源: stackexchange

问:
Scaffold-DbContext Error "Login failed for user MicrosoftAccount\my_email@gmail.com"
Trying to execute this command in Visual Studio Package Manager Console:

Scaffold-DbContext "Server=my_server\SQLEXPRESS;Database=FoodStore;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

but I'm getting this error:

Cannot open database "FoodStore" requested by the login. The login
  failed. Login failed for user 'MicrosoftAccount\my_email@gmail.com'.

I've tried creating a login in Security for 'MicrosoftAccount\my_email@gmail.com' as db_owner in Microsoft SQL Management Service Studio, as well as signing in with local accounts instead, but I'm still getting an error in Visual Studio when running Scaffold-DbContext.

答:
I encountered the same issue as you have mentioned i.e.

Cannot open database "dbxxxxx" requested by the login. The login failed.
Login failed for user 'xxxxx\xxx'.

And after working around with it, I found that I had to carefully check the value of
 server attribute.

"Server=.\SQLEXPRESS;Database=FoodStore;Trusted_Connection=True;" also works well.

ContentLicense: CC BY-SA 4.0


问:
How to attach 2 different images in mail
```<code>if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] ==  UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);}
</code>```

this is the code im using for uploading the first image, this code is working and im getting the attachment in main but how to do it for second image.

答:
As mentioned in comments you are using PHPMailer so you can do it like this:

```<code> $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);}

 $mail->AddAttachment($_FILES['uploaded_file2']['tmp_name'],
                         $_FILES['uploaded_file2']['name']);}
</code>```

you can follow this sample:
How to send multiple attachment in single mail in php

Body:
if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] ==  UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);}

this is the code im using for uploading the first image, this code is working and im getting the attachment in main but how to do it for second image.

Body:
As mentioned in comments you are using PHPMailer so you can do it like this:

 $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);}

 $mail->AddAttachment($_FILES['uploaded_file2']['tmp_name'],
                         $_FILES['uploaded_file2']['name']);}

you can follow this sample:
How to send multiple attachment in single mail in php


问:
Why does multimap allow duplicate key-value pairs?
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

```<code>#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}
</code>```

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?

答:
Multimap only has a predicate ordering the keys. It has no method to determine whether the values are equal. Is value "A" a duplicate of value "a"? Without a second predicate for the values, there's no telling. Therefore, it doesn't even make sense to talk about duplicate values in a multimap.

If you would like a container that stores pairs, and enforces the unique-ness of both parts of the pair, look at boost::multi_index_container. It's very flexible,  but takes a load of arguments as a result.

ContentLicense: CC BY-SA 3.0

Body:
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?


问:
Bootstrap 4 modal div with ID (Guid from C# model)
So basically if I go with:

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#@Model.ID">
<div class="modal fade" id="@Model.ID" tabindex="-1" role="dialog" aria-labelledby="CenterTitle"" aria-hidden="true">
</code>```

it does not work! (ID is public Guid ID { get; set; })
The button does not open the modal window.

If I manually change to something like

```<code> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#id11">
<div class="modal fade" id="id11" tabindex="-1" role="dialog" aria-labelledby="CenterTitle"" aria-hidden="true">
</code>```

it works? Any idea?

答: The problem was that the Guid value sometimes starts with a number and that's a problem for CSS.</p>

Body:
So basically if I go with:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#@Model.ID">

it does not work! (ID is public Guid ID { get; set; })
The button does not open the modal window.

If I manually change to something like

 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#id11">

it works? Any idea?


问:
Amazon Neptune: Node Properties
I have ran the gremlin query and get the result but not able to get each vertex properties.

Here is the query I have ran:

```<code>g.V('a6b575a5-e2d3-334d-aa0b-5aa372d71fc0').outE('member').inV().unfold().toList()
</code>```

Here is the result properties are undefined how to get?

```<code>2019-05-27T01:21:51.292Z    9f82a2ab-4271-406c-9601-0479899ccb61    [ Vertex {
id: '2cb575ab-d398-8a18-4c8c-4d5f6cca6076',
label: 'tribe',
properties: undefined },
Vertex {
id: '5eb575ad-59e5-0878-3d05-297c390b0479',
label: 'tribe',
properties: undefined } ]
</code>```

答:
You should add the valueMap step at the end of the query.</p>

```<code>g.V('a6b575a5-e2d3-334d-aa0b-5aa372d71fc0').outE('member').inV().valueMap(true).toList()

</code>```

Title: Amazon Neptune: Node Properties

Body:
I have ran the gremlin query and get the result but not able to get each vertex properties.

Here is the query I have ran:

g.V('a6b575a5-e2d3-334d-aa0b-5aa372d71fc0').outE('member').inV().unfold().toList()

Here is the result properties are undefined how to get?

2019-05-27T01:21:51.292Z    9f82a2ab-4271-406c-9601-0479899ccb61    [ Vertex {
id: '2cb575ab-d398-8a18-4c8c-4d5f6cca6076',
label: 'tribe',
properties: undefined },
Vertex {
id: '5eb575ad-59e5-0878-3d05-297c390b0479',
label: 'tribe',
properties: undefined } ]

Body:
You should add the valueMap step at the end of the query.

g.V('a6b575a5-e2d3-334d-aa0b-5aa372d71fc0').outE('member').inV().valueMap(true).toList()


问:
.NET Core - FromForm doesn't pick up an IEnumerable<int>
I am trying to pass an ajax call to a REST endpoint. I have set up a DTO, and all parameters work correctly except for the two that are IEnumerbles.

DTO looks like

```<code>public string title{ get; set; }

public IEnumerable<int> idsToSend{ get; set; }

public IEnumerable<IFormFile> AdditionalFiles { get; set; }
</code>```

Controller method looks like

```<code>[FromForm] myGreatDTO dto
</code>```

When I send the request, in my network inspector, I can see that all 3 properties are indeed included in the request, and the content type header is set to multipart/form-data

When I breakpoint in the controller, I can see the DTO come in, but only the title (the single string) is set. Both the array of numbers and array of IFormFiles are set to "Count = 0"

I've tried googling but I can't find anything on this. Thank you for any direction.

EDIT: Here is the request from chromes network inspector as requested:

```<code>Content-Disposition: form-data; name="AdditionalFiles"

[object File]

------WebKitFormBoundaryun80WvPO3VUW6BU8
Content-Disposition: form-data; name="idsToSend"

2,3

------WebKitFormBoundaryun80WvPO3VUW6BU8
Content-Disposition: form-data; name="title"

a title
</code>```

And the content type header

```<code>Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryun80WvPO3VUW6BU8
</code>```

EDIT 2: And the parsed version from chrome inspector

```<code>title: a title
idsToSend: 2,3
AdditionalFiles: [object File]
</code>```

EDIT 3:
I have gotten the idsToSend to work by manually composing those values.

So rather than

```<code>requestObject.append('idsToSend', myvaluesarray);
</code>```

it's a loop that puts out

```<code>requestObject.append('idsToSend[i]', myvaluesarray[i]);
</code>```

So that's great.

However, doing the same with AdditionalFiles does not work. The backend reads the value as "null".

EDIT 4

Here is the front-end angular method that sends this request as requestd

```<code>sendRequest(dto) {
  let url = `${this._profileService.root}/document`;
  let requestObject = new FormData();
  //fill in the base keys
  requestObject.append('Title', dto.Title);

  for (let i = 0; i < dto.ids.length; i++) {
    requestObject.append(`idsToSend[${i}]`, dto.ids[i].toString());
  }
  for (let j = 0; j < dto.AdditionalFiles.length; j++) {
    requestObject.append(`AdditionalFiles[${j}]`, dto.AdditionalFiles[j]);
  }

  return this._http.post(url, requestObject).catch(this.errorHandler);
}
</code>```

答:
IEnumerable<IFormFile> is different from simple fields. Every element within this collection is designed to has its own file name. There's no need to construct a field name like AdditionalFiles[].

Use AdditionalFiles as the field names directly (instead of AdditionalFiles[]), as the type itself already indicates that's a collection type.

```
sendRequest(dto) {
  let url = `${this._profileService.root}/document`;
  let requestObject = new FormData();
  //fill in the base keys
  requestObject.append('Title', dto.Title);

  for (let i = 0; i  < dto.ids.length; i++) {
    requestObject.append(`idsToSend[${i}]`, dto.ids[i].toString());
  }
  for (let j = 0; j < dto.AdditionalFiles.length; j++) {
    <strike>requestObject.append(`AdditionalFiles[${j}]`, dto.AdditionalFiles[j]);</strike>
    <b>requestObject.append(`additionalFiles`, dto.AdditionalFiles[j]);</b>
  }

  return this._http.post(url, requestObject).catch(this.errorHandler);
}
```

Body:
I am trying to pass an ajax call to a REST endpoint. I have set up a DTO, and all parameters work correctly except for the two that are IEnumerbles.

DTO looks like

public string title{ get; set; }

public IEnumerable<int> idsToSend{ get; set; }

public IEnumerable<IFormFile> AdditionalFiles { get; set; }

Controller method looks like

[FromForm] myGreatDTO dto

When I send the request, in my network inspector, I can see that all 3 properties are indeed included in the request, and the content type header is set to multipart/form-data

When I breakpoint in the controller, I can see the DTO come in, but only the title (the single string) is set. Both the array of numbers and array of IFormFiles are set to "Count = 0"

I've tried googling but I can't find anything on this. Thank you for any direction.

EDIT: Here is the request from chromes network inspector as requested:

Content-Disposition: form-data; name="AdditionalFiles"

[object File]

------WebKitFormBoundaryun80WvPO3VUW6BU8
Content-Disposition: form-data; name="idsToSend"

2,3

------WebKitFormBoundaryun80WvPO3VUW6BU8
Content-Disposition: form-data; name="title"

a title

And the content type header

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryun80WvPO3VUW6BU8

EDIT 2: And the parsed version from chrome inspector

title: a title
idsToSend: 2,3
AdditionalFiles: [object File]

EDIT 3:
I have gotten the idsToSend to work by manually composing those values.

So rather than

requestObject.append('idsToSend', myvaluesarray);

it's a loop that puts out

requestObject.append('idsToSend[i]', myvaluesarray[i]);

So that's great.

However, doing the same with AdditionalFiles does not work. The backend reads the value as "null".

EDIT 4

Here is the front-end angular method that sends this request as requestd

sendRequest(dto) {
  let url = `${this._profileService.root}/document`;
  let requestObject = new FormData();
  //fill in the base keys
  requestObject.append('Title', dto.Title);

  for (let i = 0; i < dto.ids.length; i++) {
    requestObject.append(`idsToSend[${i}]`, dto.ids[i].toString());
  }
  for (let j = 0; j < dto.AdditionalFiles.length; j++) {
    requestObject.append(`AdditionalFiles[${j}]`, dto.AdditionalFiles[j]);
  }

  return this._http.post(url, requestObject).catch(this.errorHandler);
}

Body:
IEnumerable<IFormFile> is different from simple fields. Every element within this collection is designed to has its own file name. There's no need to construct a field name like AdditionalFiles[].

Use AdditionalFiles as the field names directly (instead of AdditionalFiles[]), as the type itself already indicates that's a collection type.

sendRequest(dto) {
  let url = `${this._profileService.root}/document`;
  let requestObject = new FormData();
  //fill in the base keys
  requestObject.append('Title', dto.Title);

  for (let i = 0; i  < dto.ids.length; i++) {
    requestObject.append(`idsToSend[${i}]`, dto.ids[i].toString());
  }
  for (let j = 0; j < dto.AdditionalFiles.length; j++) {
    requestObject.append(`AdditionalFiles[${j}]`, dto.AdditionalFiles[j]);
    requestObject.append(`additionalFiles`, dto.AdditionalFiles[j]);
  }

  return this._http.post(url, requestObject).catch(this.errorHandler);
}


问:
Google Assistant - Sign in to Strava
Apologies if this is a newbie question but I'm hoping someone can offer some advice.

I am fulfilling my Google Assistant intents via an Express app.  I would like for users of my action to be able to get and modify data from their Strava account.  Strava supports Google Authentication and I wondered if I could use node libraries such as Passport (https://www.npmjs.com/package/passport-strava-oauth2) to allow users to sign in to their strava account so that my action can make calls for their data?

I have a welcome intent that gets some Google profile data so wondering if I can pass through some details from this response?

```<code>googleApp.intent('Default Welcome Intent', (conv) => {
  conv.ask(new Permission({
    context: 'Hi, can I  get your details from your Google account?',
    permissions: 'NAME'
  }));
});
</code>```

答:
Yes, but probably not in the way you're looking at.

The Permission helper requests access to specific types of information - name and location. You're looking to establish more of an identity relationship (using their email address or Google account).

You can do this using Account Linking.

If you're sure you're using Google Sign In on the Strava side then things are even easier and you can take advantage of Google Sign In for Assistant. With this, once they sign in, your Action will get an Identity Token which you can use to get information including their Google ID and the email address associated with the signed-in Google account. They only need to sign-in once - afterwards, you'll be given an Identity Token whenever they connect.

If your Strava project and your Action are both using the same Google Cloud Project, things get even easier for your users. Once they have signed in on either client, they're signed in on the other one. So you'll know who they are immediately through the Identity Token.

Title: Google Assistant - Sign in to Strava

Body:
Apologies if this is a newbie question but I'm hoping someone can offer some advice.

I am fulfilling my Google Assistant intents via an Express app.  I would like for users of my action to be able to get and modify data from their Strava account.  Strava supports Google Authentication and I wondered if I could use node libraries such as Passport (https://www.npmjs.com/package/passport-strava-oauth2) to allow users to sign in to their strava account so that my action can make calls for their data?

I have a welcome intent that gets some Google profile data so wondering if I can pass through some details from this response?

googleApp.intent('Default Welcome Intent', (conv) => {
  conv.ask(new Permission({
    context: 'Hi, can I  get your details from your Google account?',
    permissions: 'NAME'
  }));
});


问:
How can I fix this warning produced when I run my Test::Unit tests
I'm getting this warning in my Test::Unit output...

```<code>/usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/functional/sessions_controller_test.rb].each { |f| require f }" | unit_diff -u
Loaded suite -e
Started
.../Users/ethan/project/mtc/contactdb/app/views/sessions/new.html.haml:30: warning: multiple values for a block parameter (0 for 1)
    from /usr/local/lib/ruby/gems/1.8/gems/haml-2.0.8/lib/haml/helpers/action_view_mods.rb:142
[...repeated eight times...]
</code>```

I think the relevant part is:

```<code>/contactdb/app/views/sessions/new.html.haml:30: warning:
  multiple values for a block parameter (0 for 1)
</code>```

Looking at my Haml file, I've narrowed it down to this snippet (I think)...

```<code>- form_tag( recover_login_path, :method => 'get') do |f|
  %p
    = text_field_tag :email, '', { :size => '35', :maxlength => '255' }
</code>```

recover_login is a named route.

I looked at the API docs for form_tag. It seems like my code is following what they have in the examples.

答: The form_tag block takes no parameters. So remove the |f| and the warning should go away.

OwnerDisplayName: Ethan

ContentLicense: CC BY-SA 2.5

Body:
I'm getting this warning in my Test::Unit output...

/usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/functional/sessions_controller_test.rb].each { |f| require f }" | unit_diff -u
Loaded suite -e
Started
.../Users/ethan/project/mtc/contactdb/app/views/sessions/new.html.haml:30: warning: multiple values for a block parameter (0 for 1)
    from /usr/local/lib/ruby/gems/1.8/gems/haml-2.0.8/lib/haml/helpers/action_view_mods.rb:142
[...repeated eight times...]

I think the relevant part is:

/contactdb/app/views/sessions/new.html.haml:30: warning:
  multiple values for a block parameter (0 for 1)

Looking at my Haml file, I've narrowed it down to this snippet (I think)...

- form_tag( recover_login_path, :method => 'get') do |f|
  %p
    = text_field_tag :email, '', { :size => '35', :maxlength => '255' }

recover_login is a named route.

I looked at the API docs for form_tag. It seems like my code is following what they have in the examples.

OwnerDisplayName: Sarah Mei


问:
Qt - What is meant by those lines of code
In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:

```<code>#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}
</code>```

Can you just describe those lines of code?

```<code>    Ui::GoToCellDialog ui;
    QDialog *dialog = new QDialog;
    ui.setupUi(dialog);
</code>```

Thanks.

答: It sets up the ui described by an qt ui xml file hosted inside of a dialog window/qdialog.</p>

Body:
In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:

#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}

Can you just describe those lines of code?

    Ui::GoToCellDialog ui;
    QDialog *dialog = new QDialog;
    ui.setupUi(dialog);

Thanks.


问:
Typescript infer parent type based on nested member
Typescript can infer the type of a value based on questions you ask it at if statements. For example, one member of an object can be inferred based on another:

type ChildType = 'a' | 'b';

type Child<T extends ChildType> = T extends 'a' ? { type: 'a', color: 'blue' } : T extends 'b' ? { type: 'b', color: 'red' } : never;

interface Parent<T extends Child<ChildType>> {
    child: T extends Child<infer R> ? Child<R> : never;
}

function test<T extends Parent<Child<any>>>(parent: T) {
    if (parent.child.type === 'a') {
        parent.child.color === 'red'; // complains because should be blue
    }
}
```

<p>However, performing the same check using nested members of a type, it doesn't seem to provide the same effect.</p>

<pre class="lang-js prettyprint-override"><code>type ChildType = 'a' | 'b';

interface BaseParent<T extends Child<ChildType>> {
    child: T;
}

interface Child<T extends ChildType> {
    type: T;
}

type Parent<T extends ChildType>
    = T extends 'a' ? { color: 'blue' } & BaseParent<Child<'a'>>
    : T extends 'b' ? { color: 'red', opacity: 2 } & BaseParent<Child<'b'>>
    : never;

function test<T extends Parent<ChildType>>(parent: T) {
    if (parent.child.type === 'a') {
        parent.color === 'red' // should complain, but doesn't
    }
}
</code>```

This could easily be rectified using type guards, however I'm searching for a way to do this without them.

答:
First things first - having parent data dependency on it's child is propably not proper architecture. Dependencies should go down. You can think about it in the first place. </p>

<p>But if you want, I'd do it something like (I've added animal example to make it easier for me to understand): </p>

```<code>
type AcceptedAnimal = 'dogs' | 'cats';

interface ParentBase {
  accepts: AcceptedAnimal
}

interface Cat {
  meows: boolean;
}

interface Dog {
  race: string;
}

type Parent = DogOwner | CatOwner;

interface DogOwner extends ParentBase {
  animal: Dog
}

interface CatOwner extends ParentBase {
  animal: Cat;
}

function isDogOwner(parent: ParentBase): parent is DogOwner {
  return parent.accepts === 'dogs';
}

function test(parent: Parent) {
  if (isDogOwner(parent)) {
    parent.animal.race; // ok
    return;
  }

  parent.animal.meows; // ok;
}
</code>```

Body:
Typescript can infer the type of a value based on questions you ask it at if statements. For example, one member of an object can be inferred based on another:

type ChildType = 'a' | 'b';

type Child<T extends ChildType> = T extends 'a' ? { type: 'a', color: 'blue' } : T extends 'b' ? { type: 'b', color: 'red' } : never;

interface Parent<T extends Child<ChildType>> {
    child: T extends Child<infer R> ? Child<R> : never;
}

function test<T extends Parent<Child<any>>>(parent: T) {
    if (parent.child.type === 'a') {
        parent.child.color === 'red'; // complains because should be blue
    }
}

However, performing the same check using nested members of a type, it doesn't seem to provide the same effect.

type ChildType = 'a' | 'b';

interface BaseParent<T extends Child<ChildType>> {
    child: T;
}

interface Child<T extends ChildType> {
    type: T;
}

type Parent<T extends ChildType>
    = T extends 'a' ? { color: 'blue' } & BaseParent<Child<'a'>>
    : T extends 'b' ? { color: 'red', opacity: 2 } & BaseParent<Child<'b'>>
    : never;

function test<T extends Parent<ChildType>>(parent: T) {
    if (parent.child.type === 'a') {
        parent.color === 'red' // should complain, but doesn't
    }
}

This could easily be rectified using type guards, however I'm searching for a way to do this without them.

Body:
First things first - having parent data dependency on it's child is propably not proper architecture. Dependencies should go down. You can think about it in the first place.

But if you want, I'd do it something like (I've added animal example to make it easier for me to understand):

type AcceptedAnimal = 'dogs' | 'cats';

interface ParentBase {
  accepts: AcceptedAnimal
}

interface Cat {
  meows: boolean;
}

interface Dog {
  race: string;
}

type Parent = DogOwner | CatOwner;

interface DogOwner extends ParentBase {
  animal: Dog
}

interface CatOwner extends ParentBase {
  animal: Cat;
}

function isDogOwner(parent: ParentBase): parent is DogOwner {
  return parent.accepts === 'dogs';
}

function test(parent: Parent) {
  if (isDogOwner(parent)) {
    parent.animal.race; // ok
    return;
  }

  parent.animal.meows; // ok;
}


问:
PySpark Milliseconds of TimeStamp
I am trying to get the difference between two timestamp columns but the milliseconds is gone.

How to correct this?

```<code>from pyspark.sql.functions import unix_timestamp
timeFmt = "yyyy-MM-dd' 'HH:mm:ss.SSS"

data = [
    (1, '2018-07-25 17:15:06.39','2018-07-25 17:15:06.377'),
    (2,'2018-07-25 11:12:49.317','2018-07-25 11:12:48.883')

]

df = spark.createDataFrame(data, ['ID', 'max_ts','min_ts']).withColumn('diff',F.unix_timestamp('max_ts', format=timeFmt) - F.unix_timestamp('min_ts', format=timeFmt))
df.show(truncate = False)
</code>```

答:
The answer from Tanjin doesn't work when the values are of type timestamp and the milliseconds are round numbers (like 390, 500). Python would cut the 0 at the end and the timestamp from the example would look like this 2018-07-25 17:15:06.39.

The problem is the hardcoded value in F.substring('max_ts', -3, 3). If the 0 at the end is missing then the substring goes wild.

To convert tmpColumn of type timestamp column to tmpLongColumn of type long I used this snippet:

```<code>timeFmt = "yyyy-MM-dd HH:mm:ss.SSS"

df = df \
  .withColumn('tmpLongColumn', F.substring_index('tmpColumn', '.', -1).cast('float')) \
  .withColumn('tmpLongColumn', F.when(F.col('tmpLongColumn') < 100, F.col('tmpLongColumn')*10).otherwise(F.col('tmpLongColumn')).cast('long')) \
  .withColumn('tmpLongColumn', (F.unix_timestamp('tmpColumn', format=timeFmt)*1000 + F.col('tmpLongColumn'))) \
</code>```

The first transformation extracts the substring containing the milliseconds. Next, if the value is less then 100 multiply it by 10. Finally, convert the timestamp and add milliseconds.

Title: PySpark Milliseconds of TimeStamp

Body:
I am trying to get the difference between two timestamp columns but the milliseconds is gone.

How to correct this?

from pyspark.sql.functions import unix_timestamp
timeFmt = "yyyy-MM-dd' 'HH:mm:ss.SSS"

data = [
    (1, '2018-07-25 17:15:06.39','2018-07-25 17:15:06.377'),
    (2,'2018-07-25 11:12:49.317','2018-07-25 11:12:48.883')

]

df = spark.createDataFrame(data, ['ID', 'max_ts','min_ts']).withColumn('diff',F.unix_timestamp('max_ts', format=timeFmt) - F.unix_timestamp('min_ts', format=timeFmt))
df.show(truncate = False)

Body:
The answer from Tanjin doesn't work when the values are of type timestamp and the milliseconds are round numbers (like 390, 500). Python would cut the 0 at the end and the timestamp from the example would look like this 2018-07-25 17:15:06.39.

The problem is the hardcoded value in F.substring('max_ts', -3, 3). If the 0 at the end is missing then the substring goes wild.

To convert tmpColumn of type timestamp column to tmpLongColumn of type long I used this snippet:

timeFmt = "yyyy-MM-dd HH:mm:ss.SSS"

df = df \
  .withColumn('tmpLongColumn', F.substring_index('tmpColumn', '.', -1).cast('float')) \
  .withColumn('tmpLongColumn', F.when(F.col('tmpLongColumn') < 100, F.col('tmpLongColumn')*10).otherwise(F.col('tmpLongColumn')).cast('long')) \
  .withColumn('tmpLongColumn', (F.unix_timestamp('tmpColumn', format=timeFmt)*1000 + F.col('tmpLongColumn'))) \

The first transformation extracts the substring containing the milliseconds. Next, if the value is less then 100 multiply it by 10. Finally, convert the timestamp and add milliseconds.


问:
convert latitude and longitude to x and y grid system using python
I have file with latitude and longitude values, that i want to convert the x and y in km
I want to measure the distance from each point.

for instance I make the first points of latitude and longitude(which are 51.58, -124.6 respectfully)

to (0,0) in my x and y system so than basically i want to find out what the other points are and their location from the origin so i want to find what 51.56(lat) -123.64(long) is in (x,y) in km and so on for the rest of the file.

I want to do this all in python, is there some sort code ?

I found sites online , for instance

http://www.whoi.edu/marine/ndsf/cgi-bin/NDSFutility.cgi?form=0&from=LatLon&to=XY

does exactly want i want to do, I just don't know how they do it.

答:
if you were to use a 3D system, these functions will do:</p>

```<code>def arc_to_deg(arc):
    """convert spherical arc length [m] to great circle distance [deg]"""
    return float(arc)/6371/1000 * 180/math.pi

def deg_to_arc(deg):
    """convert great circle distance [deg] to spherical arc length [m]"""
    return float(deg)*6371*1000 * math.pi/180

def latlon_to_xyz(lat,lon):
    """Convert angluar to cartesian coordiantes

    latitude is the 90deg - zenith angle in range [-90;90]
    lonitude is the azimuthal angle in range [-180;180]
    """
    r = 6371 # https://en.wikipedia.org/wiki/Earth_radius
    theta = math.pi/2 - math.radians(lat)
    phi = math.radians(lon)
    x = r * math.sin(theta) * math.cos(phi) # bronstein (3.381a)
    y = r * math.sin(theta) * math.sin(phi)
    z = r * math.cos(theta)
    return [x,y,z]

def xyz_to_latlon (x,y,z):
    """Convert cartesian to angular lat/lon coordiantes"""
    r = math.sqrt(x**2 + y**2 + z**2)
    theta = math.asin(z/r) # https://stackoverflow.com/a/1185413/4933053
    phi = math.atan2(y,x)
    lat = math.degrees(theta)
    lon = math.degrees(phi)
    return [lat,lon]
</code>```

Body:
if you were to use a 3D system, these functions will do:

def arc_to_deg(arc):
    """convert spherical arc length [m] to great circle distance [deg]"""
    return float(arc)/6371/1000 * 180/math.pi

def deg_to_arc(deg):
    """convert great circle distance [deg] to spherical arc length [m]"""
    return float(deg)*6371*1000 * math.pi/180

def latlon_to_xyz(lat,lon):
    """Convert angluar to cartesian coordiantes

    latitude is the 90deg - zenith angle in range [-90;90]
    lonitude is the azimuthal angle in range [-180;180]
    """
    r = 6371 # https://en.wikipedia.org/wiki/Earth_radius
    theta = math.pi/2 - math.radians(lat)
    phi = math.radians(lon)
    x = r * math.sin(theta) * math.cos(phi) # bronstein (3.381a)
    y = r * math.sin(theta) * math.sin(phi)
    z = r * math.cos(theta)
    return [x,y,z]

def xyz_to_latlon (x,y,z):
    """Convert cartesian to angular lat/lon coordiantes"""
    r = math.sqrt(x**2 + y**2 + z**2)
    theta = math.asin(z/r) # https://stackoverflow.com/a/1185413/4933053
    phi = math.atan2(y,x)
    lat = math.degrees(theta)
    lon = math.degrees(phi)
    return [lat,lon]


问:
Android SQLite: No such table error when trying to fetch data from Database
I am trying to use an already created DB from a csv file using DB Browser.
I tried uninstalling and re-installing the app. Also upgraded the DB version and still the same error occurs!
Checked my DB path and if the file is being created or not.

DatabaseHelper.java

```<code>package com.timespro.bookaseat.Model;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.timespro.bookaseat.Students;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TABLE_NAME1 = "StudentDetails";

    private static final int DB_VERSION = 5;
    private static String DB_NAME = "data.sqlite";
    private  String DB_PATH;
    private  Context mContext;
    private SQLiteDatabase mDataBase;
    private boolean mNeedUpdate = false;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.mContext = context;
        DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
        Log.d("DB_Path",DB_PATH);
    }

    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();

            copyDataBase();

            mNeedUpdate = false;
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

        }catch(SQLiteException e){

            Log.d("DB","DB doesn't exist!");

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transferring bytestream.
     * */
    private void copyDataBase() throws IOException{
        Log.d("DB","Database copied!");
        //Open your local db as the input stream
        InputStream myInput = mContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     **/
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            Log.d("DatabaseHelper","DB already exists!");
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    private void copyDBFile() throws IOException {
        Log.d("DB","DB File created on phone");
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        //InputStream mInput = mContext.getResources().openRawResource(getResources().getIdentifier("data","raw", getPackageName()));
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        Log.d("DB","DB opened");
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        db.setForeignKeyConstraintsEnabled(true);
    }
    @Override
    public synchronized void close() {

        if(mDataBase != null)
            mDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("DB","DB created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
    public ArrayList<Students> getAllData(){
        ArrayList<Students> students = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            Cursor res = db.rawQuery("select * from "+TABLE_NAME1, null);
            res.moveToFirst();
            while(res.moveToNext()) {
                int uid = Integer.parseInt(res.getString(0));   //0 is the number of id column in your database table
                String name = res.getString(1);
                String pass = res.getString(2);
                String city = res.getString(3);
                String centre = res.getString(4);
                String inst = res.getString(5);
                String pro = res.getString(6);
                String batch = res.getString(7);
                String days = res.getString(8);
                String time = res.getString(9);

                Students newStudents = new Students(uid,name,pass,city,centre,inst,pro,batch,days,time);
                students.add(newStudents);
            }
            res.close();
        }
        catch(SQLiteException sql){
            Log.d("DatabaseError!","No table found!");
        }
        finally {

            db.close();
        }

        return students;
    }
</code>```

}

error message:
E/SQLiteLog: (1) no such table: StudentDetails
D/DatabaseError!: No table found!

答:
The issue could well be that the device is Android Pie or above in which case the default logging has been changed from journal to WAL.

This in conjunction with using

```<code>//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
</code>```

results in a database being created (so as to create the database directory), this then includes two files for WAL  dbname suffixed with -shm and -wal.

When the database is copied the -wal and -shm files do not match the new database (they belong to the overwritten database).

See this for fixes A pre-populated database does not work at API 28 throws “no such table” exception

Body:
I am trying to use an already created DB from a csv file using DB Browser.
I tried uninstalling and re-installing the app. Also upgraded the DB version and still the same error occurs!
Checked my DB path and if the file is being created or not.

DatabaseHelper.java

package com.timespro.bookaseat.Model;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.timespro.bookaseat.Students;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TABLE_NAME1 = "StudentDetails";

    private static final int DB_VERSION = 5;
    private static String DB_NAME = "data.sqlite";
    private  String DB_PATH;
    private  Context mContext;
    private SQLiteDatabase mDataBase;
    private boolean mNeedUpdate = false;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.mContext = context;
        DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
        Log.d("DB_Path",DB_PATH);
    }

    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();

            copyDataBase();

            mNeedUpdate = false;
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

        }catch(SQLiteException e){

            Log.d("DB","DB doesn't exist!");

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transferring bytestream.
     * */
    private void copyDataBase() throws IOException{
        Log.d("DB","Database copied!");
        //Open your local db as the input stream
        InputStream myInput = mContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     **/
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            Log.d("DatabaseHelper","DB already exists!");
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    private void copyDBFile() throws IOException {
        Log.d("DB","DB File created on phone");
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        //InputStream mInput = mContext.getResources().openRawResource(getResources().getIdentifier("data","raw", getPackageName()));
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        Log.d("DB","DB opened");
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        db.setForeignKeyConstraintsEnabled(true);
    }
    @Override
    public synchronized void close() {

        if(mDataBase != null)
            mDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("DB","DB created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
    public ArrayList<Students> getAllData(){
        ArrayList<Students> students = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            Cursor res = db.rawQuery("select * from "+TABLE_NAME1, null);
            res.moveToFirst();
            while(res.moveToNext()) {
                int uid = Integer.parseInt(res.getString(0));   //0 is the number of id column in your database table
                String name = res.getString(1);
                String pass = res.getString(2);
                String city = res.getString(3);
                String centre = res.getString(4);
                String inst = res.getString(5);
                String pro = res.getString(6);
                String batch = res.getString(7);
                String days = res.getString(8);
                String time = res.getString(9);

                Students newStudents = new Students(uid,name,pass,city,centre,inst,pro,batch,days,time);
                students.add(newStudents);
            }
            res.close();
        }
        catch(SQLiteException sql){
            Log.d("DatabaseError!","No table found!");
        }
        finally {

            db.close();
        }

        return students;
    }

}

error message:
E/SQLiteLog: (1) no such table: StudentDetails
D/DatabaseError!: No table found!

Body:
The issue could well be that the device is Android Pie or above in which case the default logging has been changed from journal to WAL.

This in conjunction with using

//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();

results in a database being created (so as to create the database directory), this then includes two files for WAL  dbname suffixed with -shm and -wal.

When the database is copied the -wal and -shm files do not match the new database (they belong to the overwritten database).

See this for fixes A pre-populated database does not work at API 28 throws “no such table” exception


问:
What is the meaning of "Localization native development region" entry in info.plist?
I don't know if I really understood the function of the "Localization native development region" entry in info.plist file.

Somewhere I read that this entry allows to specify the app language when there is no matching with a language resource dir.

I have an app localized in three languages: english, italian and spanish (en.lproj, it.lproj and es.lproj) and I set "Localization native development region" entry to Italy. When I change the language and locale in "Settings" (for example by chosing the arabic language and a proper region), the app language is english. Shouldn't be it italian as I set "Localization native development region" to Italy in the info.plist?

Any ideas? Could it be tied to the AppStore app description language?

答: The native development region also sets the default language spoken by VoiceOver. If you set this correctly you won't have to override the accessibility language in all the default components used in your app (which fall back to English).</p>


问:
setting the ckeditor caret at the end of a new link
I am currently working on the ckeditor for a project,
We are using the link dialog plugin.

As said in the title I wish to make new links, and set the caret at the end of it.
The default behaviour selects the text in the editor once you add a new link.

I've been working around with the link.js plugin

I think I located where it happen, but I am not able to set my caret after the end of my a tag in all case (It works sometimes=> it places the caret at the end, but after some tries it does put it at the begining of my link)

Here is a sample of what it does :
first time : [a href="#"]my link[/a]^
after some tries : [a href="#"]my link[/a][a href="#"]my link[/a]^[a href="#"]my link[/a]

the code inside the onOk method of the link plugin:

```<code>//I've commented the line under to have no selection : it works
//range.select();
// According to the doc, this should do the job ??
range.moveToPosition(text, CKEDITOR.POSITION_AFTER_END);
</code>```

Thank you for your attention.

Dre.

答:
I know the previous answer and question are old, but I had exactly the same issue & didn't immediately find a proper working solution. Using the answer of @oleq I got the "getParent of null" error.

Instead of touching the core or overwriting core functions (such as onOk), you can leverage event listeners. In this case the onHide from the dialogDefinition as it's only called once right before closing the dialog.

```<code>CKEDITOR.on('dialogDefinition', function (ev) {

        var dialogName = ev.data.name,
            dialogDefinition = evt.data.definition;

        // Only in case of the link dialog
        if ( dialogName === 'link' ) {
            dialogDefinition.on('hide', function (e) {
                var sel = ev.editor.getSelection(), // Current Selection
                    range = sel.getRanges()[0];
                range.moveToPosition(sel.getStartElement(), CKEDITOR. POSITION_AFTER_END);
                range.select();
            });
        }

    });
</code>```

Body:
I am currently working on the ckeditor for a project,
We are using the link dialog plugin.

As said in the title I wish to make new links, and set the caret at the end of it.
The default behaviour selects the text in the editor once you add a new link.

I've been working around with the link.js plugin

I think I located where it happen, but I am not able to set my caret after the end of my a tag in all case (It works sometimes=> it places the caret at the end, but after some tries it does put it at the begining of my link)

Here is a sample of what it does :
first time : [a href="#"]my link[/a]^
after some tries : [a href="#"]my link[/a][a href="#"]my link[/a]^[a href="#"]my link[/a]

the code inside the onOk method of the link plugin:

//I've commented the line under to have no selection : it works
//range.select();
// According to the doc, this should do the job ??
range.moveToPosition(text, CKEDITOR.POSITION_AFTER_END);

Thank you for your attention.

Dre.

Body:
I know the previous answer and question are old, but I had exactly the same issue & didn't immediately find a proper working solution. Using the answer of @oleq I got the "getParent of null" error.

Instead of touching the core or overwriting core functions (such as onOk), you can leverage event listeners. In this case the onHide from the dialogDefinition as it's only called once right before closing the dialog.

CKEDITOR.on('dialogDefinition', function (ev) {

        var dialogName = ev.data.name,
            dialogDefinition = evt.data.definition;

        // Only in case of the link dialog
        if ( dialogName === 'link' ) {
            dialogDefinition.on('hide', function (e) {
                var sel = ev.editor.getSelection(), // Current Selection
                    range = sel.getRanges()[0];
                range.moveToPosition(sel.getStartElement(), CKEDITOR. POSITION_AFTER_END);
                range.select();
            });
        }

    });


问:
Unity - How can i make a function fire only when player clicked on it 3 times?
I have a hint button on my game, but it fires up everytime you click on it. I need for it to fire only once every 3 clicks

i've tried adding a loadCount = 0 and an if statement

```<code>if (loadCount % 3 == 0) { }
</code>```

but it dosen't seem to work

image for reference : https://ibb.co/L9LnNDw

Here is the script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class HintScript : MonoBehaviour
{

    LineRenderer line;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        FindObjectOfType<AdMobManager>().Hint = true;
        FindObjectOfType<AdMobManager>().showInterstitial();
    }
}
</code>```

答:
1.Keep a static/global variable.

2.You can't stop event notifications so, please add condition(if condition) upon code block inside the event handler code.

Body:
I have a hint button on my game, but it fires up everytime you click on it. I need for it to fire only once every 3 clicks

i've tried adding a loadCount = 0 and an if statement

if (loadCount % 3 == 0) { }

but it dosen't seem to work

image for reference : https://ibb.co/L9LnNDw

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class HintScript : MonoBehaviour
{

    LineRenderer line;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        FindObjectOfType<AdMobManager>().Hint = true;
        FindObjectOfType<AdMobManager>().showInterstitial();
    }
}


问:
include new line/crlf into string variable using expression builder
I am building a flow, and need to append values into a string variable for an audit trail

so I have this:

```<code>concat(string(utcNow()), ': ', 'Approved by Data Protection', Char(13))
</code>```

but I get an error when trying to save the expression ...

in the list following the update (using the variable) it looks like this:

```<code>2019-05-21T08:28:43.2692428Z: Approved by Health & Safety2019-05-21T08:30:02.4883027Z: Approved by Data Protection
</code>```

when it should look like this:

```<code>2019-05-21T08:28:43.2692428Z: Approved by Health & Safety
2019-05-21T08:30:02.4883027Z: Approved by Data Protection
</code>```

what am I doing wrong, and how can I include a new line/line feed into the variable

答:
Very simple and neat resolution is to initialize a new String Variable and just type ENTER key inside Value input.

Or just put \n in concat() function.

Body:
I am building a flow, and need to append values into a string variable for an audit trail

so I have this:

concat(string(utcNow()), ': ', 'Approved by Data Protection', Char(13))

but I get an error when trying to save the expression ...

in the list following the update (using the variable) it looks like this:

2019-05-21T08:28:43.2692428Z: Approved by Health & Safety2019-05-21T08:30:02.4883027Z: Approved by Data Protection

when it should look like this:

2019-05-21T08:28:43.2692428Z: Approved by Health & Safety
2019-05-21T08:30:02.4883027Z: Approved by Data Protection

what am I doing wrong, and how can I include a new line/line feed into the variable


问:
Check the details of columns which have attributes applied to them
In the splayed tables we can find the details/order of columns in the .d file.

I was searching if there is any file which maintains the attributes information of the columns in a table.
How can we find the details of the attributes in the file system?

```<code>t:([] a:1 2 3; b:4 5 6; c:`a`b`c)
`:/home/st set .Q.en[`:/home/st;t]
get `:/home/st/.d / Output - `a`b`c
@[`:/home/st/;`a;`s#] / Is there any place in file system where we can find the attribute applied to a column
meta get `:/home/st/ / Show that attribute s is applied on column a
</code>```

答:
Attributes details are stored in the column file itself. For example, in your case file /home/st/a will contain sorted attribute information.

But since these files are serialized data (binary format), and structure of splayed binary data is not open, we can not get the attribute information directly from the file.

Body:
In the splayed tables we can find the details/order of columns in the .d file.

I was searching if there is any file which maintains the attributes information of the columns in a table.
How can we find the details of the attributes in the file system?

t:([] a:1 2 3; b:4 5 6; c:`a`b`c)
`:/home/st set .Q.en[`:/home/st;t]
get `:/home/st/.d / Output - `a`b`c
@[`:/home/st/;`a;`s#] / Is there any place in file system where we can find the attribute applied to a column
meta get `:/home/st/ / Show that attribute s is applied on column a


问:
Matplotlib with Pydroid 3 on Android: how to see graph?
I'm currently using an Android device (of Samsung), Pydroid 3.

I tried to see any graphs, but it doesn't works.

When I run the code, it just shows me a black-blank screen temporarily and then goes back to the source code editing window.

(means that i can't see even terminal screen, which always showed me [Program Finished])

Well, even the basic sample code which Pydroid gives me doesn't show me the  graph :(

I've seen many tutorials which successfully showed graphs, but well, mine can't do that things.

Unfortunately, cannot grab any errors.

Using same code which worked at Windows, so don't think the code has problem.

Of course, matplotlib is installed, numpy is also installed.

If there's any possible problems, please let me know.

答:
I also had this problem a while back, and managed to fix it by using plt.show()
at the end of your code. With matplotlib.pyplot as plt.


问:
Form and input validation
I am trying to get two inputs inside of a form tag to bring up a error message if you leave either of them blank.

I went to w3schools and tried their code but it does not work. (see below)

HTML

```<code><form name="myForm"  onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>
</code>```

Js

```<code>function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}
</code>```

I removed the action="demo_form.asp" from the code because my teacher told me to

Here is my code

HTML

```<code><div class="loginShite">
    <form name="username" onsubmit="return validateForm()" method="post">
        <input type="text" name="username" placeholder="@Username" />
        <input type="password" name="password" placeholder="Password" />
        <br />
    </form>
    <div class="loginButton">
        <a href="#homePage">
           <input type ="button" value="login" />
        </a>
    </div>
</div>
</code>```

Js

```<code>function validateForm() {
    var x = document.forms["username"]["password"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}
</code>```

I would be greatly appreciative is somebody could either tell me what I'm doing wrong OR point me in the right direction to solve the problem.

Thank you in advance.

答:
Here's how i've done it. You need to make sure the input type for button is "submit" else the form will not consider it as a trigger to submit. then you need to use || conditionals to test both the field conditions if they are blank or not. You can secure it more by adding the trim() method to avoid any accidental whitespaces getting accepted

Here's the HTML

```<code> <form onsubmit="return validate()" action="" class="form-group">
<div style="margin-top:2%">
  <div class="col-md-4"> // bootstrap
    <input type="text" id="uname" placeholder="user name"><br>
    <input type="password" id="pass" placeholder="password"><br>
    <input type="submit" class="btn btn-primary"><br><br>
    <p id="demouname"></p>
    <p id="succesuname"></p>
  </div>
</div>
</code>```

and here's the JS

```<code>function validate() {
  var username = document.getElementById("uname");
  var password = document.getElementById("pass");
  if (username.value.trim() == "" || password.value.trim() == "") {
    document.getElementById("demouname").style.display = "block";

    document.getElementById("demouname").innerHTML = "No Empty Values Allowed";

    return false;
  } else {
    document.getElementById("succesuname").style.display = "block";
    document.getElementById("succesuname").innerHTML = "Success";
    true;
  }
}
</code>```

and some basic css for added styling

```<code>    #demouname {
  display: none;
  padding: 10px;
  border: solid red 1px;
  background-color: rgba(250, 232, 232, 0.2);
  color: red;
  border-radius: 5px;
  -webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
  animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

#succesuname {
  display: none;
  padding: 10px;
  border: solid green 1px;
  background-color: rgba(251, 252, 251, 0.521);
  color: green;
  border-radius: 5px;
  -webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
  animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

}

@-webkit-keyframes shadow-drop-2-center {
  0% {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
  }

  100% {
    -webkit-transform: translateZ(50px);
    transform: translateZ(50px);
    box-shadow: 0 0 20px 0px rgba(255, 255, 255, 0.35);
  }
}

@keyframes shadow-drop-2-center {
  0% {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
  }

  100% {
    -webkit-transform: translateZ(50px);
    transform: translateZ(50px);
    box-shadow: 0 0 20px 0px rgba(0, 0, 0, 0.35);
  }
}
</code>```

Title: Form and input validation

Body:
I am trying to get two inputs inside of a form tag to bring up a error message if you leave either of them blank.

I went to w3schools and tried their code but it does not work. (see below)

HTML

<form name="myForm"  onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>

Js

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}

I removed the action="demo_form.asp" from the code because my teacher told me to

Here is my code

HTML

    <form name="username" onsubmit="return validateForm()" method="post">
        <input type="text" name="username" placeholder="@Username" />
        <input type="password" name="password" placeholder="Password" />

    </form>

           <input type ="button" value="login" />

Js

function validateForm() {
    var x = document.forms["username"]["password"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}

I would be greatly appreciative is somebody could either tell me what I'm doing wrong OR point me in the right direction to solve the problem.

Thank you in advance.

Body:
Here's how i've done it. You need to make sure the input type for button is "submit" else the form will not consider it as a trigger to submit. then you need to use || conditionals to test both the field conditions if they are blank or not. You can secure it more by adding the trim() method to avoid any accidental whitespaces getting accepted

Here's the HTML

 <form onsubmit="return validate()" action="" class="form-group">
<div style="margin-top:2%">
  <div class="col-md-4"> // bootstrap
    <input type="text" id="uname" placeholder="user name"><br>
    <input type="password" id="pass" placeholder="password"><br>
    <input type="submit" class="btn btn-primary"><br><br>
    <p id="demouname"></p>
    <p id="succesuname"></p>
  </div>
</div>

and here's the JS

function validate() {
  var username = document.getElementById("uname");
  var password = document.getElementById("pass");
  if (username.value.trim() == "" || password.value.trim() == "") {
    document.getElementById("demouname").style.display = "block";

    document.getElementById("demouname").innerHTML = "No Empty Values Allowed";

    return false;
  } else {
    document.getElementById("succesuname").style.display = "block";
    document.getElementById("succesuname").innerHTML = "Success";
    true;
  }
}

and some basic css for added styling

    #demouname {
  display: none;
  padding: 10px;
  border: solid red 1px;
  background-color: rgba(250, 232, 232, 0.2);
  color: red;
  border-radius: 5px;
  -webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
  animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

#succesuname {
  display: none;
  padding: 10px;
  border: solid green 1px;
  background-color: rgba(251, 252, 251, 0.521);
  color: green;
  border-radius: 5px;
  -webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
  animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

}

@-webkit-keyframes shadow-drop-2-center {
  0% {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
  }

  100% {
    -webkit-transform: translateZ(50px);
    transform: translateZ(50px);
    box-shadow: 0 0 20px 0px rgba(255, 255, 255, 0.35);
  }
}

@keyframes shadow-drop-2-center {
  0% {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
  }

  100% {
    -webkit-transform: translateZ(50px);
    transform: translateZ(50px);
    box-shadow: 0 0 20px 0px rgba(0, 0, 0, 0.35);
  }
}


问:
Javascript code not fetching location longitude and latitude for mobile browser
My javascript code not fetching longitude and latitude from mobile chrome browser.

the below-given code is working for laptop or desktop browser but not mobile

```<code><script>
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
   function showPosition(position) {
        alert(position.coords.latitude);
         alert(position.coords.longitude);
        document.getElementById("input1").value = position.coords.latitude;
        document.getElementById("input2").value = position.coords.longitude;
}
    </script>
</code>```

display or get longitude and latitude on the website browser.

答:
Try using a different browser in mobile it should work.

You can also add handle_error callback function to understand the issue more clearly.

```<code>navigator.geolocation.getCurrentPosition(showPosition,handle_error);

function handle_error(err){
 if(err.code == 1)
 {
   //User denied permission
 }
 else if(err.code == 2)
 {
   //position unavailable
 }
 else if(err.code == 3)
 {
   //Timeout
 }
 else{
   //Some other error
 }
}
</code>```

Body:
My javascript code not fetching longitude and latitude from mobile chrome browser.

the below-given code is working for laptop or desktop browser but not mobile

display or get longitude and latitude on the website browser.

Body:
Try using a different browser in mobile it should work.

You can also add handle_error callback function to understand the issue more clearly.

navigator.geolocation.getCurrentPosition(showPosition,handle_error);

function handle_error(err){
 if(err.code == 1)
 {
   //User denied permission
 }
 else if(err.code == 2)
 {
   //position unavailable
 }
 else if(err.code == 3)
 {
   //Timeout
 }
 else{
   //Some other error
 }
}


问:
Why does the newest Angular CLI have a corrupted packages?
I installed the latest Node and Angular on Windows 10

```<code>npm install npm@latest -g
npm install -g @angular/cli@latest
</code>```

But when I try to start a project ng new new-project I get the following error

```<code>    npm WARN tarball tarball data for @angular/compiler@^6.1.0 (sha512-TY6axB1c7VvYXf+ebFDq3Ej+edgii3CDxew8HnyTFAWeDF2Gh8io1vTYwtdyDka6U53ASaheM1HpiUjzvYH0jQ==) seems to be corrupted. Trying one more time.
    npm WARN tar ENOENT: no such file or directory, open 'C:\Users\admin\Desktop\...\node_modules\.staging\@angular\common-6be83a81\locales\si.js'
    ...

    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\admin\AppData\Roaming\npm-cache\_logs\2018-10-08T01_01_48_404Z-debug.log
    Package install failed, see above.
</code>```

I tried to uninstall Node.js and Angular CLI completely and then reinstall again

```<code> npm install npm@latest -g
 npm install -g @angular/cli@latest
</code>```

But still the same error ..... So I googled this issue. It seems like some people had it too, but then it magically disappeared for some people.

How to fix this?

答:
I was getting the same below error when attempting to a create new project using ng new command.

npm WARN tarball tarball data for @angular/compiler@~7.2.0
  (sha512-5yb4NcLk8GuXkYf7Dcor4XkGueYp4dgihzDmMjYDUrV0NPhubKlr+SwGtLOtzgRBWJ1I2bO0S3zwa0q0OgIPOw==)
  seems to be corrupted. Trying one more time.

I tried many things but what did not worked and what finally worked for me I have listed below. My working node version is 12.2.0 and npm version is 6.9.0 (i.e. latest version).

What did not worked:

Downgraded node js to other lower versions (tried many version)

Deleted package-lock.json file from project and executed npm install

Executed npm install --registry https://registry.cnpmjs.org instead of npm install

Deleted npm and npm-cache folders from AppData\Roaming and then again installed node js

Deleted node_modules folder, executed npm update and then executed npm install

Executed npm cache clean --force and then executed npm install

Reinstalled @angular/cli

Checked for any firewall / antivirus (in my case it was disabled)

Opened node command prompt as an administrator

Checked user permissions for the project folder

Finally what worked is:

Installed the component for which it was giving error. npm install -global @angular/compiler

Body:
I installed the latest Node and Angular on Windows 10

npm install npm@latest -g
npm install -g @angular/cli@latest

But when I try to start a project ng new new-project I get the following error

    npm WARN tarball tarball data for @angular/compiler@^6.1.0 (sha512-TY6axB1c7VvYXf+ebFDq3Ej+edgii3CDxew8HnyTFAWeDF2Gh8io1vTYwtdyDka6U53ASaheM1HpiUjzvYH0jQ==) seems to be corrupted. Trying one more time.
    npm WARN tar ENOENT: no such file or directory, open 'C:\Users\admin\Desktop\...\node_modules\.staging\@angular\common-6be83a81\locales\si.js'
    ...

    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\admin\AppData\Roaming\npm-cache\_logs\2018-10-08T01_01_48_404Z-debug.log
    Package install failed, see above.

I tried to uninstall Node.js and Angular CLI completely and then reinstall again

 npm install npm@latest -g
 npm install -g @angular/cli@latest

But still the same error ..... So I googled this issue. It seems like some people had it too, but then it magically disappeared for some people.

How to fix this?


问:
How to change comments language of generated code from wsimport.exe
I want to import a .wsdl-file using %JAVA_HOME%/bin/wsimport.exe into my Java project. Everything works fine, except that the language of the comments is in german, but I want it to be in english. How can I change the language used by wsimport.exe?

答:
For Oracle JDK 8, it is possible to call the WsImport class directly, and configure the language of the generated comments by setting the Locale to your desired language (the web service tools have been removed in Java 11).

```<code>Locale.setDefault(new Locale("en"));
List<String> args = new Arraylist<>();
// add other options
args.add(wsdlFile.getAbsolutePath());
com.sun.tools.internal.ws.WsImport.doMain(args.toArray(new String[0]));
</code>```

Body:
For Oracle JDK 8, it is possible to call the WsImport class directly, and configure the language of the generated comments by setting the Locale to your desired language (the web service tools have been removed in Java 11).

Locale.setDefault(new Locale("en"));
List<String> args = new Arraylist<>();
// add other options
args.add(wsdlFile.getAbsolutePath());
com.sun.tools.internal.ws.WsImport.doMain(args.toArray(new String[0]));


问:
How to wait 'return' until 'dispatch' finish
[React JS]How to wait 'return' until 'dispatch' finish in action creator?
I don't know how handle this ;(

i made some code. this is a part of action creator. But it return before dispatch finish. i want to dispatch finish before 'return'. help me please

```<code>export const Hello = param=> dispatch => {
  return postApi('/hello', param)
    .then(async res => {
      await dispatch(goHello(res));
       return true;
})
</code>```

答:
You can use await on postApi. You can only use await directly inside of an async function. Link.

```<code>export const Hello = (param) => async (dispatch, getState) => {
   const res = await postApi("/hello", param); // <- code pauses here

   const res2 = await anotherPostApi("/helloagain", param); // <- will wait for above

   dispatch(goHello(res));

   // You can also wrap the await postApi in a try catch instead of using .catch

   const value = getState().keyOfReducerInStore <-- returns the state of your reducer, you can follow this up with whatever value you want to check
    if(value){
        return true
    }
}
</code>```

Just remember. Promises can be awaited as long as they are directly inside of an async function. If you console.log a variable it'll show you if it is a Promise.

Body:
[React JS]How to wait 'return' until 'dispatch' finish in action creator?
I don't know how handle this ;(

i made some code. this is a part of action creator. But it return before dispatch finish. i want to dispatch finish before 'return'. help me please

export const Hello = param=> dispatch => {
  return postApi('/hello', param)
    .then(async res => {
      await dispatch(goHello(res));
       return true;
})

Body:
You can use await on postApi. You can only use await directly inside of an async function. Link.

export const Hello = (param) => async (dispatch, getState) => {
   const res = await postApi("/hello", param); // <- code pauses here

   const res2 = await anotherPostApi("/helloagain", param); // <- will wait for above

   dispatch(goHello(res));

   // You can also wrap the await postApi in a try catch instead of using .catch

   const value = getState().keyOfReducerInStore <-- returns the state of your reducer, you can follow this up with whatever value you want to check
    if(value){
        return true
    }
}

Just remember. Promises can be awaited as long as they are directly inside of an async function. If you console.log a variable it'll show you if it is a Promise.


问:
Given Time in minutes, print it in hours and minutes
In Question,  Given Time is in minutes that requires to be converted into hours and minutes.

Sample :

Input - 53
Output - 0 53

```<code>num = int(input())
if num < 60:
    print('0'+" "+str(num))
else:
    if num>=60:
        time = num*(1/60)
        time1 = (format(time, '.2f'))
        print(str(time1).replace('.',' '))
</code>```

答:
As per shown in picture...

You may try this..

```<code>def HoursandMinutes(Minutes):
    Minutes = Minutes % (24*3600)
    Hour = Minutes // 60
    Minutes %= 60
    print("%d %d" % (Hour, Minutes))
</code>```

When you call this function

OUTPUT

```<code>HoursandMinutes(52)
0 52

HoursandMinutes(70)
1 10

HoursandMinutes(90)
1 30

HoursandMinutes(105)
1 45
</code>```

Body:
In Question,  Given Time is in minutes that requires to be converted into hours and minutes.

Sample :

Input - 53
Output - 0 53

num = int(input())
if num < 60:
    print('0'+" "+str(num))
else:
    if num>=60:
        time = num*(1/60)
        time1 = (format(time, '.2f'))
        print(str(time1).replace('.',' '))

Body:
As per shown in picture...

You may try this..

def HoursandMinutes(Minutes):
    Minutes = Minutes % (24*3600)
    Hour = Minutes // 60
    Minutes %= 60
    print("%d %d" % (Hour, Minutes))

When you call this function

OUTPUT

HoursandMinutes(52)
0 52

HoursandMinutes(70)
1 10

HoursandMinutes(90)
1 30

HoursandMinutes(105)
1 45