问:
Where do I find Angular CLI 7.3.9 default generated webpack settings file so I can build my overrides based on it?
I want to extend webpack building process for a project generated by Angular CLI v7.3.9.

I found out I have to use this tool:
https://github.com/just-jeb/angular-builders/tree/7.x.x/packages/custom-webpack

It seems a good solution, but unfortunately I can't find any example about extending existing Angular CLI config file.

I mean - I want to see what Angular CLI already generates for me, before I can think of correct overrides I should use in my custom builder override config. Being somewhat new to webpack, I need to learn what's already there to be able to figure out what I can adjust to avoid totally breaking the project.

Where do I find Angular CLI default generated webpack settings file so I can build my overrides based on it?

To be more specific, the problem is that building the project for production takes about 25 minutes. It is a large project with a few hundreds of form and grid components, and I see that current build process is spending about 20 minutes in ModuleConcatenationPlugin and 5 minutes in TerserPlugin without any serious load on the computer resources. I've heard ModuleConcatenationPlugin is being deprecated and thought that maybe I could use something better instead (UglifyJS ? optimization.concatenateModules ?), but at first I have to find out how Angular CLI uses it, so I can override it correctly.

答: technically in angular cli since v5 (as far as I know)  you have ng eject which will give you access to webpack config.


来源: stackexchange

问:
Python: How do I modify iterator value after some condition in 'for' loop
In such a loop, if the variable no is equal to 8, how can I return the 8th loop again? I couldn't do it, I'm confused.

no -= 1 command not working

```<code>for no in range(0,100):
    print("No:",no)
    if no == 8:
      no -= 1
      print("8 done return again")
</code>```

答:
If you want an infinite loop when you reach 8, then you can use this :</p>

```<code>no = 0
while no < 100:
    print("No:",no)
    if no == 8:
        print("8 done return again")
    else:
        no += 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In such a loop, if the variable no is equal to 8, how can I return the 8th loop again? I couldn't do it, I'm confused.

no -= 1 command not working

for no in range(0,100):
    print("No:",no)
    if no == 8:
      no -= 1
      print("8 done return again")

Body:
If you want an infinite loop when you reach 8, then you can use this :

no = 0
while no < 100:
    print("No:",no)
    if no == 8:
        print("8 done return again")
    else:
        no += 1


问:
How can I filtering for Tags(/part of String) in List-mode in OpenXava?

I want to filtering for tags in OpenXava, in List-mode.

Therefore I have a simple entity called Tag ( with int id, String name and String description)

I have a embedded Entity Details, which holds the Tag references and looks like this:

```<code>@Embeddable
public class Detail {

@ManyToOne(fetch = FetchType.LAZY, optional = true)
private Tag tag;

public Tag getTag() {
    return tag;
}

public void setTag(Tag tag) {
    this.tag = tag;
}

@Override
public String toString() {
    return tag.getName();

}
</code>```

My "main"-entity, called Target, represents an Object, which should be able to labeled with Tags.

Therefore have a Collection of Details, to assign Tags to Targets, which can't be represented in List-mode

```<code>@Tab(name="TargetTab", editors="List", properties="id, tags, manufacturer.name, owner.name, protocolID, idCreationDate, simDBID, remark, changeDate, photo, xphoto")
@Entity
public class Target implements Serializable {

...

@ElemtentCollection
@ListProperties("tag.number, tag.name, tag.description")
@Embedded
Collection<Detail> details;

    public Collection<Detail> getDetails() {
        return details;
    }

    public void setDetails(Collection<Detail> details) {
        this.details = details;
        tags = details.toString().substring(1, details.toString().length() - 1);
    }

...

</code>```

To represent Tags in List-mode, I created a String, which is filled with the name of the Tags

```<code>...
@ReadOnly
String tags;

...
</code>```

This creates a cloumn "Tags" in List-mode, which is representet by a String like: "a,b,c,d"

For filtering in List-mode, OpenXava has by default an input box, in which you can type a String like: "a,b" , to get all entries with the tags "a" and "b"

But if I enter "a,c", no results will be shown, even though there are entries with the tags "a,b,c,d"

My goal/problem:

I want a flexible filter, in which I can type something like: "a,c" and get all entries, that contain the tags "a" and "c"

I tried out to realize it by a "TagFilter.class" with "baseCondition="${tags} = ?" in the Target entity, with no usable result

答:
The tags property in Target has no relation with the tag values of details collection. The tags property in Target is just a new column in your table.

You have to options:

Define tags property using @Formula

Update the tags property each time a detail is added/removed (you can use JPA callback methods for that)

Body:
I want to filtering for tags in OpenXava, in List-mode.

Therefore I have a simple entity called Tag ( with int id, String name and String description)

I have a embedded Entity Details, which holds the Tag references and looks like this:

@Embeddable
public class Detail {

@ManyToOne(fetch = FetchType.LAZY, optional = true)
private Tag tag;

public Tag getTag() {
    return tag;
}

public void setTag(Tag tag) {
    this.tag = tag;
}

@Override
public String toString() {
    return tag.getName();

}

My "main"-entity, called Target, represents an Object, which should be able to labeled with Tags.

Therefore have a Collection of Details, to assign Tags to Targets, which can't be represented in List-mode

@Tab(name="TargetTab", editors="List", properties="id, tags, manufacturer.name, owner.name, protocolID, idCreationDate, simDBID, remark, changeDate, photo, xphoto")
@Entity
public class Target implements Serializable {

...

@ElemtentCollection
@ListProperties("tag.number, tag.name, tag.description")
@Embedded
Collection<Detail> details;

    public Collection<Detail> getDetails() {
        return details;
    }

    public void setDetails(Collection<Detail> details) {
        this.details = details;
        tags = details.toString().substring(1, details.toString().length() - 1);
    }

...

To represent Tags in List-mode, I created a String, which is filled with the name of the Tags

...
@ReadOnly
String tags;

...

This creates a cloumn "Tags" in List-mode, which is representet by a String like: "a,b,c,d"

For filtering in List-mode, OpenXava has by default an input box, in which you can type a String like: "a,b" , to get all entries with the tags "a" and "b"

But if I enter "a,c", no results will be shown, even though there are entries with the tags "a,b,c,d"

My goal/problem:

I want a flexible filter, in which I can type something like: "a,c" and get all entries, that contain the tags "a" and "c"

I tried out to realize it by a "TagFilter.class" with "baseCondition="${tags} = ?" in the Target entity, with no usable result


问:
Problem with storing german words into the MySql DB....?
I am facing an small issue in my project When I am trying to store some German words into the MYSQL Database. When this German words contains umlauts i.e. characters ä, ö, ß, ü etc., they are not stored as they are.....?

I want to store them as it is into the Database.To do so I tried to change the COLLATION to UTF8-general-ci, and others in the list using PHP myAdmin. But none of them is working for me.

Am I in the right way or I have to do something else.

Please suggest some help.

Thanks In Advance......

答:
You have to choose the right transfer encoding either. Call

```<code>SET NAMES utf8
</code>```

before inserting the data and make sure that the german words are utf8-encoded before inserting.

ContentLicense: CC BY-SA 3.0

Body:
You have to choose the right transfer encoding either. Call

SET NAMES utf8

before inserting the data and make sure that the german words are utf8-encoded before inserting.


问:
How to get local JSON (fetch)?
How to get local JSON (fetch)?

I do a service, then I call the class instance

This is not how it works:

Services.js

```<code>export default class ApiService {
    async GetPeople() {
        const request = await fetch('./data.json');
        if(!request.ok) {
            throw new Error('Что-то пошло не так', request.status)
        } else {
            return request.json()
        };
    };
};
</code>```

Userslist.js

```<code>import Service from '../../../Services';

const UsersListContainer = () => {

    const api = new Service();

    useEffect(() => {
        api.GetPeople()
        .then(data => console.log(data))
    }, [api])

    return (
        <UsersListView />
    );
};

export default UsersListContainer;
</code>```

答:
You have to await the <code>.json()</code> the request before return:  </p>

```<code>export default class ApiService {
    async GetPeople() {
        const request = await fetch('./data.json');
        const json = await request.json(); // <--------------await the .json() here
        if(!request.ok) {
            throw new Error('Что-то пошло не так', request.status)
        } else {
            return json; // return it here
        };
    };
};
</code>```

Title: How to get local JSON (fetch)?

Body:
How to get local JSON (fetch)?

I do a service, then I call the class instance

This is not how it works:

Services.js

export default class ApiService {
    async GetPeople() {
        const request = await fetch('./data.json');
        if(!request.ok) {
            throw new Error('Что-то пошло не так', request.status)
        } else {
            return request.json()
        };
    };
};

Userslist.js

import Service from '../../../Services';

const UsersListContainer = () => {

    const api = new Service();

    useEffect(() => {
        api.GetPeople()
        .then(data => console.log(data))
    }, [api])

    return (
        <UsersListView />
    );
};

export default UsersListContainer;

Body:
You have to await the .json() the request before return:

export default class ApiService {
    async GetPeople() {
        const request = await fetch('./data.json');
        const json = await request.json(); // <--------------await the .json() here
        if(!request.ok) {
            throw new Error('Что-то пошло не так', request.status)
        } else {
            return json; // return it here
        };
    };
};


问:
Map two arrays by index in Snowflake
I have a table with two columns with comma separated values. I would like to map them by index

```<code>item_list             item_type
'400,500,600,700'    'st1,st2,st2'
</code>```

Desired Output

```<code>item    type
400     st1
500     st2
600     st2
700     NULL
</code>```

I have tried using the following but it just repeates the value or each item.

```<code>select distinct a.value::string as a1
       ,b.value::string as a2
from (select '400,,500,600,700'as c1
         ,'st1,st2,st2' as c2
     ) as x,
     lateral flatten(input=>split(c1, ',')) a,
     lateral flatten(input=>split(c2, ',')) b
order by a1;
</code>```

答:
One way is to flatten them separately, and join on their indexes:

```<code>with
x as (select '400,500,600,700'as c1,'st1,st2,st2' as c2),
a as (select value::string a1, index from x, lateral flatten(input=>split(x.c1, ','))),
b as (select value::string a2, index from x, lateral flatten(input=>split(x.c2, ',')))
select a1,a2 from a full outer join b on a.index=b.index;
</code>```

Similarly, with SPLIT_TO_TABLE():

```<code>with
x as (select '400,500,600,700'as c1,'st1,st2,st2' as c2),
a as (select value::string a1, index from x, lateral split_to_table(x.c1, ',')),
b as (select value::string a2, index from x, lateral split_to_table(x.c2, ','))
select a1,a2 from a full outer join b on a.index=b.index;
</code>```

Further clarification by @Andrii Soldatenko -- Thank you:

to explain idea i would recommend to run first this:

```<code>select * from(select 'st1,st2' as c2) as x2,
                                            lateral flatten(input=>split(c2, ',')) b;
+---------+-----+------+------+-------+-------+----------+
| C2      | SEQ | KEY  | PATH | INDEX | VALUE | THIS     |
|---------+-----+------+------+-------+-------+----------|
| st1,st2 |   1 | NULL | [0]  |     0 | "st1" | [        |
|         |     |      |      |       |       |   "st1", |
|         |     |      |      |       |       |   "st2"  |
|         |     |      |      |       |       | ]        |
| st1,st2 |   1 | NULL | [1]  |     1 | "st2" | [        |
|         |     |      |      |       |       |   "st1", |
|         |     |      |      |       |       |   "st2"  |
|         |     |      |      |       |       | ]        |
+---------+-----+------+------+-------+-------+----------+
2 Row(s) produced. Time Elapsed: 1.357s
</code>```

Title: Map two arrays by index in Snowflake

Body:
I have a table with two columns with comma separated values. I would like to map them by index

item_list             item_type
'400,500,600,700'    'st1,st2,st2'

Desired Output

item    type
400     st1
500     st2
600     st2
700     NULL

I have tried using the following but it just repeates the value or each item.

select distinct a.value::string as a1
       ,b.value::string as a2
from (select '400,,500,600,700'as c1
         ,'st1,st2,st2' as c2
     ) as x,
     lateral flatten(input=>split(c1, ',')) a,
     lateral flatten(input=>split(c2, ',')) b
order by a1;

Body:
One way is to flatten them separately, and join on their indexes:

with
x as (select '400,500,600,700'as c1,'st1,st2,st2' as c2),
a as (select value::string a1, index from x, lateral flatten(input=>split(x.c1, ','))),
b as (select value::string a2, index from x, lateral flatten(input=>split(x.c2, ',')))
select a1,a2 from a full outer join b on a.index=b.index;

Similarly, with SPLIT_TO_TABLE():

with
x as (select '400,500,600,700'as c1,'st1,st2,st2' as c2),
a as (select value::string a1, index from x, lateral split_to_table(x.c1, ',')),
b as (select value::string a2, index from x, lateral split_to_table(x.c2, ','))
select a1,a2 from a full outer join b on a.index=b.index;

Further clarification by @Andrii Soldatenko -- Thank you:

to explain idea i would recommend to run first this:

select * from(select 'st1,st2' as c2) as x2,
                                            lateral flatten(input=>split(c2, ',')) b;
+---------+-----+------+------+-------+-------+----------+
| C2      | SEQ | KEY  | PATH | INDEX | VALUE | THIS     |
|---------+-----+------+------+-------+-------+----------|
| st1,st2 |   1 | NULL | [0]  |     0 | "st1" | [        |
|         |     |      |      |       |       |   "st1", |
|         |     |      |      |       |       |   "st2"  |
|         |     |      |      |       |       | ]        |
| st1,st2 |   1 | NULL | [1]  |     1 | "st2" | [        |
|         |     |      |      |       |       |   "st1", |
|         |     |      |      |       |       |   "st2"  |
|         |     |      |      |       |       | ]        |
+---------+-----+------+------+-------+-------+----------+
2 Row(s) produced. Time Elapsed: 1.357s


问:
What is wrong with my setup.py to install all dependencies in python 3.8.1
I have the below setup.py script. When I execute the command setup.py install, I do not see the python packages installed in my system. In case of java, we use maven or gradle so that it can automatically download and install in the system. I want exact feature in setup.py. I see that colorama, configparser are not installed, I manually installed setuptools and cx-Freeze using pip command. Below is my setup.py script contents.

```<code>from setuptools import setup, find_packages, Command

setup(
    name="Runner",  # program name
    version="0.0.1",
    description='A utility to build an exe',
    author="Debadatta Mishra",
    author_email="deba.java@gmail.com",
    python_requires='>=3.6',
    install_requires=['configparser==4.0.2', 'colorama==0.4.3', 'setuptools==45.2.0', 'cx-Freeze==6.1']
)
</code>```

If I execute pip list, I do not see colorama, configparser etc. Please help me , I am new to python programming.

To run the setup script, I use the command python setup.py install in command prompt.

答:
There is nothing wrong with your setup.py. There must be something wrong with your environment, because when your script is running in clean docker environment is works.

Create clean environment by using such a Dockerfile

```<code>FROM python:3.8.1-buster
RUN mkdir /debmis
ADD setup.py /debmis
WORKDIR /debmis
RUN python setup.py install
CMD /usr/bin/env pip list
</code>```

Build it (having your setup.py in current directory):

```<code>docker build -t python3 .
</code>```

And run

```<code>docker run python3

Package      Version
------------ -------
colorama     0.4.3
configparser 4.0.2
cx-Freeze    6.1
pip          20.0.2
Runner       0.0.1
setuptools   45.1.0
wheel        0.34.2
</code>```

I suggest comparing difference between python setup.py install executed in your environment and executed by docker build.

Body:
I have the below setup.py script. When I execute the command setup.py install, I do not see the python packages installed in my system. In case of java, we use maven or gradle so that it can automatically download and install in the system. I want exact feature in setup.py. I see that colorama, configparser are not installed, I manually installed setuptools and cx-Freeze using pip command. Below is my setup.py script contents.

from setuptools import setup, find_packages, Command

setup(
    name="Runner",  # program name
    version="0.0.1",
    description='A utility to build an exe',
    author="Debadatta Mishra",
    author_email="deba.java@gmail.com",
    python_requires='>=3.6',
    install_requires=['configparser==4.0.2', 'colorama==0.4.3', 'setuptools==45.2.0', 'cx-Freeze==6.1']
)

If I execute pip list, I do not see colorama, configparser etc. Please help me , I am new to python programming.

To run the setup script, I use the command python setup.py install in command prompt.

Body:
There is nothing wrong with your setup.py. There must be something wrong with your environment, because when your script is running in clean docker environment is works.

Create clean environment by using such a Dockerfile

FROM python:3.8.1-buster
RUN mkdir /debmis
ADD setup.py /debmis
WORKDIR /debmis
RUN python setup.py install
CMD /usr/bin/env pip list

Build it (having your setup.py in current directory):

docker build -t python3 .

And run

docker run python3

Package      Version
------------ -------
colorama     0.4.3
configparser 4.0.2
cx-Freeze    6.1
pip          20.0.2
Runner       0.0.1
setuptools   45.1.0
wheel        0.34.2

I suggest comparing difference between python setup.py install executed in your environment and executed by docker build.


问:
How can I find gameobject with tag that are childs of a specific parent?
```<code>public void UpdateOrAddShaderPrefabToDoors()
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        HashSet<GameObject> prefabParentsOfDoorsNeedRemove = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            List<GameObject> shadersChildren = new List<GameObject>();
            for (int i=0; i<doorGameObject.transform.childCount ;i++)
            {
                if (doorGameObject.transform.GetChild(i).name.StartsWith(c_doorShieldFxLocked))
                {
                    shadersChildren.Add(doorGameObject.transform.GetChild(i).gameObject);
                }
            }
            foreach (GameObject shader in shadersChildren)
            {
                GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(shader);
                prefabParentsOfDoorsNeedRemove.Add(outermostPrefabInstanceRoot);
            }
        });

        foreach (GameObject parent in prefabParentsOfDoorsNeedRemove)
        {
            Modify(parent, RemoveFunc);
        }

        HashSet<GameObject> prefabParentsOfDoors = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(doorGameObject);
            prefabParentsOfDoors.Add(outermostPrefabInstanceRoot);
        });

        foreach (GameObject parent in prefabParentsOfDoors)
        {
            AddShaderToPrefab(parent);
        }
    }
</code>```

When doing :

```<code>GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);
</code>```

It will find all "Door_Left" and "Door_Right" but some of them are childs of other gameobjects and I want to find the door left and door right only that are childs of : Wall_Door_Long_01

答:
Have you tried something like

GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft).Where(o => o.transform.parent.name == "Wall_Door_Long_01");

You might want to use string compare rather than == but, as an example.

Body:
public void UpdateOrAddShaderPrefabToDoors()
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        HashSet<GameObject> prefabParentsOfDoorsNeedRemove = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            List<GameObject> shadersChildren = new List<GameObject>();
            for (int i=0; i<doorGameObject.transform.childCount ;i++)
            {
                if (doorGameObject.transform.GetChild(i).name.StartsWith(c_doorShieldFxLocked))
                {
                    shadersChildren.Add(doorGameObject.transform.GetChild(i).gameObject);
                }
            }
            foreach (GameObject shader in shadersChildren)
            {
                GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(shader);
                prefabParentsOfDoorsNeedRemove.Add(outermostPrefabInstanceRoot);
            }
        });

        foreach (GameObject parent in prefabParentsOfDoorsNeedRemove)
        {
            Modify(parent, RemoveFunc);
        }

        HashSet<GameObject> prefabParentsOfDoors = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(doorGameObject);
            prefabParentsOfDoors.Add(outermostPrefabInstanceRoot);
        });

        foreach (GameObject parent in prefabParentsOfDoors)
        {
            AddShaderToPrefab(parent);
        }
    }

When doing :

GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

It will find all "Door_Left" and "Door_Right" but some of them are childs of other gameobjects and I want to find the door left and door right only that are childs of : Wall_Door_Long_01


问:
Extract all unique URL from log using sed
Can you help me with correct regexp from the sed syntaxis point of view? For now every regexp that i can write is marked by terminal as invalid.</p>

答:
If your log syntax is uniform, use this command

```<code>cut -f4 -d\" < logfile | sort -u
</code>```

If you want to skip the query  string from uniqness, use this

```<code>cut -f4 -d\" < logfile | cut -f1 -d\? | sort -u
</code>```

Explanation

Filter the output with the cut command, take the 4th field (-f4) using " as separator (-d\"). The same with the second filter, using ? as separator

Body:
If your log syntax is uniform, use this command

cut -f4 -d\" < logfile | sort -u

If you want to skip the query  string from uniqness, use this

cut -f4 -d\" < logfile | cut -f1 -d\? | sort -u

Explanation

Filter the output with the cut command, take the 4th field (-f4) using " as separator (-d\"). The same with the second filter, using ? as separator


问:
Renaming object properties in an array of objects
I have the following structure:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};
</code>```

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};
</code>```

I have tried various things like the following for example:

```<code>var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});
</code>```

However the spread pushes CreditNoteNumber outside the object.

答:
```<code>var changed = data.invoices.map(function(item) {
  return {
    Date: item.Date,
    CreditNoteNumber: item.InvoiceNumber
  };
});
</code>```

Body:
I have the following structure:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};

I have tried various things like the following for example:

var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});

However the spread pushes CreditNoteNumber outside the object.


问:
Docker image build with PHP zip extension shows "bundled libzip is deprecated" warning
I have a Dockerfile with a build command like this:

```<code>#install some base extensions
RUN apt-get install -y \
        zlib1g-dev \
        zip \
  && docker-php-ext-install zip
</code>```

I get this warning from build output:

WARNING: Use of bundled libzip is deprecated and will be removed.

  configure: WARNING: Some features such as encryption and bzip2 are not available.

  configure: WARNING: Use system library and --with-libzip is
  recommended.

What is the correct way to install the zip extension without these warnings?

My complete Dockerfile looks like:

```<code>FROM php:7.2-apache

RUN apt-get clean
RUN apt-get update

#install some basic tools
RUN apt-get install -y \
        git \
        tree \
        vim \
        wget \
        subversion

#install some base extensions
RUN apt-get install -y \
        zlib1g-dev \
        zip \
  && docker-php-ext-install zip

#setup composer
RUN curl -sS https://getcomposer.org/installer | php \
        && mv composer.phar /usr/local/bin/ \
        && ln -s /usr/local/bin/composer.phar /usr/local/bin/composer

WORKDIR /var/www/
</code>```

答:
In order to build a php/apache container you just have to first install libzip-dev library. At least using the docker image php:7.3-apache

```<code>FROM php:7.3-apache
MAINTAINER XXX

RUN apt-get update
RUN apt-get install -y libzip-dev
RUN docker-php-ext-install zip
</code>```

Hope it helps

Body:
I have a Dockerfile with a build command like this:

#install some base extensions
RUN apt-get install -y \
        zlib1g-dev \
        zip \
  && docker-php-ext-install zip

I get this warning from build output:

WARNING: Use of bundled libzip is deprecated and will be removed.

  configure: WARNING: Some features such as encryption and bzip2 are not available.

  configure: WARNING: Use system library and --with-libzip is
  recommended.

What is the correct way to install the zip extension without these warnings?

My complete Dockerfile looks like:

FROM php:7.2-apache

RUN apt-get clean
RUN apt-get update

#install some basic tools
RUN apt-get install -y \
        git \
        tree \
        vim \
        wget \
        subversion

#install some base extensions
RUN apt-get install -y \
        zlib1g-dev \
        zip \
  && docker-php-ext-install zip

#setup composer
RUN curl -sS https://getcomposer.org/installer | php \
        && mv composer.phar /usr/local/bin/ \
        && ln -s /usr/local/bin/composer.phar /usr/local/bin/composer

WORKDIR /var/www/

Body:
In order to build a php/apache container you just have to first install libzip-dev library. At least using the docker image php:7.3-apache

FROM php:7.3-apache
MAINTAINER XXX

RUN apt-get update
RUN apt-get install -y libzip-dev
RUN docker-php-ext-install zip

Hope it helps


问:
How to access table in laravel using eloquent with is not directly attached
I have the following table structure and i want to access Portal which is assigned to specific case but using patient info. For example i have the following query

```<code>$data['patients'] = Patient::with('operator')->where('case_id', $case_id)->get();
</code>```

this query returns the operator assigned to the patient now hare i want the portal name assigned to the patient using case.

Portal Table

```<code>id   Name
1   A
2   B
</code>```

Cases

```<code>id     Name    case_number     patient_name     user_id     portal_id
1      Farz       456            sania             5           1
</code>```

Patient

```<code>id    case_id   operator_id
2     456            5
</code>```

答:
Assuming you properly created the laravel relationships among Portal, Case, Patient and Operator models, you can access in this way:

```<code>// you get Case model
$case = \App\Case::findOrFail($case_id);

// patients: there is a hasMany relationship between Case and Patient models
$data['patients'] = $case->patients;

// there is a belongsTo relationship between Case and Portal models
$portal_name = $case->portal->Name;
</code>```

Body:
I have the following table structure and i want to access Portal which is assigned to specific case but using patient info. For example i have the following query

$data['patients'] = Patient::with('operator')->where('case_id', $case_id)->get();

this query returns the operator assigned to the patient now hare i want the portal name assigned to the patient using case.

Portal Table

id   Name
1   A
2   B

Cases

id     Name    case_number     patient_name     user_id     portal_id
1      Farz       456            sania             5           1

Patient

id    case_id   operator_id
2     456            5

Body:
Assuming you properly created the laravel relationships among Portal, Case, Patient and Operator models, you can access in this way:

// you get Case model
$case = \App\Case::findOrFail($case_id);

// patients: there is a hasMany relationship between Case and Patient models
$data['patients'] = $case->patients;

// there is a belongsTo relationship between Case and Portal models
$portal_name = $case->portal->Name;


问:
How to print multiple integer array based on user Input?
I am creating a java program which prompts user for the number of items in an array (a non-negative integer), reads it, and saves it in an int variable. It then prompts user for the values of all the items and saves them in an int array. Afterwards, the program prints the content of the array in the form of [x1, x2, ... ,xn]. No user validation is required. The program was supposed to work out fine, however, when I tried to enter the multiple inputs for the user, there is something wrong with the output.

Instead of showing this:

```<code>Enter the number of items: 2
Enter the value of all items (separated by space): 88
Enter the value of all items (separated by space): 99
The values are: [88, 99]
</code>```

The output becomes like this:

```<code>Enter the number of items: 2
Enter the value of all items (separated by space) : 88
Enter the value of all items (separated by space) : 99
The values are: [88]
The values are: [99]
</code>```

Also, when I enter 0 for the number of items, the output was supposed to show this

```<code>Enter the number of items: 0
The values are: []
</code>```

But my output shows this instead:

```<code>Enter the number of items: 0
</code>```

It does not even show the brackets of the values when the number of items is 0. Attached below is my codings:

```<code>import java.util.Scanner;

public class PrintArray{

public static void main(String[] args) {
 // Declare variables
      int numItems;
      int[] items;  // Declare array name, to be allocated after numItems is known

  // Prompt for a non-negative integer for the number of items;
  // and read the input as "int". No input validation.
  Scanner in = new Scanner(System.in);
  System.out.print("Enter the number of items: ");
  numItems = in.nextInt();

  // Allocate the array
  items = new int[numItems];

  // Prompt and read the items into the "int" array, if array length > 0
  if (items.length > 0) {

     for (int i = 0; i < items.length; ++i) {
        System.out.print("Enter the value of all items (separated by space) : ");
        items[i] = in.nextInt();

     }
  }

  // Print array contents, need to handle first item and subsequent items differently

  for (int i = 0; i < items.length; ++i) {
     if (i == 0) {
        // Print the first item without a leading commas
        System.out.println("The values are: [" + items[i] + "]");
     } else {
        // Print the subsequent items with a leading commas
        System.out.println("The values are: [" + items[i] + "]");
     }

  }

  }
}
</code>```

It would be good if someone can help me with that. Many thanks!

答:
In the loop you're printing the whole sentence, instead you may append the array element to a String, for printing later.
Second problem is because array is empty, which makes loop condition false in the first iteration itself. Hence loop body is not executed.

You can try something like below.

```<code>String output = "[";
for (int i = 0; i < items.length; ++i) {
    output += items[i] + ", ";
}

// remove last comma and space
output = output.substring(0, output.length() - 2);
output += "]";
System.out.println("The values are: " + output);
</code>```

Body:
I am creating a java program which prompts user for the number of items in an array (a non-negative integer), reads it, and saves it in an int variable. It then prompts user for the values of all the items and saves them in an int array. Afterwards, the program prints the content of the array in the form of [x1, x2, ... ,xn]. No user validation is required. The program was supposed to work out fine, however, when I tried to enter the multiple inputs for the user, there is something wrong with the output.

Instead of showing this:

Enter the number of items: 2
Enter the value of all items (separated by space): 88
Enter the value of all items (separated by space): 99
The values are: [88, 99]

The output becomes like this:

Enter the number of items: 2
Enter the value of all items (separated by space) : 88
Enter the value of all items (separated by space) : 99
The values are: [88]
The values are: [99]

Also, when I enter 0 for the number of items, the output was supposed to show this

Enter the number of items: 0
The values are: []

But my output shows this instead:

Enter the number of items: 0

It does not even show the brackets of the values when the number of items is 0. Attached below is my codings:

import java.util.Scanner;

public class PrintArray{

public static void main(String[] args) {
 // Declare variables
      int numItems;
      int[] items;  // Declare array name, to be allocated after numItems is known

  // Prompt for a non-negative integer for the number of items;
  // and read the input as "int". No input validation.
  Scanner in = new Scanner(System.in);
  System.out.print("Enter the number of items: ");
  numItems = in.nextInt();

  // Allocate the array
  items = new int[numItems];

  // Prompt and read the items into the "int" array, if array length > 0
  if (items.length > 0) {

     for (int i = 0; i < items.length; ++i) {
        System.out.print("Enter the value of all items (separated by space) : ");
        items[i] = in.nextInt();

     }
  }

  // Print array contents, need to handle first item and subsequent items differently

  for (int i = 0; i < items.length; ++i) {
     if (i == 0) {
        // Print the first item without a leading commas
        System.out.println("The values are: [" + items[i] + "]");
     } else {
        // Print the subsequent items with a leading commas
        System.out.println("The values are: [" + items[i] + "]");
     }

  }

  }
}

It would be good if someone can help me with that. Many thanks!

Body:
In the loop you're printing the whole sentence, instead you may append the array element to a String, for printing later.
Second problem is because array is empty, which makes loop condition false in the first iteration itself. Hence loop body is not executed.

You can try something like below.

String output = "[";
for (int i = 0; i < items.length; ++i) {
    output += items[i] + ", ";
}

// remove last comma and space
output = output.substring(0, output.length() - 2);
output += "]";
System.out.println("The values are: " + output);


问:
Multiple MySQL versions
We have a Linux server running Red Hat Enterprise 3 and MySQL 3.23. This server has a number of websites on it.

We have a new website that we want to put on this server that uses MySQL 4/5. Is it possible to run the two versions of MySQL in parallel?

If so, how?

答:
Yes, it's possible, but tricky.

Firstly, it's probably best not to use the RedHat supplied RPMS - they'll cause all sorts of dependency issues.

In essence, all you need to do is to build the two versions, and install them into completely different directories.

Then you need to make sure that they're configured with separate:

data directories

TCP ports

Local connection sockets

PID state files

In practise that can be done my creating two my.cnf files, and making sure those are chosen in the command line parameters in the daemon start up scripts.

Note also that you'll need to be very careful with any shared libraries that might get built, particularly if you're running any client applications on the same server.

This gets nasty if, for example, you want Perl::DBD::mysql running, as it's not simple to arrange for there to be two copies, with each linked against a different version of the shared libraries.

OwnerDisplayName: Blatfrig

ContentLicense: CC BY-SA 2.5

Title: Multiple MySQL versions

LastEditorDisplayName: Svante

OwnerDisplayName: Alnitak


问:
Access 2003 MDB properties
With an Access 2003 MDB, is there an inherent  MDB property we can set that disallows or blocks object exports?  In other words, assume MDBs "A" and "B". If I'm in "B" and try to import objects from "A" (i.e. File | Get External Data | Import), we want it to fail because "A" has set some property that locks out its capability to export objects.</p>

答:
Just been having a very similar problem to this. In my case I want to keep the backend password from the users because there is a very small amount of sensitive data in there (and I don't want them messing the other stuff up too easily).

One table in particular I don't want them to have any access to, or at least to minimise the chances of them getting read/write access to this table.

Fortunately, this table is only needed for a short time, so when I need it I use a bit of code to add a link to the table in the back-end database, use the table, then remove the link after it is done.

The code to add the table:

Dim db As Database, tbl As TableDef
Set tbl = New TableDef
With tbl
    tbl.Name = "SecretTable"
    tbl.SourceTableName = "SecretTable"
    tbl.Connect = "MS Access;PWD=BackendPassword;DATABASE=c:\location of database\Backend.mdb"
End With
Call db.TableDefs.Append(tbl)
```

<p>The code to remove the table after it has been used:</p>

<pre class="lang-vb prettyprint-override"><code>Dim db As Database
Set db = CurrentDb
Call db.TableDefs.Delete("SecretTable")
</code>```

This works in my situation because the table is only being used briefly. If it were a table being used constantly, clever users could probably get around it.

Title: Access 2003 MDB properties

Body:
Just been having a very similar problem to this. In my case I want to keep the backend password from the users because there is a very small amount of sensitive data in there (and I don't want them messing the other stuff up too easily).

One table in particular I don't want them to have any access to, or at least to minimise the chances of them getting read/write access to this table.

Fortunately, this table is only needed for a short time, so when I need it I use a bit of code to add a link to the table in the back-end database, use the table, then remove the link after it is done.

The code to add the table:

Dim db As Database, tbl As TableDef
Set tbl = New TableDef
With tbl
    tbl.Name = "SecretTable"
    tbl.SourceTableName = "SecretTable"
    tbl.Connect = "MS Access;PWD=BackendPassword;DATABASE=c:\location of database\Backend.mdb"
End With
Call db.TableDefs.Append(tbl)

The code to remove the table after it has been used:

Dim db As Database
Set db = CurrentDb
Call db.TableDefs.Delete("SecretTable")

This works in my situation because the table is only being used briefly. If it were a table being used constantly, clever users could probably get around it.


问:
Date not showing in my Excel file which is created on Nodejs with Exceljs
```<code>app.get("/get_report", upload.any(), function(req, res) {
  var options = {
    filename: './streamed-workbook.xlsx',
    useStyles: true,
    useSharedStrings: true
};

var workbook = new Excel.stream.xlsx.WorkbookWriter(options);
var worksheet = workbook.addWorksheet('My Sheet');
worksheet.columns = [
    { header: 'Id', key: 'id', width: 10 },
    { header: 'Name', key: 'name', width: 32 },
    { header: 'D.O.B.', key: 'DOB', width: 10 }
];

worksheet.addRow({id: 1, name: 'John Doe', DOB: new Date(1970,1,1).toString()});
worksheet.addRow({id: 2, name: 'Jane Doe', DOB: new Date(1965,1,7).toString()});
worksheet.commit();

workbook.commit().then(function(){
    console.log('xls file is written.');
});
});
</code>```

This is my api and what i find after opening the excel file that is created is that i see the columns of DATE empty instead of the data i defined here.

答: The problem is with your xls document viewer. I've copied your code and ran on my local machine than the xls file is created. Than viewed the file with WPS Spreadsheets.

Body:
app.get("/get_report", upload.any(), function(req, res) {
  var options = {
    filename: './streamed-workbook.xlsx',
    useStyles: true,
    useSharedStrings: true
};

var workbook = new Excel.stream.xlsx.WorkbookWriter(options);
var worksheet = workbook.addWorksheet('My Sheet');
worksheet.columns = [
    { header: 'Id', key: 'id', width: 10 },
    { header: 'Name', key: 'name', width: 32 },
    { header: 'D.O.B.', key: 'DOB', width: 10 }
];

worksheet.addRow({id: 1, name: 'John Doe', DOB: new Date(1970,1,1).toString()});
worksheet.addRow({id: 2, name: 'Jane Doe', DOB: new Date(1965,1,7).toString()});
worksheet.commit();

workbook.commit().then(function(){
    console.log('xls file is written.');
});
});

This is my api and what i find after opening the excel file that is created is that i see the columns of DATE empty instead of the data i defined here.


答:
Normaly, if you did the correct relations in your models, you can only use :

```<code>$data['patients'] = Patient::with('operator')->where('case_id', $case_id)->get();
$portals = [];

foreach ($data['patients'] as $patient) {
    foreach ($patient->cases as $case) {
        $portals []= $case->portal;
    }
}
</code>```

I suppose there is a HasMany between Patient and Cases, and a BelongTo between Cases and Portal ?

If you want to lazy load the data, you can try :

```<code>$data['patients'] = Patient::with(['operator', 'cases.portal'])->where('case_id', $case_id)->get();
</code>```

Title: How to access table in laravel using eloquent with is not directly attached

Body:
Normaly, if you did the correct relations in your models, you can only use :

$data['patients'] = Patient::with('operator')->where('case_id', $case_id)->get();
$portals = [];

foreach ($data['patients'] as $patient) {
    foreach ($patient->cases as $case) {
        $portals []= $case->portal;
    }
}

I suppose there is a HasMany between Patient and Cases, and a BelongTo between Cases and Portal ?

If you want to lazy load the data, you can try :

$data['patients'] = Patient::with(['operator', 'cases.portal'])->where('case_id', $case_id)->get();


问:
concurrent git pull and push on same remote repo from different locations
Suppose I'm pulling or cloning from some remote git repo
What happens if
1) after I started pulling/cloning - someone start to push to that remote repo in the middle?
2) while someone is in the middle of pushing code to remote git repo - and I start pulling cloning it?

What do I end up with in each of the cases?

Thanks

答:
There's no problem in either case.  In case 1) there'll be a point when the ref (a branch name, typically) is updated when someone's pushing, and any fetch (an essential part of clone and pull) will either get the old value before that point or the new one afterwards.  The ref is only updated when all the objects required for it are in the remote repository's object database, so there's no problem there. 2)  Similarly, if the fetch that makes up your pull happens after the ref that's being pushed to is updated, then you'll get the new value, otherwise you'll get the old one.

(One possible exception to this is the "dumb HTTP" transport, where you need to run git update-server-info in the remote repository after each push, so it's possible that a fetch will fail immmediately after a push but before the hook runs that command - however, it's relatively rare to use the dumb HTTP transport nowadays, I think.)


问:
Recyclerview not call onCreateViewHolder
My RecyclerView does not call onCreateViewHolder, onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView.
I put logs for debugging, and no log is shown.
What might be the problem?

My adapter:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}
```

<p>My custom row XML:</p>

<pre class="lang-xml prettyprint-override"><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>
</code>```

and my Fragment:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}
```

答:
Make sure your XML and Koltin/Java code match. In my case, I had a problem with the ViewHolder since I had written:

```<code>var txt: AppCompatTextView = itemView.findViewById(R.id.txt)
</code>```

But since my XML code is:

```<code><TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        .../>
</code>```

I had to change the privious row into:

```<code>var txt: TextView = itemView.findViewById(R.id.txt)
</code>```

In addition, I also had to remove:

```<code>recyclerView.setHasFixedSize(true);
</code>```

I hope this can help you :)

Body:
My RecyclerView does not call onCreateViewHolder, onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView.
I put logs for debugging, and no log is shown.
What might be the problem?

My adapter:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}

My custom row XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>

and my Fragment:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}

Body:
Make sure your XML and Koltin/Java code match. In my case, I had a problem with the ViewHolder since I had written:

var txt: AppCompatTextView = itemView.findViewById(R.id.txt)

But since my XML code is:

<TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        .../>

I had to change the privious row into:

var txt: TextView = itemView.findViewById(R.id.txt)

In addition, I also had to remove:

recyclerView.setHasFixedSize(true);

I hope this can help you :)


问:
Using CMake to create an executable that can run independently on other machines
I’m using LibTorch and OpenCV for a program in Cpp. The compilation and building is done on Linux using CMake. The program builds and runs as expected.

I want to use the executable that CMake created on another Linux machine.
The problem is that I don’t want to install either LibTorch nor OpenCV on the other machine. I’d rather supply the user with a single executable if possible.

How can CMake create a single independent executable?
If making just a single file is irrelevant, how can CMake copy all needed libraries to a single directory?

The current CMake file:

```<code>    cmake_minimum_required(VERSION 2.8)
    project(prediction)
    list(APPEND CMAKE_PREFIX_PATH “libtorch”) # the folder where libtorch in found
    set(CMAKE_BUILD_TYPE Release)

    find_package( OpenCV REQUIRED )
    find_package( Torch REQUIRED )

    if(NOT Torch_FOUND)
    message(FATAL_ERROR “Pytorch Not Found!”)
    endif(NOT Torch_FOUND)

    message(STATUS “Pytorch status:”)
    message(STATUS " libraries: ${TORCH_LIBRARIES}")

    message(STATUS “OpenCV library status:”)
    message(STATUS " version: ${OpenCV_VERSION}")
    message(STATUS " libraries: ${OpenCV_LIBS}")
    message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")

    file(GLOB SOURCES ".h" ".cpp") # Link all headers and sources in root dir

    include_directories( ${OpenCV_INCLUDE_DIRS} )
    add_executable(entrypoint ${SOURCES})
    target_link_libraries(entrypoint ${TORCH_LIBRARIES} ${OpenCV_LIBS})
    set_property(TARGET entrypoint PROPERTY CXX_STANDARD 14)
</code>```

####### EDIT

Thanks for the answers.
Following Phesho_T answer bellow, I got the static compilation of LibTorch, but it won't compile with the set() instruction. It throws C10_LIBRARY NOTFOUND.

I think I'll try to use the shared libraries. How can CMake be instructed to copy the releveant shared libraries to the "build" folder, so I can pack everything in a .zip file and send it to the user.

答:
Like another answer said, you need to link the static libs of Torch and OpenCV in your executable.

There are a few pre-requisites for this:

The two libraries need to have static (.a) libraries installed on your system. If they don't, you may have to manually build them. Steps for this differ between different packages.

You need to tell CMake to search for the static libraries ONLY. This is done via the CMAKE_FIND_LIBRARY_SUFFIXES variable. The chances are the default for this is .so;.a, meaning it will find the shared library first.

```<code>set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
</code>```

The fact that you're using variables in your target_link_libraries command, instead of imported libraries (the modern CMake way) makes me think that this should be enough - these variables should expand to full paths to the static libraries, which should then be added to your linker command.

Things are a bit more complicated to explain if imported targets were used, but this might be out-of-scope for this question.

Try it out and let us know how you get on.

Body:
I’m using LibTorch and OpenCV for a program in Cpp. The compilation and building is done on Linux using CMake. The program builds and runs as expected.

I want to use the executable that CMake created on another Linux machine.
The problem is that I don’t want to install either LibTorch nor OpenCV on the other machine. I’d rather supply the user with a single executable if possible.

How can CMake create a single independent executable?
If making just a single file is irrelevant, how can CMake copy all needed libraries to a single directory?

The current CMake file:

    cmake_minimum_required(VERSION 2.8)
    project(prediction)
    list(APPEND CMAKE_PREFIX_PATH “libtorch”) # the folder where libtorch in found
    set(CMAKE_BUILD_TYPE Release)

    find_package( OpenCV REQUIRED )
    find_package( Torch REQUIRED )

    if(NOT Torch_FOUND)
    message(FATAL_ERROR “Pytorch Not Found!”)
    endif(NOT Torch_FOUND)

    message(STATUS “Pytorch status:”)
    message(STATUS " libraries: ${TORCH_LIBRARIES}")

    message(STATUS “OpenCV library status:”)
    message(STATUS " version: ${OpenCV_VERSION}")
    message(STATUS " libraries: ${OpenCV_LIBS}")
    message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")

    file(GLOB SOURCES ".h" ".cpp") # Link all headers and sources in root dir

    include_directories( ${OpenCV_INCLUDE_DIRS} )
    add_executable(entrypoint ${SOURCES})
    target_link_libraries(entrypoint ${TORCH_LIBRARIES} ${OpenCV_LIBS})
    set_property(TARGET entrypoint PROPERTY CXX_STANDARD 14)

####### EDIT

Thanks for the answers.
Following Phesho_T answer bellow, I got the static compilation of LibTorch, but it won't compile with the set() instruction. It throws C10_LIBRARY NOTFOUND.

I think I'll try to use the shared libraries. How can CMake be instructed to copy the releveant shared libraries to the "build" folder, so I can pack everything in a .zip file and send it to the user.

Body:
Like another answer said, you need to link the static libs of Torch and OpenCV in your executable.

There are a few pre-requisites for this:

The two libraries need to have static (.a) libraries installed on your system. If they don't, you may have to manually build them. Steps for this differ between different packages.

You need to tell CMake to search for the static libraries ONLY. This is done via the CMAKE_FIND_LIBRARY_SUFFIXES variable. The chances are the default for this is .so;.a, meaning it will find the shared library first.

set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")

The fact that you're using variables in your target_link_libraries command, instead of imported libraries (the modern CMake way) makes me think that this should be enough - these variables should expand to full paths to the static libraries, which should then be added to your linker command.

Things are a bit more complicated to explain if imported targets were used, but this might be out-of-scope for this question.

Try it out and let us know how you get on.


问:
Convert dictionary's array to array of dictionary
Is there any possible ways to convert the following structure into a given structure

Input:-

```<code>var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]
</code>```

Expected output:-

```<code>var result = [
    [
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ]
]
</code>```

答:
A single liner:

```<code>var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

let result = dic.values.first!.indices.map {index in dic.mapValues {$0[index]} }
print(result)
//->[["array3": 3, "array2": 2, "array1": 1], ["array3": 3, "array2": 2, "array1": 1], ["array3": 3, "array2": 2, "array1": 1]]
</code>```

Assuming:

all values in dic has the same size

dic has at least one entry

Body:
Is there any possible ways to convert the following structure into a given structure

Input:-

var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

Expected output:-

var result = [
    [
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ]
]

Body:
A single liner:

var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

let result = dic.values.first!.indices.map {index in dic.mapValues {$0[index]} }
print(result)
//->[["array3": 3, "array2": 2, "array1": 1], ["array3": 3, "array2": 2, "array1": 1], ["array3": 3, "array2": 2, "array1": 1]]

Assuming:

all values in dic has the same size

dic has at least one entry


问:
Anaconda Navigator Install Issues for RStudio
I recommended to my class (2 sections) that they use Anaconda Navigator for a quick and easy way to install both python and R on their machine.  I have had success with this recommendation in the past but recently this proved to be very problematic.  At least on macOS, installing RStudio via the GUI does not work.  It appears to stall.

In addition, attempting to create a new environment ,with both R and Python (3.7), the environment does not get created.  It appears in the GUI for < second and then goes away without any other warning visible to the student.

Is there a bug in the recent version or perhaps version collisions across the environments?

答:
I believe there is a bug. I installed Anaconda navigator, then RStudio in navigator. RStudio installed, but when I relaunch navigator I don't get the 'launch' tile, only the 'install' tile for RStudio. When I click the install tile (just to humor myself I suppose) it appears that it is reinstalling RStudio, but really it's just a hung process.

My environment is Windows 10 1909


问:
Zend Expresive - EmitterException: Output has been emitted previously
I was trying to configure my website on VPS. On my local machine everything works fine, but on VPS I got 500 error. This is log:

```<code>PHP message: PHP Fatal error:  Uncaught Zend\HttpHandlerRunner\Exception\EmitterException: Output has been emitted previously; cannot emit response in /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Exception/EmitterException.php:23
Stack trace:
#0 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Emitter/SapiEmitterTrait.php(33): Zend\HttpHandlerRunner\Exception\EmitterException::forOutputSent()
#1 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Emitter/SapiEmitter.php(26): Zend\HttpHandlerRunner\Emitter\SapiEmitter->assertNoPreviousOutput()
#2 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Emitter/EmitterStack.php(40): Zend\HttpHandlerRunner\Emitter\SapiEmitter->emit(Object(Zend\Diactoros\Response\HtmlResponse))
#3 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/RequestHandlerRunner.php(97): Zend\HttpHandlerRunner\Emitter\EmitterStack->emit(Object(Zend\Diactoros\Response\HtmlResponse))
#4 /var/www/project/vendor/zendfram" while reading response header from upstream, client: ***.***.***.***, server: , request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.2-fpm.sock:", host: "***.***.***.***:***"
</code>```

I'm using:

Zend Expresive 3

Nginx 1.14.0

PHP 7.2 FPM

I have not idea what cause the problem and it is hard for me to debug it on this server.

答: This can happen when you have an error in the view that you're attempting to render.</p>

Body:
I was trying to configure my website on VPS. On my local machine everything works fine, but on VPS I got 500 error. This is log:

PHP message: PHP Fatal error:  Uncaught Zend\HttpHandlerRunner\Exception\EmitterException: Output has been emitted previously; cannot emit response in /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Exception/EmitterException.php:23
Stack trace:
#0 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Emitter/SapiEmitterTrait.php(33): Zend\HttpHandlerRunner\Exception\EmitterException::forOutputSent()
#1 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Emitter/SapiEmitter.php(26): Zend\HttpHandlerRunner\Emitter\SapiEmitter->assertNoPreviousOutput()
#2 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/Emitter/EmitterStack.php(40): Zend\HttpHandlerRunner\Emitter\SapiEmitter->emit(Object(Zend\Diactoros\Response\HtmlResponse))
#3 /var/www/project/vendor/zendframework/zend-httphandlerrunner/src/RequestHandlerRunner.php(97): Zend\HttpHandlerRunner\Emitter\EmitterStack->emit(Object(Zend\Diactoros\Response\HtmlResponse))
#4 /var/www/project/vendor/zendfram" while reading response header from upstream, client: ***.***.***.***, server: , request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.2-fpm.sock:", host: "***.***.***.***:***"

I'm using:

Zend Expresive 3

Nginx 1.14.0

PHP 7.2 FPM

I have not idea what cause the problem and it is hard for me to debug it on this server.


问:
Jpql and hibernate age difference
I want to write a method that searches for people at a given age with an interval of 5 years. That is, if the age is set to 30 years, then the method should bring all people from 25 to 35 years old.

```<code>  @Entity
@NamedQueries({
        @NamedQuery(name = "Person.findByNameUndSurname", query = "SELECT c FROM Person c WHERE c.name = ?1 and c.surname = ?1"),
        @NamedQuery(name = "Person.findByAge", query = "SELECT c FROM Person c WHERE c.age = ?1")
})
    Person{
    name,age und get,set
    }

public class PersonMenager extends AbstractRepository {

---
    public List findPersonByAge(int age){
            return entityManager.createQuery("SELECT c from Person c WHERE c.age = ?1 and c.age between age-5 and  age+5").getResultList();
        }
}
</code>```

I don’t understand how I can use the age input

答:
Pass 2 parameters - lower and upper - otherwise you are limited to only ever being able to query for +/- 5 years. What if you wanted +/- 3?

```<code>public class PersonMenager extends AbstractRepository {

    public List findPersonByAge(int lowerBound, int upperBound){
            return entityManager.createQuery("SELECT c from Person c
                WHERE c.age between ?1 and ?2).getResultList();
        }
}
</code>```

Storing age is probably also not a very good idea as it is not a fixed value (unlike say date of birth).

Title: Jpql and hibernate age difference

Body:
I want to write a method that searches for people at a given age with an interval of 5 years. That is, if the age is set to 30 years, then the method should bring all people from 25 to 35 years old.

  @Entity
@NamedQueries({
        @NamedQuery(name = "Person.findByNameUndSurname", query = "SELECT c FROM Person c WHERE c.name = ?1 and c.surname = ?1"),
        @NamedQuery(name = "Person.findByAge", query = "SELECT c FROM Person c WHERE c.age = ?1")
})
    Person{
    name,age und get,set
    }

public class PersonMenager extends AbstractRepository {

---
    public List findPersonByAge(int age){
            return entityManager.createQuery("SELECT c from Person c WHERE c.age = ?1 and c.age between age-5 and  age+5").getResultList();
        }
}

I don’t understand how I can use the age input

Body:
Pass 2 parameters - lower and upper - otherwise you are limited to only ever being able to query for +/- 5 years. What if you wanted +/- 3?

public class PersonMenager extends AbstractRepository {

    public List findPersonByAge(int lowerBound, int upperBound){
            return entityManager.createQuery("SELECT c from Person c
                WHERE c.age between ?1 and ?2).getResultList();
        }
}

Storing age is probably also not a very good idea as it is not a fixed value (unlike say date of birth).


问:
Mahout runs out of heap space
I am running NaiveBayes on a set of tweets using Mahout. Two files, one 100 MB and one 300 MB. I changed JAVA_HEAP_MAX to JAVA_HEAP_MAX=-Xmx2000m ( earlier it was 1000). But even then,  mahout ran for a few hours ( 2 to be precise) before it complained of heap space error.   What should i do to  resolve ?

Some more info if it helps : I am running on a single node, my laptop infact and it has 3GB of RAM (only) .

Thanks.

EDIT: I ran it the third time with <1/2 of the data that i used the first time ( first time i used 5.5 million tweets, second i used 2million ) and i still got a heap space problem. I am posting the complete error for completion purposes :

```<code>17 May, 2011 2:16:22 PM
 org.apache.hadoop.mapred.JobClient monitorAndPrintJob
INFO:  map 50% reduce 0%

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:62)
    at java.lang.StringBuilder.<init>(StringBuilder.java:85)
    at org.apache.hadoop.mapred.JobClient.monitorAndPrintJob(JobClient.java:1283)
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1251)
    at org.apache.mahout.classifier.bayes.mapreduce.common.BayesFeatureDriver.runJob(BayesFeatureDriver.java:63)
    at org.apache.mahout.classifier.bayes.mapreduce.bayes.BayesDriver.runJob(BayesDriver.java:44)
    at org.apache.mahout.classifier.bayes.TrainClassifier.trainNaiveBayes(TrainClassifier.java:54)
    at org.apache.mahout.classifier.bayes.TrainClassifier.main(TrainClassifier.java:162)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:68)
    at org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:139)
    at org.apache.mahout.driver.MahoutDriver.main(MahoutDriver.java:184)
17 May, 2011 7:14:53 PM org.apache.hadoop.mapred.LocalJobRunner$Job run
WARNING: job_local_0001
java.lang.OutOfMemoryError: Java heap space
    at java.lang.String.substring(String.java:1951)
    at java.lang.String.subSequence(String.java:1984)
    at java.util.regex.Pattern.split(Pattern.java:1019)
    at java.util.regex.Pattern.split(Pattern.java:1076)
    at org.apache.mahout.classifier.bayes.mapreduce.common.BayesFeatureMapper.map(BayesFeatureMapper.java:78)
    at org.apache.mahout.classifier.bayes.mapreduce.common.BayesFeatureMapper.map(BayesFeatureMapper.java:46)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:50)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:358)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:307)
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:177)
</code>```

And i am posting the part of the bin/mahout script that i changed :
 Original :

```<code>JAVA=$JAVA_HOME/bin/java
            JAVA_HEAP_MAX=-Xmx1000m

if [ "$MAHOUT_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $MAHOUT_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$MAHOUT_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi
</code>```

Modified :

```<code>JAVA=$JAVA_HOME/bin/java
 JAVA_HEAP_MAX=-Xmx2000m

if [ "$MAHOUT_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $MAHOUT_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$MAHOUT_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi
</code>```

答: You're not specifying what process ran out of memory, which is important. You need to set MAHOUT_HEAPSIZE, not whatever JAVA_HEAP_MAX is.

Title: Mahout runs out of heap space

Body:
I am running NaiveBayes on a set of tweets using Mahout. Two files, one 100 MB and one 300 MB. I changed JAVA_HEAP_MAX to JAVA_HEAP_MAX=-Xmx2000m ( earlier it was 1000). But even then,  mahout ran for a few hours ( 2 to be precise) before it complained of heap space error.   What should i do to  resolve ?

Some more info if it helps : I am running on a single node, my laptop infact and it has 3GB of RAM (only) .

Thanks.

EDIT: I ran it the third time with <1/2 of the data that i used the first time ( first time i used 5.5 million tweets, second i used 2million ) and i still got a heap space problem. I am posting the complete error for completion purposes :

17 May, 2011 2:16:22 PM
 org.apache.hadoop.mapred.JobClient monitorAndPrintJob
INFO:  map 50% reduce 0%

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:62)
    at java.lang.StringBuilder.<init>(StringBuilder.java:85)
    at org.apache.hadoop.mapred.JobClient.monitorAndPrintJob(JobClient.java:1283)
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1251)
    at org.apache.mahout.classifier.bayes.mapreduce.common.BayesFeatureDriver.runJob(BayesFeatureDriver.java:63)
    at org.apache.mahout.classifier.bayes.mapreduce.bayes.BayesDriver.runJob(BayesDriver.java:44)
    at org.apache.mahout.classifier.bayes.TrainClassifier.trainNaiveBayes(TrainClassifier.java:54)
    at org.apache.mahout.classifier.bayes.TrainClassifier.main(TrainClassifier.java:162)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:68)
    at org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:139)
    at org.apache.mahout.driver.MahoutDriver.main(MahoutDriver.java:184)
17 May, 2011 7:14:53 PM org.apache.hadoop.mapred.LocalJobRunner$Job run
WARNING: job_local_0001
java.lang.OutOfMemoryError: Java heap space
    at java.lang.String.substring(String.java:1951)
    at java.lang.String.subSequence(String.java:1984)
    at java.util.regex.Pattern.split(Pattern.java:1019)
    at java.util.regex.Pattern.split(Pattern.java:1076)
    at org.apache.mahout.classifier.bayes.mapreduce.common.BayesFeatureMapper.map(BayesFeatureMapper.java:78)
    at org.apache.mahout.classifier.bayes.mapreduce.common.BayesFeatureMapper.map(BayesFeatureMapper.java:46)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:50)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:358)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:307)
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:177)

And i am posting the part of the bin/mahout script that i changed :
 Original :

JAVA=$JAVA_HOME/bin/java
            JAVA_HEAP_MAX=-Xmx1000m

if [ "$MAHOUT_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $MAHOUT_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$MAHOUT_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi

Modified :

JAVA=$JAVA_HOME/bin/java
 JAVA_HEAP_MAX=-Xmx2000m

if [ "$MAHOUT_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $MAHOUT_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$MAHOUT_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi


问:
Nodejs assync function return
I'm trying to get the result of an assync function I saw that I need to put the ".then", I see that I have the results, but I can't show it in the function's return when I access the path. however in console.log I have the results. JSON with the result loads before the promise to bring the answers.

console.log

```<code>"Cartuchos e Toner > Cartucho Original > LexMark"
"Cartuchos e Toner > Cartucho Original > Epson"
"Games > Acessór. Playstation | PC"
</code>```

example of the return I have:

```<code>    "catName": "79",
    "catNamePai": "76",
    "nome": "LexMark",
    "caminho": {

    }
  },
  {
    "catName": "80",
    "catNamePai": "76",
    "nome": "Epson",
    "caminho": {

    }
  },
  {
    "catName": "81",
    "catNamePai": "73",
    "nome": "Acessór. Playstation | PC",
    "caminho": {

    }
</code>```

example of the return I expected:

```<code>    "catName": "79",
    "catNamePai": "76",
    "nome": "LexMark",
    "caminho": "Cartuchos e Toner > Cartucho Original > LexMark"
  },
  {
    "catName": "80",
    "catNamePai": "76",
    "nome": "Epson",
    "caminho": "Cartuchos e Toner > Cartucho Original > Epson"
  },
  {
    "catName": "81",
    "catNamePai": "73",
    "nome": "Acessór. Playstation | PC",
    "caminho": Games > Acessór. Playstation | PC"
</code>```

My code

```<code>const trataDadosCatDigitoComCaminho = async (req, res) => {
const string = dados;

const separaLinha = string.split(/\n/)

const item = separaLinha.map(item => {

    async function pegaCaminho(id){

    const response = await  api.get(`/tratadadoscatdigito/caminho/${id}`)
       .then(function (response) {
           // handle success
           //console.log(response.data);
          return  response.data
       })
       .catch(function (error) {
           // handle error
           console.log(error);
       });

       return await response;
   }

    const catName =  item.match(/^\d+/)[0].trim()
    const catNamePai =  item.match(/\t\d+/)[0].trim()
    const nome =  item.match(/\t[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ].+/)[0].trim()

    var caminho = pegaCaminho(catName).then(async res => {
    console.log(res)
    return await res;
   })

    const produto = { catName, catNamePai, nome, caminho}

    return produto
});

return await res.json( item )
</code>```

};

答:
I think this code solve your issue , you have to wait until each request is completed </p>

```<code>
function pegaCaminho(id) {
    return new Promise((resolve,reject)=>{
        api.get(`/tratadadoscatdigito/caminho/${id}`)
        .then(function (response) {
            // handle success
            //console.log(response.data);
            resolve(response.data)
        })
        .catch(function (error) {
            console.log(error);
            reject(error)
        });
    })
}

const trataDadosCatDigitoComCaminho = async (req, res) => {
    const string = dados;
    const separaLinha = string.split(/\n/)

    // you have to add async to each item
    const item = await separaLinha.map(async (item) => {
        const catName = item.match(/^\d+/)[0].trim()
        const catNamePai = item.match(/\t\d+/)[0].trim()
        const nome = item.match(/\t[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ].+/)[0].trim()

        try{
            var caminho = await pegaCaminho(catName);
        }catch(error){
            var caminho = null;
        }
        return { catName, catNamePai, nome, caminho }
    });

    return res.json(item)
};
</code>```

Title: Nodejs assync function return

Body:
I'm trying to get the result of an assync function I saw that I need to put the ".then", I see that I have the results, but I can't show it in the function's return when I access the path. however in console.log I have the results. JSON with the result loads before the promise to bring the answers.

console.log

"Cartuchos e Toner > Cartucho Original > LexMark"
"Cartuchos e Toner > Cartucho Original > Epson"
"Games > Acessór. Playstation | PC"

example of the return I have:

    "catName": "79",
    "catNamePai": "76",
    "nome": "LexMark",
    "caminho": {

    }
  },
  {
    "catName": "80",
    "catNamePai": "76",
    "nome": "Epson",
    "caminho": {

    }
  },
  {
    "catName": "81",
    "catNamePai": "73",
    "nome": "Acessór. Playstation | PC",
    "caminho": {

    }

example of the return I expected:

    "catName": "79",
    "catNamePai": "76",
    "nome": "LexMark",
    "caminho": "Cartuchos e Toner > Cartucho Original > LexMark"
  },
  {
    "catName": "80",
    "catNamePai": "76",
    "nome": "Epson",
    "caminho": "Cartuchos e Toner > Cartucho Original > Epson"
  },
  {
    "catName": "81",
    "catNamePai": "73",
    "nome": "Acessór. Playstation | PC",
    "caminho": Games > Acessór. Playstation | PC"

My code

const trataDadosCatDigitoComCaminho = async (req, res) => {
const string = dados;

const separaLinha = string.split(/\n/)

const item = separaLinha.map(item => {

    async function pegaCaminho(id){

    const response = await  api.get(`/tratadadoscatdigito/caminho/${id}`)
       .then(function (response) {
           // handle success
           //console.log(response.data);
          return  response.data
       })
       .catch(function (error) {
           // handle error
           console.log(error);
       });

       return await response;
   }

    const catName =  item.match(/^\d+/)[0].trim()
    const catNamePai =  item.match(/\t\d+/)[0].trim()
    const nome =  item.match(/\t[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ].+/)[0].trim()

    var caminho = pegaCaminho(catName).then(async res => {
    console.log(res)
    return await res;
   })

    const produto = { catName, catNamePai, nome, caminho}

    return produto
});

return await res.json( item )

};

Body:
I think this code solve your issue , you have to wait until each request is completed

function pegaCaminho(id) {
    return new Promise((resolve,reject)=>{
        api.get(`/tratadadoscatdigito/caminho/${id}`)
        .then(function (response) {
            // handle success
            //console.log(response.data);
            resolve(response.data)
        })
        .catch(function (error) {
            console.log(error);
            reject(error)
        });
    })
}

const trataDadosCatDigitoComCaminho = async (req, res) => {
    const string = dados;
    const separaLinha = string.split(/\n/)

    // you have to add async to each item
    const item = await separaLinha.map(async (item) => {
        const catName = item.match(/^\d+/)[0].trim()
        const catNamePai = item.match(/\t\d+/)[0].trim()
        const nome = item.match(/\t[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ].+/)[0].trim()

        try{
            var caminho = await pegaCaminho(catName);
        }catch(error){
            var caminho = null;
        }
        return { catName, catNamePai, nome, caminho }
    });

    return res.json(item)
};


问:
Can the Twisted logger log in UTC?
If I log with logging, I can force the timestamp to be in UTC time by setting

```<code>logging.Formatter.converter = time.gmtime
</code>```

like this:

```<code>import sys
import time
import logging

handler = logging.StreamHandler(sys.stdout)
out_fmt = '[%(asctime)s.%(msecs)03dZ] [%(levelname)s] %(message)s'
dt_fmt = '%Y-%m-%d %H:%M:%S'
logging.Formatter.converter = time.gmtime
formatter = logging.Formatter(out_fmt, dt_fmt)
handler.setFormatter(formatter)
root = logging.getLogger()
root.setLevel(10)
root.addHandler(handler)
logging.log(logging.INFO, 'Start logging')
</code>```

Since my application will be using Twisted, I want to use twisted.logger instead for logging. And, indeed, it is much simpler:

```<code>import sys

from twisted.logger import Logger, textFileLogObserver

log = Logger(observer=textFileLogObserver(sys.stdout, '%Y-%m-%d %H:%M:%S.%fZ'))
log.info('Start logging')
</code>```

Problem is, the timestamp is in local time - not in UTC time. Is there a way to make the Twisted logger use UTC time?

答:
I ended up overriding formatTime in FileLogObserver:

import sys
from datetime import datetime
from twisted.python import log

def myFLOformatTime(self, when):
    timeFormatString = self.timeFormat
    if timeFormatString is None:
        timeFormatString = '[%Y-%m-%d %H:%M:%S.%fZ]'
    return datetime.utcfromtimestamp(when).strftime(timeFormatString)

if __name__ == '__main__':
    log.FileLogObserver.formatTime = myFLOformatTime
    log.startLogging(sys.stdout)
```

Title: Can the Twisted logger log in UTC?

Body:
If I log with logging, I can force the timestamp to be in UTC time by setting

logging.Formatter.converter = time.gmtime

like this:

import sys
import time
import logging

handler = logging.StreamHandler(sys.stdout)
out_fmt = '[%(asctime)s.%(msecs)03dZ] [%(levelname)s] %(message)s'
dt_fmt = '%Y-%m-%d %H:%M:%S'
logging.Formatter.converter = time.gmtime
formatter = logging.Formatter(out_fmt, dt_fmt)
handler.setFormatter(formatter)
root = logging.getLogger()
root.setLevel(10)
root.addHandler(handler)
logging.log(logging.INFO, 'Start logging')

Since my application will be using Twisted, I want to use twisted.logger instead for logging. And, indeed, it is much simpler:

import sys

from twisted.logger import Logger, textFileLogObserver

log = Logger(observer=textFileLogObserver(sys.stdout, '%Y-%m-%d %H:%M:%S.%fZ'))
log.info('Start logging')

Problem is, the timestamp is in local time - not in UTC time. Is there a way to make the Twisted logger use UTC time?