问:
403 status from Firebase Cloud Function -> Google Books API
I'm currently working on creating a Firebase Cloud Function that retrieve a list of books from the NYTimes API and grabs some additional information from the Google Books API. By using the following URL : "https://www.googleapis.com/books/v1/volumes?q=isbn:&key=" I'm able to retrieve books' details based on an ISBN.

My FREE quota for Google Books API is 1000 request per day and 100 request every 100 seconds per user.  I'm only sending 15 requests and my current quota is below 200.

My key is restricted only to be used with Google Books API and it could be use from anywhere (iOS, web, android...etc)

After building the function I'm testing everything locally and data gets populated correctly although once I deploy the function on firebase I get a 403 status code when trying to access to the API.

Unfortunately I'm not getting more details about the error. It just this:

```<code>{ Error: Request failed with status code 403
    at createError (/user_code/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/user_code/node_modules/axios/lib/core/settle.js:18:12)
    at IncomingMessage.handleStreamEnd (/user_code/node_modules/axios/lib/adapters/http.js:201:11)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.18.0' },
     method: 'get',
     url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:0525520384&key=##########’,
     data: undefined },
  request:
   ClientRequest {
     domain: null,
     _events:
      { socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedHeader: {},
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 10,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        _bytesDispatched: 210,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        write: [Function: writeAfterFIN],
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 10,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        _bytesDispatched: 210,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        write: [Function: writeAfterFIN],
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     _header: 'GET /books/v1/volumes?q=isbn:0525520384&key=##### HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.18.0\r\nHost: www.googleapis.com\r\nConnection: close\r\n\r\n',
     _headers:
      { accept: 'application/json, text/plain, */*',
        'user-agent': 'axios/0.18.0',
        host: 'www.googleapis.com' },
     _headerNames: { accept: 'Accept', 'user-agent': 'User-Agent', host: 'Host' },
     _onPendingData: null,
     agent:
      Agent {
        domai
</code>```

答:
I was facing a similar issue. I was able to sucessfully use the Books API when I was running my functions locally (ie. firebase serve). But when I deployed the functions and the app to hosting, I was getting a mysterious 403: Forbidden error.

I tried several things so I'm not sure which helped so I'll just list everything:

Updated firebase functions: npm install --save firebase-functions@latest

Switched from using node-fetch to using axios for calling the API

Add country to URL: https://www.googleapis.com/books/v1/volumes?country=US&q=insubject:${randomWord}&key=${functions.config().books.api.key}

Regenerated Google Books API key

Removed all Application restrictions in the google cloud console

Hope this helps somebody out there because I was wrestling with it for hours!

Body:
I'm currently working on creating a Firebase Cloud Function that retrieve a list of books from the NYTimes API and grabs some additional information from the Google Books API. By using the following URL : "https://www.googleapis.com/books/v1/volumes?q=isbn:&key=" I'm able to retrieve books' details based on an ISBN.

My FREE quota for Google Books API is 1000 request per day and 100 request every 100 seconds per user.  I'm only sending 15 requests and my current quota is below 200.

My key is restricted only to be used with Google Books API and it could be use from anywhere (iOS, web, android...etc)

After building the function I'm testing everything locally and data gets populated correctly although once I deploy the function on firebase I get a 403 status code when trying to access to the API.

Unfortunately I'm not getting more details about the error. It just this:

{ Error: Request failed with status code 403
    at createError (/user_code/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/user_code/node_modules/axios/lib/core/settle.js:18:12)
    at IncomingMessage.handleStreamEnd (/user_code/node_modules/axios/lib/adapters/http.js:201:11)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.18.0' },
     method: 'get',
     url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:0525520384&key=##########’,
     data: undefined },
  request:
   ClientRequest {
     domain: null,
     _events:
      { socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedHeader: {},
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 10,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        _bytesDispatched: 210,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        write: [Function: writeAfterFIN],
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 10,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        _bytesDispatched: 210,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        write: [Function: writeAfterFIN],
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     _header: 'GET /books/v1/volumes?q=isbn:0525520384&key=##### HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.18.0\r\nHost: www.googleapis.com\r\nConnection: close\r\n\r\n',
     _headers:
      { accept: 'application/json, text/plain, */*',
        'user-agent': 'axios/0.18.0',
        host: 'www.googleapis.com' },
     _headerNames: { accept: 'Accept', 'user-agent': 'User-Agent', host: 'Host' },
     _onPendingData: null,
     agent:
      Agent {
        domai


来源: stackexchange

问:
How do I have to match the format between time data ' 01/27/1998' to '%d/%m/%y'?
I just tried to display my birthday(dd/mm/yyyy).
And then, I got "ValueError"
which is like "time data %r does not match format %r" % and
"time data ' 01/27/1998' does not match format '%d/%m/%y'"

Here is my code

```<code>from datetime import datetime, timedelta

birthday = input('When is your birthday (dd/mm/yyyy)?')

birthday_date = datetime.strptime(birthday, "%d/%m/%y")

print('Birthday : ' + str(birthday_date))

one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday : ' + str(birthday_eve))
</code>```

This is the detail of error

```<code>When is your birthday (dd/mm/yyyy)? 01/27/1998
Traceback (most recent call last):
  File "010-input_date.py", line 5, in <module>
    birthday_date = datetime.strptime(birthday, "%d/%m/%y")
  File
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py",
line 568,
in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py",
line 349,
in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data ' 01/27/1998' does not match format '%d/%m/%y'
</code>```

答:
Well, you specify dd/mm/yyyy, but you fed in 01/27/1998 which is mm/dd/yyyy:

```<code>birthday_date = datetime.strptime(birthday, "%m/%d/%Y")  # fixed
</code>```

Also note that %Y matches a 4-digit year while %y only matches the last 2 digits. (Reference link)

ContentLicense: CC BY-SA 4.0

Body:
I just tried to display my birthday(dd/mm/yyyy).
And then, I got "ValueError"
which is like "time data %r does not match format %r" % and
"time data ' 01/27/1998' does not match format '%d/%m/%y'"

Here is my code

from datetime import datetime, timedelta

birthday = input('When is your birthday (dd/mm/yyyy)?')

birthday_date = datetime.strptime(birthday, "%d/%m/%y")

print('Birthday : ' + str(birthday_date))

one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday : ' + str(birthday_eve))

This is the detail of error

When is your birthday (dd/mm/yyyy)? 01/27/1998
Traceback (most recent call last):
  File "010-input_date.py", line 5, in <module>
    birthday_date = datetime.strptime(birthday, "%d/%m/%y")
  File
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py",
line 568,
in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py",
line 349,
in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data ' 01/27/1998' does not match format '%d/%m/%y'

Body:
Well, you specify dd/mm/yyyy, but you fed in 01/27/1998 which is mm/dd/yyyy:

birthday_date = datetime.strptime(birthday, "%m/%d/%Y")  # fixed

Also note that %Y matches a 4-digit year while %y only matches the last 2 digits. (Reference link)


问:
List all uploaded images from cloudinary in react app
I want to display all the images in my cloudinary gallery in to my react app. Can I call the function directly like this?

```<code>showImages = () =>{
   cloudinary.v2.api.resources({
       cloud_name: CLOUDINARY_CLOUD_NAME,
       upload_preset: CLOUDINARY_UPLOAD_PRESET,
       api_key: CLOUDINARY_API_KEY,
       api_secret: CLOUDINARY_API_SECRET,
       type: 'upload'}, function(error, result){
       console.log("herrrrrrrrrreeeeeeeeeeeee",error,result);
   });
</code>```

}

It gives me this error.

```<code>Failed to load https://api.cloudinary.com/v1_1/dashboardui/resources/image/upload?: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

答:
The way to accomplish pulling images from cloudinary is to Tag the images, you need to go to media library which will display all the photos and tag photos with keyword eg "upload" which you can then use in the GET axios request. I was successfully able to pull the tagged images. You would need some css to align the images

import React, { Component } from 'react';
import axios from 'axios';
import { CloudinaryContext, Transformation, Image } from 'cloudinary-react';
import { render } from 'react-dom';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = {
            gallery: []
        }
    }
    componentDidMount() {
        // Request for images tagged xmas
        axios.get('https://res.cloudinary.com/<cloudname>/image/list/<tag_keyword>.json')
            .then(res => {
                console.log(res.data.resources);
                this.setState({gallery: res.data.resources});
            });
    }
    render(){
        return (

Galleria

                    <CloudinaryContext cloudName="cloud_name">
                        {
                            this.state.gallery.map(data => {
                                return (

                                            /image/upload/${data.public_id}.jpg`}>
                                                <Image publicId={data.public_id}>
                                                    <Transformation
                                                        crop="scale"
                                                        width="300"
                                                        height="200"
                                                        dpr="auto"
                                                        responsive_placeholder="blank"
                                                    />
                                                </Image>

Created at {data.created_at}

                                )
                            })
                        }
                    </CloudinaryContext>

        );
    }
}```

ContentLicense: CC BY-SA 3.0

Body:
I want to display all the images in my cloudinary gallery in to my react app. Can I call the function directly like this?

showImages = () =>{
   cloudinary.v2.api.resources({
       cloud_name: CLOUDINARY_CLOUD_NAME,
       upload_preset: CLOUDINARY_UPLOAD_PRESET,
       api_key: CLOUDINARY_API_KEY,
       api_secret: CLOUDINARY_API_SECRET,
       type: 'upload'}, function(error, result){
       console.log("herrrrrrrrrreeeeeeeeeeeee",error,result);
   });

}

It gives me this error.

Failed to load https://api.cloudinary.com/v1_1/dashboardui/resources/image/upload?: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Body:
The way to accomplish pulling images from cloudinary is to Tag the images, you need to go to media library which will display all the photos and tag photos with keyword eg "upload" which you can then use in the GET axios request. I was successfully able to pull the tagged images. You would need some css to align the images

import React, { Component } from 'react';
import axios from 'axios';
import { CloudinaryContext, Transformation, Image } from 'cloudinary-react';
import { render } from 'react-dom';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = {
            gallery: []
        }
    }
    componentDidMount() {
        // Request for images tagged xmas
        axios.get('https://res.cloudinary.com/<cloudname>/image/list/<tag_keyword>.json')
            .then(res => {
                console.log(res.data.resources);
                this.setState({gallery: res.data.resources});
            });
    }
    render(){
        return (
            <div className="main">
                <h1>Galleria</h1>
                <div className="gallery">
                    <CloudinaryContext cloudName="cloud_name">
                        {
                            this.state.gallery.map(data => {
                                return (
                                    <div className="responsive" key={data.public_id}>
                                        <div className="img">
                                            <a target="_blank" href={`https://res.cloudinary.com/<cloudname>/image/upload/${data.public_id}.jpg`}>
                                                <Image publicId={data.public_id}>
                                                    <Transformation
                                                        crop="scale"
                                                        width="300"
                                                        height="200"
                                                        dpr="auto"
                                                        responsive_placeholder="blank"
                                                    />
                                                </Image>
                                            </a>
                                            <div className="desc">Created at {data.created_at}</div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </CloudinaryContext>
                </div>
            </div>

        );
    }
}


问:
File Reading in C returns empty
I'm able to write data into a file but when I read it, it prints an empty file. I tried to make 2 programs one to write to file using permission "w" and one to read using "r" but when I combined both programs and changed permission to "w+" printing the files gives lots of empty spaces.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
void main()
{

    char name[20];
    char roll_no[15];
    char class[10];
    char semester[10];
    char course[20];

    FILE *file_pointer;
    file_pointer = fopen("StudentRecords.txt", "w+");
    if (file_pointer == NULL)
    {
        printf("\nError Opening File StudentRecords.txt\nCreate File Manually and Try Again.");
        exit(1);
    }

    printf("\nENTER DETAILS FOR 5 STUDENTS\n");

    //TAKE 5 RECORDS FROM USERS AND SAVE THEM IN FILE-
    for (int i = 1; i <= 5; i++)
    {
        printf("\nStudent %d", i);
        fprintf(file_pointer, "Student %d", i);

        printf("\nName : ");
        scanf("%s", &name);
        fprintf(file_pointer, "\nName : %s", name);

        printf("Roll No : ");
        scanf("%s", &roll_no);
        fprintf(file_pointer, "\nRoll No : %s", roll_no);

        printf("Class : ");
        scanf("%s", &class);
        fprintf(file_pointer, "\nClass : %s", class);

        printf("Semester : ");
        scanf("%s", &semester);
        fprintf(file_pointer, "\nSemester : %s", semester);

        printf("Course : ");
        scanf("%s", course);
        fprintf(file_pointer, "\nCourse : %s", course);

        printf("\n");
        fprintf(file_pointer, "\n\n");
    }

    //READ ENTIRE FILE WORD BY WORD
    char c;
    c = fgetc(file_pointer);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(file_pointer);
    }

    fclose(file_pointer);
}
</code>```

答:
For the read section do this instead. This will reset the position indicator to the beginning of the file so you can read from the beginning.</p>

```<code>if ( fseek(file_pointer, 0L, SEEK_SET) == 0 ) {
    char c;
    c = fgetc(file_pointer);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(file_pointer);
    }
}
</code>```

Title: File Reading in C returns empty

Body:
I'm able to write data into a file but when I read it, it prints an empty file. I tried to make 2 programs one to write to file using permission "w" and one to read using "r" but when I combined both programs and changed permission to "w+" printing the files gives lots of empty spaces.

#include <stdio.h>
#include <stdlib.h>
void main()
{

    char name[20];
    char roll_no[15];
    char class[10];
    char semester[10];
    char course[20];

    FILE *file_pointer;
    file_pointer = fopen("StudentRecords.txt", "w+");
    if (file_pointer == NULL)
    {
        printf("\nError Opening File StudentRecords.txt\nCreate File Manually and Try Again.");
        exit(1);
    }

    printf("\nENTER DETAILS FOR 5 STUDENTS\n");

    //TAKE 5 RECORDS FROM USERS AND SAVE THEM IN FILE-
    for (int i = 1; i <= 5; i++)
    {
        printf("\nStudent %d", i);
        fprintf(file_pointer, "Student %d", i);

        printf("\nName : ");
        scanf("%s", &name);
        fprintf(file_pointer, "\nName : %s", name);

        printf("Roll No : ");
        scanf("%s", &roll_no);
        fprintf(file_pointer, "\nRoll No : %s", roll_no);

        printf("Class : ");
        scanf("%s", &class);
        fprintf(file_pointer, "\nClass : %s", class);

        printf("Semester : ");
        scanf("%s", &semester);
        fprintf(file_pointer, "\nSemester : %s", semester);

        printf("Course : ");
        scanf("%s", course);
        fprintf(file_pointer, "\nCourse : %s", course);

        printf("\n");
        fprintf(file_pointer, "\n\n");
    }

    //READ ENTIRE FILE WORD BY WORD
    char c;
    c = fgetc(file_pointer);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(file_pointer);
    }

    fclose(file_pointer);
}

Body:
For the read section do this instead. This will reset the position indicator to the beginning of the file so you can read from the beginning.

if ( fseek(file_pointer, 0L, SEEK_SET) == 0 ) {
    char c;
    c = fgetc(file_pointer);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(file_pointer);
    }
}


问:
Gcc-4.2 failed with exit code 1 Error
I am getting this error when i am trying to build my app. In the simulator it works fine but when coming to build for ipa it gives the following error:

Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1

What is causing this error?

Edited

Ld
  build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge
  normal armv6 cd /Users/admin/Desktop/ShopSavvy setenv
  IPHONEOS_DEPLOYMENT_TARGET 4.2 setenv PATH
  "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch
  armv6 -isysroot
  /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk
  -L/Users/admin/Desktop/ShopSavvy/build/Release-iphoneos -L/Users/admin/Desktop/ShopSavvy -L/Users/admin/Desktop/ShopSavvy/Classes/ZBarSDK -L/Users/admin/Desktop/ShopSavvy/Classes/ScannerKit-4.0.3 -F/Users/admin/Desktop/ShopSavvy/build/Release-iphoneos -filelist /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge.LinkFileList
  -Xlinker -map -Xlinker /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/halalgauge-LinkMap-normal-armv6.txt
  -dead_strip all_load -lstdc++ -miphoneos-version-min=4.2 -framework CoreGraphics -framework AVFoundation -framework CoreVideo -framework
  CoreMedia -framework Foundation -framework AudioToolbox -framework
  QuartzCore -framework UIKit -framework iAd -lsqlite3.0 -framework
  MessageUI -framework AddressBook -framework AddressBookUI -framework
  MapKit -framework CoreLocation -liconv -lScannerKit -framework
  SystemConfiguration -framework MediaPlayer -o
  /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge

arm-apple-darwin10-gcc-4.2.1: all_load: No such file or directory
  Command
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2
  failed with exit code 1

答:
Could be due to multiple errors.

In XCode's build window select All Messages, that should give more meaningful information, which you can post here to help trace the problem.

Title: Gcc-4.2 failed with exit code 1 Error


问:
Warning: failed to read path from javaldx
An error occurs when converting a file using Libreoffice on ubuntu:

CompletedProcess(args=['soffice', '--headless', '--convert-to', 'txt:Text', '/var/www/Project/temp/e4bac2c2e7c04eb79cfa522967a30dd3.docx', '--outdir', '/var/www/Project/temp/'], returncode=77, stdout=b'', stderr=b'javaldx failed!\nWarning: failed to read path from javaldx\n')

Using subprocess:

process = subprocess.run(['soffice', '--headless', '--convert-to', 'txt:Text', path_docx, '--outdir', settings.TEMP_ROOT], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)

~# java --version

openjdk 11.0.6 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1, mixed mode, sharing)

答:
Ok found the solution:

If you are using libreoffice in headless, with a non root user, trying to convert a docx to a pdf, getting this error:

```<code>javaldx failed!
Warning: failed to read path from javaldx
</code>```

Your user doesn't has a home folder set, or the home folder is not writeable. I just switched from calling libreoffice directly to calling it via a shell script like this:

```<code>export HOME=/opt/fhir-services && /usr/lib/libreoffice/program/./soffice --headless --invisible --convert-to pdf --outdir /opt/fhir-services /opt/fhir-services/tmp.docx
</code>```

tomcat8 is the owner of this folder, now the conversion works.

Body:
Ok found the solution:

If you are using libreoffice in headless, with a non root user, trying to convert a docx to a pdf, getting this error:

javaldx failed!
Warning: failed to read path from javaldx

Your user doesn't has a home folder set, or the home folder is not writeable. I just switched from calling libreoffice directly to calling it via a shell script like this:

export HOME=/opt/fhir-services && /usr/lib/libreoffice/program/./soffice --headless --invisible --convert-to pdf --outdir /opt/fhir-services /opt/fhir-services/tmp.docx

tomcat8 is the owner of this folder, now the conversion works.


问:
What is the default filesystem of Amazon Linux AMI 18.03
I am logged into EMR master node, which is an EC2 instance launched using Amazon Linux AMI 2018.03 release. and executed below commands and their outputs are as follows:

```<code>uname -a
Linux ip-xx-xx-xxx-xxx y.yy.yyy-yyy.yyy.amzn1.x86_64 #1 SMP <TimeStamp Data> x86_64 GNU/Linux

cat /etc/os-release

NAME="Amazon Linux AMI"
VERSION="2018.03"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2018.03"
PRETTY_NAME="Amazon Linux AMI 2018.03"
ANSI_COLOR="0;33"
CPE_NAME="cpe:/o:amazon:linux:2018.03:ga"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"
</code>```

I've 3 queries as follows about the above EC2 instance:

```<code>what is the operating system?
what is default filesystem?
what is root volume?
</code>```

Appreciate your help!

答:
The operating system, in this case, is Amazon Linux AMI 2018.03. You can also find the details about the operating system by typing the command lsb_release -a. The sample output of this command will be something of this format.

```<code>Distributor ID:    Ubuntu
Description:       Ubuntu 18.04.2 LTS
Release:           18.04
Codename:          bionic
</code>```

For the next 2 questions, you can try this command. df -Th. This gives you the detail about all the filesystem present in this instance. The sample output of this will be something like this

In the above output, you can see Filesystem /dev/xvda1 of type ext4 is mounted on / which acts as root volume.

You can also try this command if this instance has the required permission. aws ec2 describe-volumes to get the detailed information about all the volumes. You can filter for a specific instance as well. Check this for more detail Describe volume

You can also check these details in the AWS EC2 console. Go to the EC2 console, type your instance IP. In the Description tab, you will find many useful details. For example, you can get detail about root device like this.

You can click on that link and it will take you to the Volume console, which will have all the information associated with root volume.

I hope this helps.

Body:
I am logged into EMR master node, which is an EC2 instance launched using Amazon Linux AMI 2018.03 release. and executed below commands and their outputs are as follows:

uname -a
Linux ip-xx-xx-xxx-xxx y.yy.yyy-yyy.yyy.amzn1.x86_64 #1 SMP <TimeStamp Data> x86_64 GNU/Linux

cat /etc/os-release

NAME="Amazon Linux AMI"
VERSION="2018.03"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2018.03"
PRETTY_NAME="Amazon Linux AMI 2018.03"
ANSI_COLOR="0;33"
CPE_NAME="cpe:/o:amazon:linux:2018.03:ga"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"

I've 3 queries as follows about the above EC2 instance:

what is the operating system?
what is default filesystem?
what is root volume?

Appreciate your help!

Body:
The operating system, in this case, is Amazon Linux AMI 2018.03. You can also find the details about the operating system by typing the command lsb_release -a. The sample output of this command will be something of this format.

Distributor ID:    Ubuntu
Description:       Ubuntu 18.04.2 LTS
Release:           18.04
Codename:          bionic

For the next 2 questions, you can try this command. df -Th. This gives you the detail about all the filesystem present in this instance. The sample output of this will be something like this

In the above output, you can see Filesystem /dev/xvda1 of type ext4 is mounted on / which acts as root volume.

You can also try this command if this instance has the required permission. aws ec2 describe-volumes to get the detailed information about all the volumes. You can filter for a specific instance as well. Check this for more detail Describe volume

You can also check these details in the AWS EC2 console. Go to the EC2 console, type your instance IP. In the Description tab, you will find many useful details. For example, you can get detail about root device like this.

You can click on that link and it will take you to the Volume console, which will have all the information associated with root volume.

I hope this helps.


问:
Curl works but React App throwing Cannot POST / error while using Axios and Express
I am trying to implement a simple form to send email. The error that I am getting is

Cannot POST /

I've used Create React App and the App.js looks like below:-

```<code>import React, { Component } from 'react';
//import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import renderEmail from 'axios';
import MyEmail from 'axios';

class App extends Component {
  state = {
      data: null
    };

    componentDidMount() {
        // Call our fetch function below once the component mounts
      this.callBackendAPI()
        .then(res => this.setState({ data: res.express }))
        .catch(err => console.log(err));
    }
      // Fetches our GET route from the Express server
    callBackendAPI = async () => {
      const response = await fetch('/express_backend');
      const body = await response.json();

      if (response.status !== 200) {
        throw Error(body.message)
      }
      return body;
    };

    handleSubmit(event){

      const messageHtml =  renderEmail(
        <MyEmail name={this.state.name}> {this.state.feedback}</MyEmail>
      );

              axios({
                  method: "POST",
                  url:"http://localhost:3000/send",
                  data: {
              name: this.state.name,
              email: this.state.email,
              messageHtml: messageHtml
                  }
              }).then((response)=>{
                  if (response.data.msg === 'success'){
                      alert("Email sent, awesome!");
                      this.resetForm()
                  }else if(response.data.msg === 'fail'){
                      alert("Oops, something went wrong. Try again")
                  }
              })
          }

          resetForm(){

            this.setState({feedback: ''});
        }

   render() {
    return (
      <form id="contact-form" method="POST">
    <div className="form-group">
        <label htmlFor="name">Name</label>
        <input type="text" className="form-control" id="name" />
    </div>
    <div className="form-group">
        <label htmlFor="exampleInputEmail1">Email address</label>
        <input type="email" className="form-control" id="email" aria-describedby="emailHelp" />
    </div>
    <div className="form-group">
        <label htmlFor="message">Message</label>
        <textarea className="form-control" rows="5" id="message"></textarea>
    </div>
    <button type="submit" className="btn btn-primary" onClick={this.handleSubmit}>Submit</button>
</form>
    );
  }
}

export default App;
</code>```

The server.js look like the below:-

```<code>const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
var nodemailer = require('nodemailer');
const creds = require('./config');

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

// create a GET route
 app.get('/express_backend', (req, res) => {
  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});

    var transport = {
    host: 'host', // e.g. smtp.gmail.com
    //service: 'gmail',
    port: 465,
    secure: true,
    auth: {
      user: 'xxxxx',
      pass: 'xxxxx'
    },
    tls: {
        // do not fail on invalid certs
        rejectUnauthorized: false
    }
  }

  var transporter = nodemailer.createTransport(transport)

  transporter.verify((error, success) => {
    if (error) {
      console.log(error);
    } else {
      console.log('All works fine, congratz!');
    }
  });

  app.use(express.json());

  app.post('/send', (req, res, next) => {
    const name = req.body.name
    const email = req.body.email
    const message = req.body.messageHtml

    var mail = {
      from: name,
      to: 'abc@gmail.com',
      subject: 'Contact form',

      html: message
    }

    transporter.sendMail(mail, (err, data) => {
      if (err) {
        res.json({
          msg: 'fail'
        })
      } else {
        res.json({
          msg: 'success'
        })
      }
    })
  });
</code>```

I have checked with curl and the localhost:3000/send is working properly and returns success. Please help! Thank you.

答: Have you tried enabling CORS in your server so as to enable React interact with your back end server?</p>

Body:
I am trying to implement a simple form to send email. The error that I am getting is

Cannot POST /

I've used Create React App and the App.js looks like below:-

import React, { Component } from 'react';
//import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import renderEmail from 'axios';
import MyEmail from 'axios';

class App extends Component {
  state = {
      data: null
    };

    componentDidMount() {
        // Call our fetch function below once the component mounts
      this.callBackendAPI()
        .then(res => this.setState({ data: res.express }))
        .catch(err => console.log(err));
    }
      // Fetches our GET route from the Express server
    callBackendAPI = async () => {
      const response = await fetch('/express_backend');
      const body = await response.json();

      if (response.status !== 200) {
        throw Error(body.message)
      }
      return body;
    };

    handleSubmit(event){

      const messageHtml =  renderEmail(
        <MyEmail name={this.state.name}> {this.state.feedback}</MyEmail>
      );

              axios({
                  method: "POST",
                  url:"http://localhost:3000/send",
                  data: {
              name: this.state.name,
              email: this.state.email,
              messageHtml: messageHtml
                  }
              }).then((response)=>{
                  if (response.data.msg === 'success'){
                      alert("Email sent, awesome!");
                      this.resetForm()
                  }else if(response.data.msg === 'fail'){
                      alert("Oops, something went wrong. Try again")
                  }
              })
          }

          resetForm(){

            this.setState({feedback: ''});
        }

   render() {
    return (
      <form id="contact-form" method="POST">

        Name
        <input type="text" className="form-control" id="name" />

        Email address
        <input type="email" className="form-control" id="email" aria-describedby="emailHelp" />

        Message
        <textarea className="form-control" rows="5" id="message"></textarea>

    <button type="submit" className="btn btn-primary" onClick={this.handleSubmit}>Submit</button>
</form>
    );
  }
}

export default App;

The server.js look like the below:-

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
var nodemailer = require('nodemailer');
const creds = require('./config');

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

// create a GET route
 app.get('/express_backend', (req, res) => {
  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});

    var transport = {
    host: 'host', // e.g. smtp.gmail.com
    //service: 'gmail',
    port: 465,
    secure: true,
    auth: {
      user: 'xxxxx',
      pass: 'xxxxx'
    },
    tls: {
        // do not fail on invalid certs
        rejectUnauthorized: false
    }
  }

  var transporter = nodemailer.createTransport(transport)

  transporter.verify((error, success) => {
    if (error) {
      console.log(error);
    } else {
      console.log('All works fine, congratz!');
    }
  });

  app.use(express.json());

  app.post('/send', (req, res, next) => {
    const name = req.body.name
    const email = req.body.email
    const message = req.body.messageHtml

    var mail = {
      from: name,
      to: 'abc@gmail.com',
      subject: 'Contact form',

      html: message
    }

    transporter.sendMail(mail, (err, data) => {
      if (err) {
        res.json({
          msg: 'fail'
        })
      } else {
        res.json({
          msg: 'success'
        })
      }
    })
  });

I have checked with curl and the localhost:3000/send is working properly and returns success. Please help! Thank you.


问:
Select from a comma separated list in a colum
I have a table, Table 1,

and I want to select all regions that are neighbours of region 3. What would be my query for this? The NEIGHBOUR column is a CHAR column.

I know the table should not be set up this way, but that is what I have to work with, as I don't have the rights to the database.

答:
Fix your data model!  There are numerous reasons why this is broken.

But if you ware stuck with it, you can use:

```<code>select t.*
from t
where ',' + neighbor + ',' like '%,3,%';
</code>```

You can also unnest the value using string_split():

```<code>select t.*
from t cross apply
     string_split(t.neighbor, ',') s
where s.value = '3';
</code>```

Body:
Fix your data model!  There are numerous reasons why this is broken.

But if you ware stuck with it, you can use:

select t.*
from t
where ',' + neighbor + ',' like '%,3,%';

You can also unnest the value using string_split():

select t.*
from t cross apply
     string_split(t.neighbor, ',') s
where s.value = '3';


问:
Show/hide password onClick of using Vanilla js
I'm trying to hide/show password using the following codes which works fine if it is for 1 input field. If I have another input field, say for 'verify password', how do I make the other works. I'm kinda stuck here.

Any input is very much appreciated. Thank you.

```<code>    var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");

    function togglePassword() {
        if (passwordField.type === "password") {
            passwordField.type = "text";
        } else {
            passwordField.type = "password";
        }
    }
    eyeIcon.addEventListener("click", togglePassword);
</code>```

答:
How about refactoring togglePassword() to handle a provided list of elements?

```<code>function togglePassword(fields = []) {
  fields.forEach(toggleType);
}

toggleType(field) {
  if(!field.type) {
    return;
  }

  if (field.type === "password") {
    field.type = "text";
  } else {
    field.type = "password";
  }
}
</code>```

Then you can declare multiple fields at the top, and pass them into the function as an array (togglePassword([passwordField, verifyField, ...])).

Body:
I'm trying to hide/show password using the following codes which works fine if it is for 1 input field. If I have another input field, say for 'verify password', how do I make the other works. I'm kinda stuck here.

Any input is very much appreciated. Thank you.

    var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");

    function togglePassword() {
        if (passwordField.type === "password") {
            passwordField.type = "text";
        } else {
            passwordField.type = "password";
        }
    }
    eyeIcon.addEventListener("click", togglePassword);

Body:
How about refactoring togglePassword() to handle a provided list of elements?

function togglePassword(fields = []) {
  fields.forEach(toggleType);
}

toggleType(field) {
  if(!field.type) {
    return;
  }

  if (field.type === "password") {
    field.type = "text";
  } else {
    field.type = "password";
  }
}

Then you can declare multiple fields at the top, and pass them into the function as an array (togglePassword([passwordField, verifyField, ...])).


问:
How can I output the names of rows which are NA in a given column in R?
I am working with panel data, and I've found out that I have 16 NAs in a column I am interested by typing:

```<code>sum(is.na(df$X1995))
[1] 16
</code>```

Now I want to know which rows had missing values for this year. Which rows had these 16 NAs?

I tried this, but it returns NULL:

```<code>rownames(which(is.na(df$X1995)))
</code>```

答:
I think @akrun has explained the reason in details.

Below is another option maybe work for you as well, where subset sorts out those rows with NA and then you can read the row names:

```<code>row.names(subset(df,is.na(X1995)))
</code>```

Body:
I am working with panel data, and I've found out that I have 16 NAs in a column I am interested by typing:

sum(is.na(df$X1995))
[1] 16

Now I want to know which rows had missing values for this year. Which rows had these 16 NAs?

I tried this, but it returns NULL:

rownames(which(is.na(df$X1995)))

Body:
I think @akrun has explained the reason in details.

Below is another option maybe work for you as well, where subset sorts out those rows with NA and then you can read the row names:

row.names(subset(df,is.na(X1995)))


问:
Unity3D Package Cache errors(?)
After deleting and installing Unity due to a problem it caused me, these errors appeared in the console. I've already tried to reinstall Unity but they won't go away.

EDIT: I get these errors in every project I open.

答:
I usually go to the Project Tab and Right Click on the Assets Folder and click "Reimport All".

Depending on wicht version of Unity this could happen more often that you want... f.e. using an Alpha Version.

I find it faster only reimporting than deleting files and importing again.

Title: Unity3D Package Cache errors(?)


问:
Django | Error when insert imageName with for into static url
Error when we want to insert image file name into static url. No all has imageName.

Error:

Invalid block tag

Code:

```<code><img width="40%" src="{% static 'files/img/
{% for i in questions %}
  {% i.imageName %}
{% endfor %}
' %}">
</code>```

答:
try </p>

```<code>{% for i in questions %}
<img width="40%" src="{% static "files/img/{{i.imageName.url }}" %}">
{% endfor %}
</code>```

Body:
try

{% for i in questions %}
<img width="40%" src="{% static "files/img/{{i.imageName.url }}" %}">
{% endfor %}


问:
Error in insert data using keyboard on JDBC
In JDBC, I want to insert data using input from the keyboard.

As a result of finding the method, I came to know the scanner and wrote the code as follows.

```<code>package DB;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

class insert{

    Connection con;

    Statement stmt;

    Scanner scan = new Scanner(Syetem.in);

    public insert() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:orcl";
            con = DriverManager.getConnection(url,"scott","1234");
            stmt = con.createStatement();
        } catch(ClassNotFoundException ce) {
            System.out.println(ce.getMessage());
        } catch(SQLException se){
            System.out.println(se.getMessage());
        }
    }

    public void disconnect() throws SQLException{
        if (stmt!=null) stmt.close();
        if (con!=null) con.close();
    }

    public void insert() throws SQLException{
        System.out.println("name:")
        String employee_name=scan.next();

        System.out.println("domain:")
        String street=scan.next();

        System.out.println("country:")
        String city=scan.next();

        String sql="insert into information values('"+name+"', '"+domain+"', '"+country+"')";

        int n=stmt.executeUpdate(sql);
    }

}

</code>```

But it didn't run and got an error ...
The default method cannot be found in the class. Define a default method in the following format. public static void main (String [] args)

Where should I put the main function to fix the error?

What is the problem? The name of the table to be inserted is 'information'.

Any help would be greatly appreciated

Because JDBC is not yet familiar, if possible, if you write a full query including a connection as in the above query, I would be very grateful.

*my oracle version is 11g

答:
For your code to run you need to provide a method that works as an entry point for your program, that method has the signature public static void main(String[] args) besides that, your class should be named Insert with capital I first because thats de standard y second because you have a method called insert, you will need to have something like this:

public class Insert {
  public Insert() {
  ...
  }

  public void disconnect() throws SQLException {
  ...
  }

  public void insert() throws SQLException {
  ...
  }

  public static void main(String[] args) {
    new Insert().insert();
  }
}
```

Body:
In JDBC, I want to insert data using input from the keyboard.

As a result of finding the method, I came to know the scanner and wrote the code as follows.

package DB;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

class insert{

    Connection con;

    Statement stmt;

    Scanner scan = new Scanner(Syetem.in);

    public insert() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:orcl";
            con = DriverManager.getConnection(url,"scott","1234");
            stmt = con.createStatement();
        } catch(ClassNotFoundException ce) {
            System.out.println(ce.getMessage());
        } catch(SQLException se){
            System.out.println(se.getMessage());
        }
    }

    public void disconnect() throws SQLException{
        if (stmt!=null) stmt.close();
        if (con!=null) con.close();
    }

    public void insert() throws SQLException{
        System.out.println("name:")
        String employee_name=scan.next();

        System.out.println("domain:")
        String street=scan.next();

        System.out.println("country:")
        String city=scan.next();

        String sql="insert into information values('"+name+"', '"+domain+"', '"+country+"')";

        int n=stmt.executeUpdate(sql);
    }

}

But it didn't run and got an error ...
The default method cannot be found in the class. Define a default method in the following format. public static void main (String [] args)

Where should I put the main function to fix the error?

What is the problem? The name of the table to be inserted is 'information'.

Any help would be greatly appreciated

Because JDBC is not yet familiar, if possible, if you write a full query including a connection as in the above query, I would be very grateful.

*my oracle version is 11g


问:
How to remove randomization in Repast Simphony for testing purposes?
I want to remove all randomization from my Repast model so that I can refactor with confidence that functionality is unchanged. However, I was unable to remove randomization by setting the seed using RandomHelper.setSeed(1) at the top of myBuilder.build(), and making sure that my 'Default Random Seed' parameter seed was set to 1 in the GUI at initialization.

So, I tried to remove randomization from the sample JZombies model and had the same issue. Again, I set RandomHelper.setSeed(1) at the top of JZombiesBuilder.build(), and made sure the Default Random Seed was set to 1. Sometimes the output was identical, sometimes it was not.

In both cases I'm using a Text Sink to record a constant number of ticks of aggregate agent counts and aggregate agent attributes as my data. I found differences in the output files using both Windows's FC & FCIV.

What changes do I need to make to ensure deterministic behavior?

Edit:

I got deterministic behavior in the JZombies demo model by also putting RandomHelper.setSeed(1); at the top of each class's constructor. Doing the same thing in my actual model makes the first step consistently identical. There are still differences from the second tick on. I think the issue is random scheduling, now?

答:
You should not have to set your random seed twice, so I would start with removing the RandomHelper.setSeed(1) call in your builder (and elsewhere).
The GUI random seed you are mentioning is set via the JZombies_Demo.rs/parameters.xml file.

On to your actual question. If you are using RandomHelper calls for all of your stochastic elements in the code, you should see reproducible results. If not, this could indicate that there is some unaccounted for stochasticity, e.g., the use of a non-RandomHelper call or something like iterating through a HashMap. E.g., when you iterate using the for loop over a DefaultContext, the iteration occurs over a HashSet, but when using the Context.getObjects() method, the internal iteration is over a LinkedHashMap, so repeatability is ensured.


问:
How to upgrade to Python 3.7 in Linux centos from 2.7 in Compute Engine?
Ive been trying to install Python3.7 by following this instruction to my compute engine instance. https://tecadmin.net/install-python-3-7-on-centos/

but everytime i try to check the version python3.7 --V it still not recognising my installation. And if i do python --version, it's still showing me python2.7

What's the best way to install python for the GCP compute engine' instance?

Thank you

答:
Upgrading default python on Linux is a very critical operation. Because most of the Linux functions uses python. So, upgrading would break those. But still, we can install the latest python versions through make altinstall command. It'll install the given version without replacing the default/existing version. You could find the binary at /usr/local/bin/python3 or /usr/local/bin/python3.7.

make altinstall is used to prevent replacing the default python binary
  file /usr/bin/python.

If you installed python3 use python3 --version or python3.7 --version command to find out the version.


问:
Android Content Provider inside the same application
I've more than one activity (inside the same Application) that needs to have access to the database. What's the best pattern to implement this ? Do I need a content provider even if all activities belong to the same application? </p>

<p>Which activity should have the responsibility for opening and closing the database ? </p>

答:
Content providers offer a structured storage mechanism that can be limited to your own application or exported to allow access by other applications. If you do not intend to provide other applications with access to your ContentProvider, mark them as android:exported=false in the application manifest. Otherwise, set the android:exported attribute to true to allow other apps to access the stored data.

https://developer.android.com/training/articles/security-tips

ContentLicense: CC BY-SA 2.5

Body:
I've more than one activity (inside the same Application) that needs to have access to the database. What's the best pattern to implement this ? Do I need a content provider even if all activities belong to the same application?

Which activity should have the responsibility for opening and closing the database ?


问:
Print specific "columns" of text file that has a somewhat inconsistent format
I'm trying to extract three columns from a text file that looks like this:

```<code><Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72">
<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>
</code>```

This is the information I'd like to extract:

```<code>sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39", "72"
"Wahoo", "2020-05-30 07:37:05", "83"
</code>```

So I basically need the source name, full creationDate and value in a comma-separated format.

The issue I'm having is that sourceName itself has multiple nested "fields" and creationDate has spaces. So my previous attempts using grep and awk all failed :)

Any help would be greatly appreciated.

答:
With this valid file.xml:

```<code><root>
  <Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72"/>
  <Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>
</root>
</code>```

Command:

```<code>xmlstarlet select --text --template --match '//Record' --value-of \
  "concat('\"',@sourceName,'\", \"', @creationDate,'\", \"',@value,'\"')" -n file.xml
</code>```

Output:

```
"Michael’s Apple Watch", "2020-05-30 07:26:39 -0400", "72"
"Wahoo", "2020-05-30 07:37:05 -0400", "83"
```

Body:
I'm trying to extract three columns from a text file that looks like this:

<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72">
<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>

This is the information I'd like to extract:

sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39", "72"
"Wahoo", "2020-05-30 07:37:05", "83"

So I basically need the source name, full creationDate and value in a comma-separated format.

The issue I'm having is that sourceName itself has multiple nested "fields" and creationDate has spaces. So my previous attempts using grep and awk all failed :)

Any help would be greatly appreciated.

Body:
With this valid file.xml:

<root>
  <Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael&#x2019;s Apple Watch" sourceVersion="6.2.5" device="&lt;&lt;HKDevice: 0x2877dc870&gt;, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D&gt;" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72"/>
  <Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>
</root>

Command:

xmlstarlet select --text --template --match '//Record' --value-of \
  "concat('\"',@sourceName,'\", \"', @creationDate,'\", \"',@value,'\"')" -n file.xml

Output:

"Michael’s Apple Watch", "2020-05-30 07:26:39 -0400", "72"
"Wahoo", "2020-05-30 07:37:05 -0400", "83"


问:
Get related ID collections from a json array react native
I have a array of objects as a json file, I used the objects to display them on the list, When getting to details of that item it has a related items also.
I want to show related items for this item
Heres the json file

```<code>[
{
    "id": 1,
    "name": "Kling-Spencer",
    "description": "sed justo pellentesque viverra pede ac diam cras pellentesque volutpat dui maecenas tristique est et tempus semper est quam pharetra magna",
    "email": "fdory0@opera.com",
    "image": "http://dummyimage.com/300x300.bmp/cc0000/ffffff&text=Kling-Spencer",
    "related": [
        2,
        3,
        6,
        8,
        23
    ]
},
{
    "id": 2,
    "name": "Donnelly, Lockman and Dare",
    "description": "in felis donec semper sapien a libero nam dui proin leo odio porttitor id consequat in consequat ut nulla sed accumsan felis ut at dolor quis odio consequat varius integer",
    "email": "amcglaughn1@indiatimes.com",
    "image": "http://dummyimage.com/300x300.png/5fa2dd/ffffff&text=Donnelly",
    "related": null
},
{
    "id": 3,
    "name": "Klein LLC",
    "description": "dictumst aliquam augue quam sollicitudin vitae consectetuer eget rutrum at lorem integer tincidunt ante vel ipsum praesent blandit lacinia erat",
    "email": "kcaso2@miibeian.gov.cn",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Klein%20LLC",
    "related": [
        15,
        13,
        1,
        5,
        4
    ]
},
{
    "id": 4,
    "name": "Aufderhar Group",
    "description": "id justo sit amet sapien dignissim vestibulum vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae nulla dapibus dolor",
    "email": "ageleman3@zdnet.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Aufderhar%20Group",
    "related": null
},
{
    "id": 5,
    "name": "Lynch, Raynor and Mayer",
    "description": "ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae nulla dapibus dolor vel est donec odio justo sollicitudin ut suscipit a feugiat et eros vestibulum",
    "email": "dleece4@apache.org",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000",
    "related": null
},
{
    "id": 6,
    "name": "Kuhn, Miller and Carroll",
    "description": "in felis eu sapien cursus vestibulum proin eu mi nulla ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing",
    "email": "bgotliffe5@seesaa.net",
    "image": "http://dummyimage.com/300x300.png/5fa2dd/ffffff&text=Kuhn,%20Miller%20and%20Carroll",
    "related": [
        1,
        29,
        15
    ]
},
{
    "id": 7,
    "name": "Feest-Brown",
    "description": "ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing lorem vitae mattis nibh ligula nec sem duis aliquam convallis",
    "email": "mbridges6@deviantart.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Feest-Brown",
    "related": null
},
{
    "id": 8,
    "name": "Gutmann, Buckridge and Kris",
    "description": "quis lectus suspendisse potenti in eleifend quam a odio in hac habitasse platea dictumst maecenas ut massa quis augue luctus tincidunt nulla mollis molestie lorem",
    "email": "tdumbrell7@ted.com",
    "image": "http://dummyimage.com/300x300.bmp/ff4444/ffffff&text=Gutmann",
    "related": [
        14,
        20,
        23,
        27
    ]
},
{
    "id": 9,
    "name": "McLaughlin-Bogan",
    "description": "morbi quis tortor id nulla ultrices aliquet maecenas leo odio condimentum id luctus nec molestie sed justo pellentesque viverra pede ac diam cras pellentesque",
    "email": "lgadsdon8@joomla.org",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=McLaughlin-Bogan",
    "related": [
        6,
        9,
        12,
        30
    ]
},
{
    "id": 10,
    "name": "Kilback-Padberg",
    "description": "leo odio condimentum id luctus nec molestie sed justo pellentesque viverra pede ac diam cras pellentesque volutpat dui maecenas tristique est et tempus semper est quam pharetra magna ac",
    "email": "eodegaard9@dailymail.co.uk",
    "image": "http://dummyimage.com/300x300.png/ff4444/ffffff&text=Kilback-Padberg",
    "related": null
},
{
    "id": 11,
    "name": "Skiles LLC",
    "description": "rutrum at lorem integer tincidunt ante vel ipsum praesent blandit lacinia erat vestibulum sed magna at nunc commodo placerat praesent blandit nam nulla integer pede justo lacinia eget tincidunt eget",
    "email": "marchibolda@apple.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Skiles%20LLC",
    "related": [
        21,
        27,
        28,
        5
    ]
},
{
    "id": 12,
    "name": "McGlynn Group",
    "description": "nulla integer pede justo lacinia eget tincidunt eget tempus vel pede morbi porttitor lorem id ligula suspendisse ornare consequat lectus in est risus",
    "email": "eraggettb@nba.com",
    "image": "http://dummyimage.com/300x300.bmp/cc0000/ffffff&text=McGlynn%20Group",
    "related": [
        10,
        18,
        26
    ]
},
{
    "id": 13,
    "name": "Cassin-Kling",
    "description": "ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing lorem vitae mattis nibh ligula nec sem duis aliquam convallis",
    "email": "cdunbletonc@indiatimes.com",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Cassin-Kling",
    "related": [
        17,
        29,
        1,
        3,
        8
    ]
},
{
    "id": 14,
    "name": "Greenfelder, Conroy and Schinner",
    "description": "imperdiet nullam orci pede venenatis non sodales sed tincidunt eu felis fusce posuere felis sed lacus morbi sem mauris laoreet ut rhoncus aliquet pulvinar sed nisl nunc rhoncus",
    "email": "njamiesond@ehow.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Greenfelder",
    "related": [
        18,
        21,
        27
    ]
},
{
    "id": 15,
    "name": "MacGyver, Huel and Lind",
    "description": "cubilia curae duis faucibus accumsan odio curabitur convallis duis consequat dui nec nisi volutpat eleifend donec ut dolor morbi vel lectus in",
    "email": "tclinche@soundcloud.com",
    "image": "http://dummyimage.com/300x300.bmp/ff4444/ffffff&text=MacGyver",
    "related": null
},
{
    "id": 16,
    "name": "Aufderhar-Little",
    "description": "nisl aenean lectus pellentesque eget nunc donec quis orci eget orci vehicula condimentum curabitur in libero ut massa volutpat convallis morbi odio odio elementum eu",
    "email": "epennellsf@symantec.com",
    "image": "http://dummyimage.com/300x300.png/dddddd/000000&text=Aufderhar-Little",
    "related": null
},
{
    "id": 17,
    "name": "Graham-Berge",
    "description": "non ligula pellentesque ultrices phasellus id sapien in sapien iaculis congue vivamus metus arcu adipiscing molestie hendrerit at vulputate vitae nisl aenean lectus pellentesque eget nunc donec quis orci",
    "email": "rvielg@weibo.com",
    "image": "http://dummyimage.com/300x300.bmp/ff4444/ffffff&text=Graham-Berge",
    "related": [
        12,
        16,
        29,
        30
    ]
},
{
    "id": 18,
    "name": "Gaylord, Klein and Donnelly",
    "description": "ac est lacinia nisi venenatis tristique fusce congue diam id ornare imperdiet sapien urna pretium nisl ut volutpat sapien arcu sed augue",
    "email": "estoyellh@bing.com",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Klein%20and%20Donnelly",
    "related": [
        6,
        7,
        9,
        18,
        21
    ]
},
{
    "id": 19,
    "name": "Gusikowski Group",
    "description": "lacus morbi quis tortor id nulla ultrices aliquet maecenas leo odio condimentum id luctus nec molestie sed justo pellentesque viverra pede ac diam cras pellentesque volutpat dui maecenas tristique",
    "email": "kpalatinoi@toplist.cz",
    "image": "http://dummyimage.com/300x300.jpg/ff4444/ffffff&text=Gusikowski",
    "related": [
        16,
        29,
        3
    ]
},
{
    "id": 20,
    "name": "Jaskolski-McKenzie",
    "description": "a nibh in quis justo maecenas rhoncus aliquam lacus morbi quis tortor id nulla ultrices aliquet maecenas leo odio condimentum id luctus nec",
    "email": "sloganj@japanpost.jp",
    "image": "http://dummyimage.com/300x300.bmp/cc0000/ffffff&text=Jaskolski-McKenzie",
    "related": [
        12,
        14,
        18
    ]
},
{
    "id": 21,
    "name": "Kautzer, Dooley and Kuhic",
    "description": "hac habitasse platea dictumst maecenas ut massa quis augue luctus tincidunt nulla mollis molestie lorem quisque ut erat curabitur gravida nisi at nibh in",
    "email": "snoodsk@over-blog.com",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=Kautzer",
    "related": [
        3,
        5,
        17,
        29,
        30
    ]
},
{
    "id": 22,
    "name": "Kohler, Tremblay and Bernier",
    "description": "in lacus curabitur at ipsum ac tellus semper interdum mauris ullamcorper purus sit amet nulla quisque arcu libero rutrum ac lobortis vel dapibus at",
    "email": "zsorriel@arizona.edu",
    "image": "http://dummyimage.com/300x300.png/ff4444/ffffff&text=Kohler",
    "related": null
},
{
    "id": 23,
    "name": "Cummerata, Trantow and Huels",
    "description": "potenti nullam porttitor lacus at turpis donec posuere metus vitae ipsum aliquam non mauris morbi non lectus aliquam sit amet diam in magna bibendum imperdiet nullam orci pede venenatis non",
    "email": "rshillingtonm@people.com.cn",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=Cummerata",
    "related": [
        5,
        4,
        13,
        23,
        27
    ]
},
{
    "id": 24,
    "name": "O'Reilly LLC",
    "description": "eu orci mauris lacinia sapien quis libero nullam sit amet turpis elementum ligula vehicula consequat morbi a ipsum integer a",
    "email": "tstaten@symantec.com",
    "image": "http://dummyimage.com/300x300.png/5fa2dd/ffffff&text=O'Reilly%20LLC",
    "related": [
        4,
        5,
        6,
        10
    ]
},
{
    "id": 25,
    "name": "Grant-Spencer",
    "description": "augue vel accumsan tellus nisi eu orci mauris lacinia sapien quis libero nullam sit amet turpis elementum ligula vehicula consequat morbi a ipsum integer a",
    "email": "bgrzegorczyko@vk.com",
    "image": "http://dummyimage.com/300x300.png/ff4444/ffffff&text=Grant-Spencer",
    "related": null
},
{
    "id": 26,
    "name": "Jacobi-Jaskolski",
    "description": "orci nullam molestie nibh in lectus pellentesque at nulla suspendisse potenti cras in purus eu magna vulputate luctus cum sociis natoque penatibus et magnis dis parturient montes",
    "email": "afranktonp@uol.com.br",
    "image": "http://dummyimage.com/300x300.bmp/5fa2dd/ffffff&text=Jacobi-Jaskolski",
    "related": null
},
{
    "id": 27,
    "name": "Heathcote LLC",
    "description": "curabitur in libero ut massa volutpat convallis morbi odio odio elementum eu interdum eu tincidunt in leo maecenas pulvinar lobortis est phasellus",
    "email": "sgeggusq@weather.com",
    "image": "http://dummyimage.com/300x300.bmp/5fa2dd/ffffff&text=Heathcote%20LLC",
    "related": [
        15,
        20,
        1,
        3
    ]
},
{
    "id": 28,
    "name": "Towne, Schaefer and Reichert",
    "description": "congue elementum in hac habitasse platea dictumst morbi vestibulum velit id pretium iaculis diam erat fermentum justo nec condimentum neque sapien placerat ante nulla justo aliquam quis",
    "email": "msnoadr@army.mil",
    "image": "http://dummyimage.com/300x300.jpg/ff4444/ffffff&text=Towne",
    "related": null
},
{
    "id": 29,
    "name": "Graham, Green and Roberts",
    "description": "vestibulum sagittis sapien cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus etiam vel augue vestibulum rutrum rutrum neque aenean auctor gravida",
    "email": "aflecknoes@redcross.org",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=Graham",
    "related": null
},
{
    "id": 30,
    "name": "Commings Group",
    "description": "luctus tincidunt nulla mollis molestie lorem quisque ut erat curabitur gravida nisi at nibh in hac habitasse platea dictumst aliquam augue",
    "email": "gmationt@slideshare.net",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Commings%20Group",
    "related": null
}
</code>```

]

As you can see for every item has a related, but related are just ID's how can i find each related item object and show them heres what i tried

this is the item details screen

```<code>   import React from "react";
import { View, Image, StyleSheet, Text, FlatList } from "react-native";

import RelatedList from "../components/RelatedList";

import api from "../apis/stores.json";

function StoreDetails(props) {
  const { navigation } = props;
  const id = navigation.getParam("id");
  const name = navigation.getParam("name");
  const email = navigation.getParam("email");
  const description = navigation.getParam("description");
  const image = navigation.getParam("image");
  const data = [api[0]];

  data.filter(value => value.id == id)
  const related = [
    data
  ];
  return (
    <View>
      <Image style={styles.image} source={{ uri: image }} />
      <View style={styles.detailsContainer}>
        <Text style={styles.name}>{name}</Text>
        <Text>{email}</Text>
        <Text>{description}</Text>
        <FlatList
          data={related}
          keyExtractor={(related) => related.id.toString()}
          renderItem={({ item }) => (
            <RelatedList
              image={item.image}
              name={item.name}
              status={item.status}
            />
          )}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  image: {
    width: "100%",
    height: 300,
  },
  detailsContainer: {
    padding: 20,
  },
  name: {
    fontWeight: "bold",
    fontSize: 25,
  },
});

export default StoreDetails;
</code>```

答:
You can use such function to get element with all related

```<code>const getWithRelated = (data, id) => {
  const items = []
  const item = data.find(v => v.id === id) // find item itself
  if (item) {
    items.push(
      item, // ad item
      ...data.filter(v => item.related.includes(v.id)) // and all related
    )
  }
  return items
}
</code>```

if perfomance is critical you can create an object, where ids are object keys, then search will be faster

```<code>const dataMap = data.reduce((agg, v) => { agg[v.id] = v; return agg }, {})

const getWithRelated = (data, id, dataMap) => {
  const items = []
  const item = dataMap[id]
  if (item) {
    items.push(
      item, // ad item
      ...item.related.map(relatedId => dataMap[relatedId]) // and all related
    )
  }
  return items
}
</code>```

so in your case you can replace

```<code>data.filter(value => value.id == id)
const related = [
  data
];
</code>```

with

```<code>const related = getWithRelated(data, id)
</code>```

Body:
I have a array of objects as a json file, I used the objects to display them on the list, When getting to details of that item it has a related items also.
I want to show related items for this item
Heres the json file

[
{
    "id": 1,
    "name": "Kling-Spencer",
    "description": "sed justo pellentesque viverra pede ac diam cras pellentesque volutpat dui maecenas tristique est et tempus semper est quam pharetra magna",
    "email": "fdory0@opera.com",
    "image": "http://dummyimage.com/300x300.bmp/cc0000/ffffff&text=Kling-Spencer",
    "related": [
        2,
        3,
        6,
        8,
        23
    ]
},
{
    "id": 2,
    "name": "Donnelly, Lockman and Dare",
    "description": "in felis donec semper sapien a libero nam dui proin leo odio porttitor id consequat in consequat ut nulla sed accumsan felis ut at dolor quis odio consequat varius integer",
    "email": "amcglaughn1@indiatimes.com",
    "image": "http://dummyimage.com/300x300.png/5fa2dd/ffffff&text=Donnelly",
    "related": null
},
{
    "id": 3,
    "name": "Klein LLC",
    "description": "dictumst aliquam augue quam sollicitudin vitae consectetuer eget rutrum at lorem integer tincidunt ante vel ipsum praesent blandit lacinia erat",
    "email": "kcaso2@miibeian.gov.cn",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Klein%20LLC",
    "related": [
        15,
        13,
        1,
        5,
        4
    ]
},
{
    "id": 4,
    "name": "Aufderhar Group",
    "description": "id justo sit amet sapien dignissim vestibulum vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae nulla dapibus dolor",
    "email": "ageleman3@zdnet.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Aufderhar%20Group",
    "related": null
},
{
    "id": 5,
    "name": "Lynch, Raynor and Mayer",
    "description": "ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae nulla dapibus dolor vel est donec odio justo sollicitudin ut suscipit a feugiat et eros vestibulum",
    "email": "dleece4@apache.org",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000",
    "related": null
},
{
    "id": 6,
    "name": "Kuhn, Miller and Carroll",
    "description": "in felis eu sapien cursus vestibulum proin eu mi nulla ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing",
    "email": "bgotliffe5@seesaa.net",
    "image": "http://dummyimage.com/300x300.png/5fa2dd/ffffff&text=Kuhn,%20Miller%20and%20Carroll",
    "related": [
        1,
        29,
        15
    ]
},
{
    "id": 7,
    "name": "Feest-Brown",
    "description": "ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing lorem vitae mattis nibh ligula nec sem duis aliquam convallis",
    "email": "mbridges6@deviantart.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Feest-Brown",
    "related": null
},
{
    "id": 8,
    "name": "Gutmann, Buckridge and Kris",
    "description": "quis lectus suspendisse potenti in eleifend quam a odio in hac habitasse platea dictumst maecenas ut massa quis augue luctus tincidunt nulla mollis molestie lorem",
    "email": "tdumbrell7@ted.com",
    "image": "http://dummyimage.com/300x300.bmp/ff4444/ffffff&text=Gutmann",
    "related": [
        14,
        20,
        23,
        27
    ]
},
{
    "id": 9,
    "name": "McLaughlin-Bogan",
    "description": "morbi quis tortor id nulla ultrices aliquet maecenas leo odio condimentum id luctus nec molestie sed justo pellentesque viverra pede ac diam cras pellentesque",
    "email": "lgadsdon8@joomla.org",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=McLaughlin-Bogan",
    "related": [
        6,
        9,
        12,
        30
    ]
},
{
    "id": 10,
    "name": "Kilback-Padberg",
    "description": "leo odio condimentum id luctus nec molestie sed justo pellentesque viverra pede ac diam cras pellentesque volutpat dui maecenas tristique est et tempus semper est quam pharetra magna ac",
    "email": "eodegaard9@dailymail.co.uk",
    "image": "http://dummyimage.com/300x300.png/ff4444/ffffff&text=Kilback-Padberg",
    "related": null
},
{
    "id": 11,
    "name": "Skiles LLC",
    "description": "rutrum at lorem integer tincidunt ante vel ipsum praesent blandit lacinia erat vestibulum sed magna at nunc commodo placerat praesent blandit nam nulla integer pede justo lacinia eget tincidunt eget",
    "email": "marchibolda@apple.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Skiles%20LLC",
    "related": [
        21,
        27,
        28,
        5
    ]
},
{
    "id": 12,
    "name": "McGlynn Group",
    "description": "nulla integer pede justo lacinia eget tincidunt eget tempus vel pede morbi porttitor lorem id ligula suspendisse ornare consequat lectus in est risus",
    "email": "eraggettb@nba.com",
    "image": "http://dummyimage.com/300x300.bmp/cc0000/ffffff&text=McGlynn%20Group",
    "related": [
        10,
        18,
        26
    ]
},
{
    "id": 13,
    "name": "Cassin-Kling",
    "description": "ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing lorem vitae mattis nibh ligula nec sem duis aliquam convallis",
    "email": "cdunbletonc@indiatimes.com",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Cassin-Kling",
    "related": [
        17,
        29,
        1,
        3,
        8
    ]
},
{
    "id": 14,
    "name": "Greenfelder, Conroy and Schinner",
    "description": "imperdiet nullam orci pede venenatis non sodales sed tincidunt eu felis fusce posuere felis sed lacus morbi sem mauris laoreet ut rhoncus aliquet pulvinar sed nisl nunc rhoncus",
    "email": "njamiesond@ehow.com",
    "image": "http://dummyimage.com/300x300.bmp/dddddd/000000&text=Greenfelder",
    "related": [
        18,
        21,
        27
    ]
},
{
    "id": 15,
    "name": "MacGyver, Huel and Lind",
    "description": "cubilia curae duis faucibus accumsan odio curabitur convallis duis consequat dui nec nisi volutpat eleifend donec ut dolor morbi vel lectus in",
    "email": "tclinche@soundcloud.com",
    "image": "http://dummyimage.com/300x300.bmp/ff4444/ffffff&text=MacGyver",
    "related": null
},
{
    "id": 16,
    "name": "Aufderhar-Little",
    "description": "nisl aenean lectus pellentesque eget nunc donec quis orci eget orci vehicula condimentum curabitur in libero ut massa volutpat convallis morbi odio odio elementum eu",
    "email": "epennellsf@symantec.com",
    "image": "http://dummyimage.com/300x300.png/dddddd/000000&text=Aufderhar-Little",
    "related": null
},
{
    "id": 17,
    "name": "Graham-Berge",
    "description": "non ligula pellentesque ultrices phasellus id sapien in sapien iaculis congue vivamus metus arcu adipiscing molestie hendrerit at vulputate vitae nisl aenean lectus pellentesque eget nunc donec quis orci",
    "email": "rvielg@weibo.com",
    "image": "http://dummyimage.com/300x300.bmp/ff4444/ffffff&text=Graham-Berge",
    "related": [
        12,
        16,
        29,
        30
    ]
},
{
    "id": 18,
    "name": "Gaylord, Klein and Donnelly",
    "description": "ac est lacinia nisi venenatis tristique fusce congue diam id ornare imperdiet sapien urna pretium nisl ut volutpat sapien arcu sed augue",
    "email": "estoyellh@bing.com",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Klein%20and%20Donnelly",
    "related": [
        6,
        7,
        9,
        18,
        21
    ]
},
{
    "id": 19,
    "name": "Gusikowski Group",
    "description": "lacus morbi quis tortor id nulla ultrices aliquet maecenas leo odio condimentum id luctus nec molestie sed justo pellentesque viverra pede ac diam cras pellentesque volutpat dui maecenas tristique",
    "email": "kpalatinoi@toplist.cz",
    "image": "http://dummyimage.com/300x300.jpg/ff4444/ffffff&text=Gusikowski",
    "related": [
        16,
        29,
        3
    ]
},
{
    "id": 20,
    "name": "Jaskolski-McKenzie",
    "description": "a nibh in quis justo maecenas rhoncus aliquam lacus morbi quis tortor id nulla ultrices aliquet maecenas leo odio condimentum id luctus nec",
    "email": "sloganj@japanpost.jp",
    "image": "http://dummyimage.com/300x300.bmp/cc0000/ffffff&text=Jaskolski-McKenzie",
    "related": [
        12,
        14,
        18
    ]
},
{
    "id": 21,
    "name": "Kautzer, Dooley and Kuhic",
    "description": "hac habitasse platea dictumst maecenas ut massa quis augue luctus tincidunt nulla mollis molestie lorem quisque ut erat curabitur gravida nisi at nibh in",
    "email": "snoodsk@over-blog.com",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=Kautzer",
    "related": [
        3,
        5,
        17,
        29,
        30
    ]
},
{
    "id": 22,
    "name": "Kohler, Tremblay and Bernier",
    "description": "in lacus curabitur at ipsum ac tellus semper interdum mauris ullamcorper purus sit amet nulla quisque arcu libero rutrum ac lobortis vel dapibus at",
    "email": "zsorriel@arizona.edu",
    "image": "http://dummyimage.com/300x300.png/ff4444/ffffff&text=Kohler",
    "related": null
},
{
    "id": 23,
    "name": "Cummerata, Trantow and Huels",
    "description": "potenti nullam porttitor lacus at turpis donec posuere metus vitae ipsum aliquam non mauris morbi non lectus aliquam sit amet diam in magna bibendum imperdiet nullam orci pede venenatis non",
    "email": "rshillingtonm@people.com.cn",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=Cummerata",
    "related": [
        5,
        4,
        13,
        23,
        27
    ]
},
{
    "id": 24,
    "name": "O'Reilly LLC",
    "description": "eu orci mauris lacinia sapien quis libero nullam sit amet turpis elementum ligula vehicula consequat morbi a ipsum integer a",
    "email": "tstaten@symantec.com",
    "image": "http://dummyimage.com/300x300.png/5fa2dd/ffffff&text=O'Reilly%20LLC",
    "related": [
        4,
        5,
        6,
        10
    ]
},
{
    "id": 25,
    "name": "Grant-Spencer",
    "description": "augue vel accumsan tellus nisi eu orci mauris lacinia sapien quis libero nullam sit amet turpis elementum ligula vehicula consequat morbi a ipsum integer a",
    "email": "bgrzegorczyko@vk.com",
    "image": "http://dummyimage.com/300x300.png/ff4444/ffffff&text=Grant-Spencer",
    "related": null
},
{
    "id": 26,
    "name": "Jacobi-Jaskolski",
    "description": "orci nullam molestie nibh in lectus pellentesque at nulla suspendisse potenti cras in purus eu magna vulputate luctus cum sociis natoque penatibus et magnis dis parturient montes",
    "email": "afranktonp@uol.com.br",
    "image": "http://dummyimage.com/300x300.bmp/5fa2dd/ffffff&text=Jacobi-Jaskolski",
    "related": null
},
{
    "id": 27,
    "name": "Heathcote LLC",
    "description": "curabitur in libero ut massa volutpat convallis morbi odio odio elementum eu interdum eu tincidunt in leo maecenas pulvinar lobortis est phasellus",
    "email": "sgeggusq@weather.com",
    "image": "http://dummyimage.com/300x300.bmp/5fa2dd/ffffff&text=Heathcote%20LLC",
    "related": [
        15,
        20,
        1,
        3
    ]
},
{
    "id": 28,
    "name": "Towne, Schaefer and Reichert",
    "description": "congue elementum in hac habitasse platea dictumst morbi vestibulum velit id pretium iaculis diam erat fermentum justo nec condimentum neque sapien placerat ante nulla justo aliquam quis",
    "email": "msnoadr@army.mil",
    "image": "http://dummyimage.com/300x300.jpg/ff4444/ffffff&text=Towne",
    "related": null
},
{
    "id": 29,
    "name": "Graham, Green and Roberts",
    "description": "vestibulum sagittis sapien cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus etiam vel augue vestibulum rutrum rutrum neque aenean auctor gravida",
    "email": "aflecknoes@redcross.org",
    "image": "http://dummyimage.com/300x300.jpg/dddddd/000000&text=Graham",
    "related": null
},
{
    "id": 30,
    "name": "Commings Group",
    "description": "luctus tincidunt nulla mollis molestie lorem quisque ut erat curabitur gravida nisi at nibh in hac habitasse platea dictumst aliquam augue",
    "email": "gmationt@slideshare.net",
    "image": "http://dummyimage.com/300x300.jpg/cc0000/ffffff&text=Commings%20Group",
    "related": null
}

]

As you can see for every item has a related, but related are just ID's how can i find each related item object and show them heres what i tried

this is the item details screen

   import React from "react";
import { View, Image, StyleSheet, Text, FlatList } from "react-native";

import RelatedList from "../components/RelatedList";

import api from "../apis/stores.json";

function StoreDetails(props) {
  const { navigation } = props;
  const id = navigation.getParam("id");
  const name = navigation.getParam("name");
  const email = navigation.getParam("email");
  const description = navigation.getParam("description");
  const image = navigation.getParam("image");
  const data = [api[0]];

  data.filter(value => value.id == id)
  const related = [
    data
  ];
  return (
    <View>
      <Image style={styles.image} source={{ uri: image }} />
      <View style={styles.detailsContainer}>
        <Text style={styles.name}>{name}</Text>
        <Text>{email}</Text>
        <Text>{description}</Text>
        <FlatList
          data={related}
          keyExtractor={(related) => related.id.toString()}
          renderItem={({ item }) => (
            <RelatedList
              image={item.image}
              name={item.name}
              status={item.status}
            />
          )}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  image: {
    width: "100%",
    height: 300,
  },
  detailsContainer: {
    padding: 20,
  },
  name: {
    fontWeight: "bold",
    fontSize: 25,
  },
});

export default StoreDetails;

Body:
You can use such function to get element with all related

const getWithRelated = (data, id) => {
  const items = []
  const item = data.find(v => v.id === id) // find item itself
  if (item) {
    items.push(
      item, // ad item
      ...data.filter(v => item.related.includes(v.id)) // and all related
    )
  }
  return items
}

if perfomance is critical you can create an object, where ids are object keys, then search will be faster

const dataMap = data.reduce((agg, v) => { agg[v.id] = v; return agg }, {})

const getWithRelated = (data, id, dataMap) => {
  const items = []
  const item = dataMap[id]
  if (item) {
    items.push(
      item, // ad item
      ...item.related.map(relatedId => dataMap[relatedId]) // and all related
    )
  }
  return items
}

so in your case you can replace

data.filter(value => value.id == id)
const related = [
  data
];

with

const related = getWithRelated(data, id)


问:
How to set value of the DatePicker in React
I want to set the date of DatePicker value when i click on the set date button but i am getting this error RangeError Invalid time value

```<code>import React from "react";
import "./styles.css";
import DatePicker from "react-datepicker";
export default function App() {
  const my_date = "26/05/2020";
  var [edit_check_date, set_edit_check_date] = React.useState(new Date());

  const set_date = () => {
    set_edit_check_date(my_date);
  };
  return (
    <div className="App">
      <input type="submit" value="set date" onClick={set_date} />
      <DatePicker
        dateFormat="dd/MM/yyyy"
        className="form-control"
        selected={edit_check_date}
        onChange={date => set_edit_check_date(date)}
      />
    </div>
  );
}
</code>```

答:
I have prepared an example using react-datepicker. I dont change any code from your one except I show an alert to see the changed date. Here is the complete example:

```<code>import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import React, {useState} from "react";

export default function DatePickerEx() {
    const [edit_check_date, set_edit_check_date] = useState(new Date());

    const open_modal = record => {
        /* record.check_date value is '25/05/2020' */
        set_edit_check_date(record.check_date); // This is making the error
    };

    function clickHandler(event) {
        const my_date = new Date( "2020-05-26");
        set_edit_check_date(my_date);
    }

    return (
        <div>
            <DatePicker
                dateFormat="dd/MM/yyyy"
                className="form-control"
                selected={edit_check_date}
                onChange={date => {
                    set_edit_check_date(date);
                    alert(date);
                }}
            />
            <button onClick={clickHandler}>Set 2020-05-26</button>
        </div>
    );
}
</code>```

Here is the Code Sandbox

Update

```<code>function clickHandler(event) {
    let date = "26/05/2020";
    let my_date = new Date(date.split("/").reverse().join("-"));
    console.log(date);
    console.log(my_date);
    set_edit_check_date(my_date);
}
</code>```

Body:
I want to set the date of DatePicker value when i click on the set date button but i am getting this error RangeError Invalid time value

import React from "react";
import "./styles.css";
import DatePicker from "react-datepicker";
export default function App() {
  const my_date = "26/05/2020";
  var [edit_check_date, set_edit_check_date] = React.useState(new Date());

  const set_date = () => {
    set_edit_check_date(my_date);
  };
  return (

      <input type="submit" value="set date" onClick={set_date} />
      <DatePicker
        dateFormat="dd/MM/yyyy"
        className="form-control"
        selected={edit_check_date}
        onChange={date => set_edit_check_date(date)}
      />

  );
}

Body:
I have prepared an example using react-datepicker. I dont change any code from your one except I show an alert to see the changed date. Here is the complete example:

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import React, {useState} from "react";

export default function DatePickerEx() {
    const [edit_check_date, set_edit_check_date] = useState(new Date());

    const open_modal = record => {
        /* record.check_date value is '25/05/2020' */
        set_edit_check_date(record.check_date); // This is making the error
    };

    function clickHandler(event) {
        const my_date = new Date( "2020-05-26");
        set_edit_check_date(my_date);
    }

    return (
        <div>
            <DatePicker
                dateFormat="dd/MM/yyyy"
                className="form-control"
                selected={edit_check_date}
                onChange={date => {
                    set_edit_check_date(date);
                    alert(date);
                }}
            />
            <button onClick={clickHandler}>Set 2020-05-26</button>
        </div>
    );
}

Here is the Code Sandbox

Update

function clickHandler(event) {
    let date = "26/05/2020";
    let my_date = new Date(date.split("/").reverse().join("-"));
    console.log(date);
    console.log(my_date);
    set_edit_check_date(my_date);
}