问:
Postgres SQL to fill in time series gaps for multiple groups
I have a single table like this which spans 2 days of data capture:

```<code>   class   timestamp              count

   2       2020-05-20 03:10:00    4
   1       2020-05-21 07:45:00    2
   6       2020-05-20 09:20:00    1
   2       2020-05-21 11:30:00    1
   5       2020-05-21 21:50:00    3
   1       2020-05-21 07:45:00    5
   5       2020-05-20 14:55:00    2
</code>```

I would like to create output similar to that schema but with every 5 minute interval over the two days represented with count zeroed out if there is no matching timestamp.  All duplicate timestamps for a class need to be totaled for that timestamp entry.  All the unique classes need to be grouped and the order should be timestamp ascending.

Every unique class need to be treated that way - group by class, fill in the missing 5 minute times in order, sum any counts with the exact same timestamp in that group, order by timestamp.  The overall output should be ordered by class ascending.

Thanks for any assistance.

答:
Postgres makes this particularly easy using a left join.  The following has one row per timestamp:

```<code>select gs.ts, coalesce(sum(t.count), 0)
from generate_series('2020-05-20 00:00:00'::timestamp, '2020-05-21 23:55:00'::timestamp, interval '5 minute') gs(ts) left join
     t
     on t.timestamp = gs.ts
group by gs.ts;
</code>```

If you want this broken out by class (I really cannot tell what you intend based on the phrasing of the question), then use cross join to generate the rows and left join and aggregation:

```<code>select c.class, gs.ts, coalesce(sum(t.count), 0)
from generate_series('2020-05-20 00:00:00'::timestamp, '2020-05-21 23:55:00'::timestamp, interval '5 minute') gs(ts) cross join
     (select distinct class from t) c left join
     t
     on t.timestamp = gs.ts
group by c.class, gs.ts;
</code>```

It occurs to me that the timestamps may not be exact in your data.  If that is the case, use inequalities for the join:

```<code>     on t.timestamp >= gs.ts and
        t.timestamp < gs.ts + interval '5 minute'
</code>```

Body:
I have a single table like this which spans 2 days of data capture:

   class   timestamp              count

   2       2020-05-20 03:10:00    4
   1       2020-05-21 07:45:00    2
   6       2020-05-20 09:20:00    1
   2       2020-05-21 11:30:00    1
   5       2020-05-21 21:50:00    3
   1       2020-05-21 07:45:00    5
   5       2020-05-20 14:55:00    2

I would like to create output similar to that schema but with every 5 minute interval over the two days represented with count zeroed out if there is no matching timestamp.  All duplicate timestamps for a class need to be totaled for that timestamp entry.  All the unique classes need to be grouped and the order should be timestamp ascending.

Every unique class need to be treated that way - group by class, fill in the missing 5 minute times in order, sum any counts with the exact same timestamp in that group, order by timestamp.  The overall output should be ordered by class ascending.

Thanks for any assistance.

Body:
Postgres makes this particularly easy using a left join.  The following has one row per timestamp:

select gs.ts, coalesce(sum(t.count), 0)
from generate_series('2020-05-20 00:00:00'::timestamp, '2020-05-21 23:55:00'::timestamp, interval '5 minute') gs(ts) left join
     t
     on t.timestamp = gs.ts
group by gs.ts;

If you want this broken out by class (I really cannot tell what you intend based on the phrasing of the question), then use cross join to generate the rows and left join and aggregation:

select c.class, gs.ts, coalesce(sum(t.count), 0)
from generate_series('2020-05-20 00:00:00'::timestamp, '2020-05-21 23:55:00'::timestamp, interval '5 minute') gs(ts) cross join
     (select distinct class from t) c left join
     t
     on t.timestamp = gs.ts
group by c.class, gs.ts;

It occurs to me that the timestamps may not be exact in your data.  If that is the case, use inequalities for the join:

     on t.timestamp >= gs.ts and
        t.timestamp < gs.ts + interval '5 minute'


来源: stackexchange

问:
Failed to copy file when trying to publish in Visual Studio (2019)
I am trying to publish a C# project according to Microsoft's own guide, however when I try to do this I am met with the following error (when build output log level is set to diagnostic).

```<code>Error: Failed to copy file '[path that is over 260 characters]' to '[path that is under 260 characters]'.
Unable to add '[path that is under 260 characters]' to the Web site.
Unable to add file '[subset of path that is under 260 characters]'.
The system cannot find the path specified.
</code>```

I have abstracted the literal paths to make the error easier to read.

What is happening here?

答:
Enabling Windows Long Paths (Paths over 260 characters) and rebooting will not save you here.

If you are seeing this issue then one solution is move your project such that the paths it tries to copy are not over 260 characters long. Essentially take your project and move it as close to the root of a drive as you possibly can.

There is possibly a better solution out there however I have been unable to find a way to inform Microsoft's Publishing Tool to correctly interpret paths longer than 260.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to publish a C# project according to Microsoft's own guide, however when I try to do this I am met with the following error (when build output log level is set to diagnostic).

Error: Failed to copy file '[path that is over 260 characters]' to '[path that is under 260 characters]'.
Unable to add '[path that is under 260 characters]' to the Web site.
Unable to add file '[subset of path that is under 260 characters]'.
The system cannot find the path specified.

I have abstracted the literal paths to make the error easier to read.

What is happening here?


问:
How to access 2D vector having map?
```<code>int main()
{
    map<int,string> my_map;
    vector<map<int,string> > v_temp;
    vector< vector<map<int,string> > > vectors;
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
             my_map.insert(make_pair(1,"sea"));
             my_map.insert(make_pair(2,"ocean"));
            v_temp.push_back(my_map);
        }
        vectors.push_back(v_temp);
        v_temp.clear();
    }

    for(size_t i=0;i<vectors.size();i++)
        for(size_t j=0;j<vectors[i].size();j++)
            std::cout << "vectors[" << i << "][" << j << "][" << vectors[i][j].first<< " "<<vectors[i][j].second<<"]"<< std::endl;
    return 0;
}
                                                                                ^
</code>```

I am facing compilation issue stating no member having first and second. How can I access it. Thanks in advance.

答:
vectors[i][j] is a map, which does not have a first or second. You want to loop over each pair of the map, and use first and second on it.

```<code>for ( size_t i = 0; i < vectors.size(); i++ )
    for ( size_t j = 0; j < vectors[i].size(); j++ )
        for ( const auto &pair : vectors[i][j] )
            std::cout << "vectors[" << i << "][" << j << "][" << pair.first << " " << pair.second << "]" << std::endl;
</code>```

PS: highly recommend not doing using namespace std, see here for reasons

Title: How to access 2D vector having map?

Body:
int main()
{
    map<int,string> my_map;
    vector<map<int,string> > v_temp;
    vector< vector<map<int,string> > > vectors;
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
             my_map.insert(make_pair(1,"sea"));
             my_map.insert(make_pair(2,"ocean"));
            v_temp.push_back(my_map);
        }
        vectors.push_back(v_temp);
        v_temp.clear();
    }

    for(size_t i=0;i<vectors.size();i++)
        for(size_t j=0;j<vectors[i].size();j++)
            std::cout << "vectors[" << i << "][" << j << "][" << vectors[i][j].first<< " "<<vectors[i][j].second<<"]"<< std::endl;
    return 0;
}
                                                                                ^

I am facing compilation issue stating no member having first and second. How can I access it. Thanks in advance.

Body:
vectors[i][j] is a map, which does not have a first or second. You want to loop over each pair of the map, and use first and second on it.

for ( size_t i = 0; i < vectors.size(); i++ )
    for ( size_t j = 0; j < vectors[i].size(); j++ )
        for ( const auto &pair : vectors[i][j] )
            std::cout << "vectors[" << i << "][" << j << "][" << pair.first << " " << pair.second << "]" << std::endl;

PS: highly recommend not doing using namespace std, see here for reasons


问:
Can anyone tell me how to make the printed screen blue?
This is the original question:

As shown above, I need to print a blue screen. This is what I did:

import pygame

pygame.init()

blue = (0, 0, 255)

size = (width, height) = (640, 640)

screen = pygame.display.set_mode(size)

""" Game Drawing """
screen.fill(blue)
pyagme.draw.rect(screen, color, [x, y, 50, 50])
pygame.draw.rect(screen, blue, [mouseX, mouseY, 50, 50])
pygame.display.flip()
```

However, only a black screen is produced... Can anyone tell me how to fix it?

答:
Ok, let's fix the errors in your code.

```<code>import pygame

pygame.init()
blue = (0, 0, 255)
red = (255, 0, 0)
size = (640, 640)
screen = pygame.display.set_mode(size)

screen.fill(blue)
pygame.draw.rect(screen, red, [0,590, 50, 640])
pygame.display.update()

crashed = False
while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
            pygame.quit()
</code>```

And now your screen is blue. And you have a red square.

Body:
This is the original question:

As shown above, I need to print a blue screen. This is what I did:

import pygame

pygame.init()

blue = (0, 0, 255)

size = (width, height) = (640, 640)

screen = pygame.display.set_mode(size)

""" Game Drawing """
screen.fill(blue)
pyagme.draw.rect(screen, color, [x, y, 50, 50])
pygame.draw.rect(screen, blue, [mouseX, mouseY, 50, 50])
pygame.display.flip()

However, only a black screen is produced... Can anyone tell me how to fix it?

Body:
Ok, let's fix the errors in your code.

import pygame

pygame.init()
blue = (0, 0, 255)
red = (255, 0, 0)
size = (640, 640)
screen = pygame.display.set_mode(size)

screen.fill(blue)
pygame.draw.rect(screen, red, [0,590, 50, 640])
pygame.display.update()

crashed = False
while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
            pygame.quit()

And now your screen is blue. And you have a red square.


问:
Sum values in a list of lists of dictionaries using common key-value pairs
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

```<code>data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]
</code>```

Expected output:

```<code>op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]
</code>```

答:
op = []
for lst in data:
    rating_of_user = {}
    for e in lst:
        user, rating = e['user'], e['rating']
        rating_of_user[user] = rating_of_user.get(user, 0) + rating
    op.append([{'user': u, 'rating': r} for u, r in rating_of_user.items()])

```

N.B.: since Python 3.7 dictionaries officially preserve the insertion order

Body:
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

Expected output:

op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]

Body:
op = []
for lst in data:
    rating_of_user = {}
    for e in lst:
        user, rating = e['user'], e['rating']
        rating_of_user[user] = rating_of_user.get(user, 0) + rating
    op.append([{'user': u, 'rating': r} for u, r in rating_of_user.items()])

N.B.: since Python 3.7 dictionaries officially preserve the insertion order


问:
GitHub commits aren't recorded in the 'Your Contributions` calendar
I've been making continuous commits to my GitHub repos from my linux shell and they show up nicely on the website just as they should. The only problem is that "Your Contributions" section doesn't show any recent activity. I have one green square from some day in November which I don't know how I got but all the other contributions don't show up in the calendar (but again, they do  show up in their repos.

What am I missing here?

My github site

答:
I had the same problem and the solution was pretty simple. I had the wrong email set for the global email config

```<code>git config --global user.email "email@yourmail.com"
</code>```

Just make sure the above email and your GitHub account email are same

ContentLicense: CC BY-SA 3.0

Body:
I had the same problem and the solution was pretty simple. I had the wrong email set for the global email config

git config --global user.email "email@yourmail.com"

Just make sure the above email and your GitHub account email are same


问:
adding size option to file_field tag in rails
ANSWERED

I actually found the answer while formulating the question but I'm posting it any way since some might find this useful(as said here: https://meta.stackexchange.com/questions/49922/should-i-continue-adding-a-question-if-i-have-found-the-answer-myself)

I'm having trouble adding size to a file field in ROR3. Here was my syntax:

```<code>= f.file_field :file, :size => "11"
</code>```

this doesnt appear but creates an file input field with this:

```<code><input type="file" name="soap_test_zip_file[file]" id="soap_test_zip_file_file">
</code>```

now I KNOW I made it work before so I looked into some old code and found this:

```<code>= file_field_tag :file, :size => 11
</code>```

which outputs this:

```<code><input type="file" size="11" name="file" id="file">
</code>```

which gives me the correct size, but the wrong file id and name. So I tried this:

```<code><input type="file" size="11" name="soap_test_file_file" id="soap_test_file_file">
</code>```

which gives me the RIGHT ID, but the WRONG NAME. Question is how do I reproduce that file_field but with the size?

I looked into this answer by Ryan Bigg btw: Problem showing the 'size' attribute for a 'file_field' using Ruby on Rails 3

and he's saying it's a cross browser thing that they render file fields differently. That is the case, but I would like to render a short file field IF the browser can handle it.

答:
doesn't seem to work for me..

I thought of another alternative :
jquery ..

```<code>$('#user_photo_photo').attr('size', 1);
</code>```

bingo!!

Body:
ANSWERED

I actually found the answer while formulating the question but I'm posting it any way since some might find this useful(as said here: https://meta.stackexchange.com/questions/49922/should-i-continue-adding-a-question-if-i-have-found-the-answer-myself)

I'm having trouble adding size to a file field in ROR3. Here was my syntax:

= f.file_field :file, :size => "11"

this doesnt appear but creates an file input field with this:

<input type="file" name="soap_test_zip_file[file]" id="soap_test_zip_file_file">

now I KNOW I made it work before so I looked into some old code and found this:

= file_field_tag :file, :size => 11

which outputs this:

<input type="file" size="11" name="file" id="file">

which gives me the correct size, but the wrong file id and name. So I tried this:

<input type="file" size="11" name="soap_test_file_file" id="soap_test_file_file">

which gives me the RIGHT ID, but the WRONG NAME. Question is how do I reproduce that file_field but with the size?

I looked into this answer by Ryan Bigg btw: Problem showing the 'size' attribute for a 'file_field' using Ruby on Rails 3

and he's saying it's a cross browser thing that they render file fields differently. That is the case, but I would like to render a short file field IF the browser can handle it.

Body:
doesn't seem to work for me..

I thought of another alternative :
jquery ..

$('#user_photo_photo').attr('size', 1);

bingo!!


问:
Once child thread completes its execution, will it resume executing main thread lines?
I am trying to create a child thread in a main thread as below,

```<code>public class test {
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("In normal child thread " + Thread.currentThread().getName());

            }
        });
        t1.start();
        System.out.println("main thread sleeping for 5 seconds : " + Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println("In main thread : " + Thread.currentThread().getName());
        System.out.println("exiting main thread : " + Thread.currentThread().getName());
    }

}
</code>```

In the above example, i have made main thread sleep for 5 seconds. So once the child thread completes printing its sysout statement, I am expecting below lines to be executed twice,

```<code>System.out.println("In main thread : " + Thread.currentThread().getName());
System.out.println("exiting main thread : " + Thread.currentThread().getName());
</code>```

But when i execute the program, i see only once these lines are executed.

Please update me if my expectation is right? . I am expecting main thread should execute these sysout statements twice.

答:
Here we're running two threads: the MainThread and the Child thread. When we invoke the start() method for the child thread(), the logic in the run() method is executed.
This child thread will die when its run method is executed.
The main thread continues with its execution of the remaining code.</p>

Body:
I am trying to create a child thread in a main thread as below,

public class test {
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("In normal child thread " + Thread.currentThread().getName());

            }
        });
        t1.start();
        System.out.println("main thread sleeping for 5 seconds : " + Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println("In main thread : " + Thread.currentThread().getName());
        System.out.println("exiting main thread : " + Thread.currentThread().getName());
    }

}

In the above example, i have made main thread sleep for 5 seconds. So once the child thread completes printing its sysout statement, I am expecting below lines to be executed twice,

System.out.println("In main thread : " + Thread.currentThread().getName());
System.out.println("exiting main thread : " + Thread.currentThread().getName());

But when i execute the program, i see only once these lines are executed.

Please update me if my expectation is right? . I am expecting main thread should execute these sysout statements twice.


问:
React-table: State doesn't change as expected, and table doesn't update
Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

I am using the react-table package (version 7.1.0).

I have a table which displays some invoices like so:

The user should be able to select some or all of these items using the selected checkbox.

The selected field is not part of the data. However, when the user hits a selected checkbox, the field should toggle and an array storing document numbers should be populated.

To store the document numbers, I have a stateful getter and setter:

```<code>const [selectedInvoiceIds, setSelectedInvoiceIds] = useState([]);
</code>```

To populate the field, I am attempting to simply add the document number to the array immutably, from the onChange of the checkbox:

```<code>      {
        Header: "Selected",
        accessor: "selected",
        Cell: item => {
          const { documentNumber } = item.row.values;
          return (
            <input
              type="checkbox"
              checked={selectedInvoiceIds.includes(documentNumber)}
              onChange={() => {
                setSelectedInvoiceIds([...selectedInvoiceIds, documentNumber]);
              }}
            />
          );
        }
      }
</code>```

When a checkbox is clicked for the first time, the selectedInvoiceIds becomes populated:

```<code>selectedInvoiceIds: ["706942"]
</code>```

The problems are:

The table does not update to reflect the state change, despite this prop on the checkbox:

```<code>checked={selectedInvoiceIds.includes(documentNumber)}
</code>```

The selectedInvoiceIds value gets overwritten when another document number is added, instead of being added to, as if the state is re-initialising to [] somewhere in between.

Can it be explained why these state issues are occurring and how to get around it?

I am aware of the useTableState value exposed by react-table, but I don't know how I can apply it to this use case.

Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

答:
There are multiple issues in this code:

```<code>// 1) updates to state should should use callback function if it uses prv state

 return (
            <input
              type="checkbox"
              checked={selectedInvoiceIds.includes(documentNumber)}
              onChange={() => {
                setSelectedInvoiceIds(prvSelectedInovicesId => [...prvSelectedInovicesId, documentNumber]);
              }}
            />
          );

// 2) also columns is using useMemo, however not providing dependencies, so columns are not being updated when the selectedInvociesIds state gets updated

// 3) you are not yet handling the toggle, this mean you are just always just adding to the array and not removing from it

</code>```

here is a working version code sandbox
https://codesandbox.io/s/react-table-state-not-updating-wkri3?file=/src/App.js

Body:
Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

I am using the react-table package (version 7.1.0).

I have a table which displays some invoices like so:

The user should be able to select some or all of these items using the selected checkbox.

The selected field is not part of the data. However, when the user hits a selected checkbox, the field should toggle and an array storing document numbers should be populated.

To store the document numbers, I have a stateful getter and setter:

const [selectedInvoiceIds, setSelectedInvoiceIds] = useState([]);

To populate the field, I am attempting to simply add the document number to the array immutably, from the onChange of the checkbox:

      {
        Header: "Selected",
        accessor: "selected",
        Cell: item => {
          const { documentNumber } = item.row.values;
          return (
            <input
              type="checkbox"
              checked={selectedInvoiceIds.includes(documentNumber)}
              onChange={() => {
                setSelectedInvoiceIds([...selectedInvoiceIds, documentNumber]);
              }}
            />
          );
        }
      }

When a checkbox is clicked for the first time, the selectedInvoiceIds becomes populated:

selectedInvoiceIds: ["706942"]

The problems are:

The table does not update to reflect the state change, despite this prop on the checkbox:

checked={selectedInvoiceIds.includes(documentNumber)}

The selectedInvoiceIds value gets overwritten when another document number is added, instead of being added to, as if the state is re-initialising to [] somewhere in between.

Can it be explained why these state issues are occurring and how to get around it?

I am aware of the useTableState value exposed by react-table, but I don't know how I can apply it to this use case.

Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

Body:
There are multiple issues in this code:

// 1) updates to state should should use callback function if it uses prv state

 return (
            <input
              type="checkbox"
              checked={selectedInvoiceIds.includes(documentNumber)}
              onChange={() => {
                setSelectedInvoiceIds(prvSelectedInovicesId => [...prvSelectedInovicesId, documentNumber]);
              }}
            />
          );

// 2) also columns is using useMemo, however not providing dependencies, so columns are not being updated when the selectedInvociesIds state gets updated

// 3) you are not yet handling the toggle, this mean you are just always just adding to the array and not removing from it

here is a working version code sandbox
https://codesandbox.io/s/react-table-state-not-updating-wkri3?file=/src/App.js


问:
How can I add each instance of a scriptable object to a collection?
hello :)

I wish to add each and every instante of an scriptable object class to a HashSet (which is in a static class in a separate script).

I did this by creating a method that adds said class to the hashset and I called this method in the constructor of the class I'm instantiating. Here's the thing though... it works, but not always? Here's the code, I'll go further into the problem at the end:

//first script where the hashset is:
public static class Record
{
    private static HashSet<MyClassToInstantiate> MyHashSet = new HashSet<MyClassToInstantiate>();

    public static void AddToMyHashSet(MyClassToInstantiate obj)
    {
        MyHashSet.Add(obj);
    }

}

```

<pre class="lang-cs prettyprint-override"><code>//the other script:
[CreateAssetMenu(menuName = "X")]
public class MyClassToInstantiate : ScriptableObject
{
    [SerializeField] string someRandomData1;
    [SerializeField] int someRandomData2;

    public MyClassToInstantiate()
    {
        Record.AddToMyHashSet(this);
    }
}
</code>```

This works perfectly except the first time I open Unity. The first time I always have to go into any instance of my "MyClassToInstantiate" and change something (anything) and it just starts working (I'm using the [createAssetMenu] attribute btw).

ps. I'm sure I have blatant theoretical problem that I'm not seeing! Thanks in advance to anyone who gives me some idea of what is going on

答:
So here's the main issue. A scriptableObject instance is an asset that lives permanently in your unity project. Your static class with the hashset is data that only exist while unity is running. Once you leave the application its gone so you would need to regenerate the data. Now I"m not 100% sure why unity calls the scriptableObject's constructor it seems on validate (when you select it/make changes) but relying on something like that will surely cause issues ;) .

You could get all instances when you access the data.

```<code> public static class Record
</code>```

{

```<code>private static HashSet<MyClassToInstantiate> MyHashet;

public static HashSet<MyClassToInstantiate> GetHashSet()
{
    RefreshHash();

    return MyHashet;
}

public static void RefreshHash()
{
    MyClassToInstantiate[] allInstances = GetAllInstances<MyClassToInstantiate>();
    MyHashet = new HashSet<MyClassToInstantiate>();
    for (int i = 0; i < allInstances.Length; ++i)
    {
        MyHashet.Add(allInstances[i]);
    }
}

private static T[] GetAllInstances<T>() where T : ScriptableObject
{
    string[] guids = UnityEditor.AssetDatabase.FindAssets("t:" + typeof(T).Name);  //FindAssets uses tags check documentation for more info
    T[] a = new T[guids.Length];
    for (int i = 0; i < guids.Length; i++)         //probably could get optimized
    {
        string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
        a[i] = UnityEditor.AssetDatabase.LoadAssetAtPath<T>(path);
    }

    return a;
}
</code>```

}

The GetHashSet() function will then return all instances of your scriptable object.

But if you want a cleaner solution, having an other scriptableObject with links to all MyClassToIntanctiate instances you want may be better. It would let you edit the list so they aren't all added by default.

Body:
hello :)

I wish to add each and every instante of an scriptable object class to a HashSet (which is in a static class in a separate script).

I did this by creating a method that adds said class to the hashset and I called this method in the constructor of the class I'm instantiating. Here's the thing though... it works, but not always? Here's the code, I'll go further into the problem at the end:

//first script where the hashset is:
public static class Record
{
    private static HashSet<MyClassToInstantiate> MyHashSet = new HashSet<MyClassToInstantiate>();

    public static void AddToMyHashSet(MyClassToInstantiate obj)
    {
        MyHashSet.Add(obj);
    }

}

//the other script:
[CreateAssetMenu(menuName = "X")]
public class MyClassToInstantiate : ScriptableObject
{
    [SerializeField] string someRandomData1;
    [SerializeField] int someRandomData2;

    public MyClassToInstantiate()
    {
        Record.AddToMyHashSet(this);
    }
}

This works perfectly except the first time I open Unity. The first time I always have to go into any instance of my "MyClassToInstantiate" and change something (anything) and it just starts working (I'm using the [createAssetMenu] attribute btw).

ps. I'm sure I have blatant theoretical problem that I'm not seeing! Thanks in advance to anyone who gives me some idea of what is going on

Body:
So here's the main issue. A scriptableObject instance is an asset that lives permanently in your unity project. Your static class with the hashset is data that only exist while unity is running. Once you leave the application its gone so you would need to regenerate the data. Now I"m not 100% sure why unity calls the scriptableObject's constructor it seems on validate (when you select it/make changes) but relying on something like that will surely cause issues ;) .

You could get all instances when you access the data.

 public static class Record

{

private static HashSet<MyClassToInstantiate> MyHashet;

public static HashSet<MyClassToInstantiate> GetHashSet()
{
    RefreshHash();

    return MyHashet;
}

public static void RefreshHash()
{
    MyClassToInstantiate[] allInstances = GetAllInstances<MyClassToInstantiate>();
    MyHashet = new HashSet<MyClassToInstantiate>();
    for (int i = 0; i < allInstances.Length; ++i)
    {
        MyHashet.Add(allInstances[i]);
    }
}

private static T[] GetAllInstances<T>() where T : ScriptableObject
{
    string[] guids = UnityEditor.AssetDatabase.FindAssets("t:" + typeof(T).Name);  //FindAssets uses tags check documentation for more info
    T[] a = new T[guids.Length];
    for (int i = 0; i < guids.Length; i++)         //probably could get optimized
    {
        string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
        a[i] = UnityEditor.AssetDatabase.LoadAssetAtPath<T>(path);
    }

    return a;
}

}

The GetHashSet() function will then return all instances of your scriptable object.

But if you want a cleaner solution, having an other scriptableObject with links to all MyClassToIntanctiate instances you want may be better. It would let you edit the list so they aren't all added by default.


问:
How to solve a non-linear system in Python
I have three different 3D equations and i want to get the intersection between them (the solution of the system). My variables are x,y,z

Equations:

```<code>-0.006683 x**2 - 0.06893 x + 56.73- z = 0
0.002538 y**2 - 1.115 y + 56.73 - z = 0
(x-24.680)**2+(y-238.341)**2+(z+13.971)**2 = 12.580**2
</code>```

How can i solve this nonlinear system in python?

答:
If you re-write the functions:

```<code>-0.006683 x**2 - 0.06893 x + 56.73- z = 0
0.002538 y**2 - 1.115 y + 56.73 - z = 0
(x-24.680)**2+(y-238.341)**2+(z+13.971)**2 - 12.580**2 = 0
</code>```

this helps a bit.

You've got three equations, and three unknowns.

The brute force method is to loop through x, y, and z values (over some domain of x, y, and z), and see how close all equations get to zero.

```<code>fa = -0.006683 x**2 - 0.06893 x + 56.73- z
fb = 0.002538 y**2 - 1.115 y + 56.73 - z
fc = (x-24.680)**2+(y-238.341)**2+(z+13.971)**2 - 12.580**2
</code>```

Use a 'cost function', like cost=fa * fa + fb * fb + fc  * fc , and look for the minimum.

There are other methods, like the Nelder-Mead method, which can be used, and are more efficient.  https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method

Once you find a minimum, you can take your original search range, and make it finer, depending on what sort of accuracy you need.

@warped gives a nicer, more Pythonic solution, however, there is always the possibility there is no solution, or multiple solutions.  BTW, is this a geometry problem?  The last equation looks like the equation of a sphere.

```<code>from scipy.optimize import fsolve
import math

def equations(p):
    x, y, z = p
    return (-0.006683 * x*x - 0.06893 * x + 56.73- z, \
            0.002538 * y*y - 1.115 * y + 56.73 - z, \
          (x-24.680)**2+(y-238.341)**2+(z+13.971)**2-12.580**2)

x, y, z =  fsolve(equations, (1,1,1))

print (equations((x,y,z)))

print(x,y,z)
</code>```

Using the method noted in this question using SymPy (answered in nice detail by @Oscar Benjamin), How to solve a pair of nonlinear equations using Python?

you can find other solutions in another way.  However, this method didn't find any solutions, at least with my first stab at it.

```<code>from sympy import *

x, y, z = symbols('x, y, z')
eq1 = Eq(-0.006683 * x * x - 0.06893 * x + 56.73- z, 0)
eq2 = Eq(0.002538 * y * y - 1.115 * y + 56.73 - z, 0)
eq3 = Eq((x-24.680)**2+(y-238.341)**2+(z+13.971)**2-12.580**2, 0)

sol = solve([eq1, eq2, eq3], [x, y,z])

print(sol)
print("")
if(len(sol)>1):
    soln = [tuple(v.evalf() for v in s) for s in sol]
    for idx, each in enumerate(soln):
        print(idx,each)
</code>```

Body:
I have three different 3D equations and i want to get the intersection between them (the solution of the system). My variables are x,y,z

Equations:

-0.006683 x**2 - 0.06893 x + 56.73- z = 0
0.002538 y**2 - 1.115 y + 56.73 - z = 0
(x-24.680)**2+(y-238.341)**2+(z+13.971)**2 = 12.580**2

How can i solve this nonlinear system in python?

Body:
If you re-write the functions:

-0.006683 x**2 - 0.06893 x + 56.73- z = 0
0.002538 y**2 - 1.115 y + 56.73 - z = 0
(x-24.680)**2+(y-238.341)**2+(z+13.971)**2 - 12.580**2 = 0

this helps a bit.

You've got three equations, and three unknowns.

The brute force method is to loop through x, y, and z values (over some domain of x, y, and z), and see how close all equations get to zero.

fa = -0.006683 x**2 - 0.06893 x + 56.73- z
fb = 0.002538 y**2 - 1.115 y + 56.73 - z
fc = (x-24.680)**2+(y-238.341)**2+(z+13.971)**2 - 12.580**2

Use a 'cost function', like cost=fa * fa + fb * fb + fc  * fc , and look for the minimum.

There are other methods, like the Nelder-Mead method, which can be used, and are more efficient.  https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method

Once you find a minimum, you can take your original search range, and make it finer, depending on what sort of accuracy you need.

@warped gives a nicer, more Pythonic solution, however, there is always the possibility there is no solution, or multiple solutions.  BTW, is this a geometry problem?  The last equation looks like the equation of a sphere.

from scipy.optimize import fsolve
import math

def equations(p):
    x, y, z = p
    return (-0.006683 * x*x - 0.06893 * x + 56.73- z, \
            0.002538 * y*y - 1.115 * y + 56.73 - z, \
          (x-24.680)**2+(y-238.341)**2+(z+13.971)**2-12.580**2)

x, y, z =  fsolve(equations, (1,1,1))

print (equations((x,y,z)))

print(x,y,z)

Using the method noted in this question using SymPy (answered in nice detail by @Oscar Benjamin), How to solve a pair of nonlinear equations using Python?

you can find other solutions in another way.  However, this method didn't find any solutions, at least with my first stab at it.

from sympy import *

x, y, z = symbols('x, y, z')
eq1 = Eq(-0.006683 * x * x - 0.06893 * x + 56.73- z, 0)
eq2 = Eq(0.002538 * y * y - 1.115 * y + 56.73 - z, 0)
eq3 = Eq((x-24.680)**2+(y-238.341)**2+(z+13.971)**2-12.580**2, 0)

sol = solve([eq1, eq2, eq3], [x, y,z])

print(sol)
print("")
if(len(sol)>1):
    soln = [tuple(v.evalf() for v in s) for s in sol]
    for idx, each in enumerate(soln):
        print(idx,each)


问:
Django static files are not loaded when deploying on Heroku using Docker and Whitenoise
I'm trying to deploy a django app on Heroku (using Whitenoise), and all works fine except for the static files. The sample project just shows a header "Home" on the front page. If the css file is loaded correctly then the header will have the red colour, otherwise it will be black.

I got the above project to work in a virtualenv, a Docker container, with DEBUG=False, but I could not make it work on Heroku for some reason (The header would be Red if the CSS loaded correctly).

I tried to use the django-heroku as suggested by the Heroku docs but it starts throwing 500 server error, and when checking the heroku logs it says manifest not found for the css file, which seems to be because it sets STATICFILES_STORAGE to a different value.

Is there something setup incorrectly in the settings or the yml files? Or perhaps because I'm deploying a Docker file (as opposed to a Procfile) I need to use different settings?

Update 1:

As suggested in the comments. I tried to follow what's done in this tutorial, which has two additional things done:

Setting STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Running heroku plugins:install @heroku-cli/plugin-manifest

When doing this, now I get a different HTTP 500 error:

/usr/local/lib/python3.7/site-packages/whitenoise/base.py:115: UserWarning: No directory at: /django-heroku-staticfiles/staticfiles/

Now I think the problem is clear. So I started running some commands on the heroku instance:

```<code>$ heroku run ls -l /django-heroku-staticfiles
Running ls -l /django-heroku-staticfiles on ⬢ evening-lowlands-39080... up, run.5553 (Free)
total 160
-rw------- 1 u35232 dyno    179 May 30 12:21 Dockerfile
-rw------- 1 u35232 dyno 131072 May 30 12:21 db.sqlite3
-rw------- 1 u35232 dyno    235 May 30 12:21 docker-compose.yml
drwx------ 2 u35232 dyno   4096 May 30 12:21 hello_project
-rw------- 1 u35232 dyno    182 May 30 12:21 heroku.yml
-rwx------ 1 u35232 dyno    633 May 30 12:21 manage.py
drwx------ 4 u35232 dyno   4096 May 30 12:21 pages
-rw------- 1 u35232 dyno     93 May 30 12:21 requirements.txt
drwx------ 2 u35232 dyno   4096 May 30 12:21 templates

$ heroku run python manage.py collectstatic --clear --noinput
Running python manage.py collectstatic --clear --noinput on ⬢ evening-lowlands-39080... up, run.9686 (Free)

131 static files copied to '/django-heroku-staticfiles/staticfiles', 413 post-processed.

$ heroku run ls -l /django-heroku-staticfiles
Running ls -l /django-heroku-staticfiles on ⬢ evening-lowlands-39080... up, run.3303 (Free)
total 160
-rw------- 1 u20456 dyno    179 May 30 12:21 Dockerfile
-rw------- 1 u20456 dyno 131072 May 30 12:21 db.sqlite3
-rw------- 1 u20456 dyno    235 May 30 12:21 docker-compose.yml
drwx------ 2 u20456 dyno   4096 May 30 12:21 hello_project
-rw------- 1 u20456 dyno    182 May 30 12:21 heroku.yml
-rwx------ 1 u20456 dyno    633 May 30 12:21 manage.py
drwx------ 4 u20456 dyno   4096 May 30 12:21 pages
-rw------- 1 u20456 dyno     93 May 30 12:21 requirements.txt
drwx------ 2 u20456 dyno   4096 May 30 12:21 templates
</code>```

Why is staticfiles not getting created? Maybe I need to run the command through Docker? Sorry I'm new to Docker, Django, and Heroku, so I might be missing something obvious.

答:
Thanks to @Original BBQ Sauce, this SO question, and this Reddit post the problem is finally solved. It's related to where/when we run collectstatic. Initially I was running it as a release command in the heroku.yml file, which was not creating the staticfiles directory for some reason. I was doing it this way as is done in the Django for Professionals book.

Now, if that command is run in the Dockerfile instead, the staticfiles directory is created and all should work fine. The repo now has the new, working settings.

Body:
I'm trying to deploy a django app on Heroku (using Whitenoise), and all works fine except for the static files. The sample project just shows a header "Home" on the front page. If the css file is loaded correctly then the header will have the red colour, otherwise it will be black.

I got the above project to work in a virtualenv, a Docker container, with DEBUG=False, but I could not make it work on Heroku for some reason (The header would be Red if the CSS loaded correctly).

I tried to use the django-heroku as suggested by the Heroku docs but it starts throwing 500 server error, and when checking the heroku logs it says manifest not found for the css file, which seems to be because it sets STATICFILES_STORAGE to a different value.

Is there something setup incorrectly in the settings or the yml files? Or perhaps because I'm deploying a Docker file (as opposed to a Procfile) I need to use different settings?

Update 1:

As suggested in the comments. I tried to follow what's done in this tutorial, which has two additional things done:

Setting STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Running heroku plugins:install @heroku-cli/plugin-manifest

When doing this, now I get a different HTTP 500 error:

/usr/local/lib/python3.7/site-packages/whitenoise/base.py:115: UserWarning: No directory at: /django-heroku-staticfiles/staticfiles/

Now I think the problem is clear. So I started running some commands on the heroku instance:

$ heroku run ls -l /django-heroku-staticfiles
Running ls -l /django-heroku-staticfiles on ⬢ evening-lowlands-39080... up, run.5553 (Free)
total 160
-rw------- 1 u35232 dyno    179 May 30 12:21 Dockerfile
-rw------- 1 u35232 dyno 131072 May 30 12:21 db.sqlite3
-rw------- 1 u35232 dyno    235 May 30 12:21 docker-compose.yml
drwx------ 2 u35232 dyno   4096 May 30 12:21 hello_project
-rw------- 1 u35232 dyno    182 May 30 12:21 heroku.yml
-rwx------ 1 u35232 dyno    633 May 30 12:21 manage.py
drwx------ 4 u35232 dyno   4096 May 30 12:21 pages
-rw------- 1 u35232 dyno     93 May 30 12:21 requirements.txt
drwx------ 2 u35232 dyno   4096 May 30 12:21 templates

$ heroku run python manage.py collectstatic --clear --noinput
Running python manage.py collectstatic --clear --noinput on ⬢ evening-lowlands-39080... up, run.9686 (Free)

131 static files copied to '/django-heroku-staticfiles/staticfiles', 413 post-processed.

$ heroku run ls -l /django-heroku-staticfiles
Running ls -l /django-heroku-staticfiles on ⬢ evening-lowlands-39080... up, run.3303 (Free)
total 160
-rw------- 1 u20456 dyno    179 May 30 12:21 Dockerfile
-rw------- 1 u20456 dyno 131072 May 30 12:21 db.sqlite3
-rw------- 1 u20456 dyno    235 May 30 12:21 docker-compose.yml
drwx------ 2 u20456 dyno   4096 May 30 12:21 hello_project
-rw------- 1 u20456 dyno    182 May 30 12:21 heroku.yml
-rwx------ 1 u20456 dyno    633 May 30 12:21 manage.py
drwx------ 4 u20456 dyno   4096 May 30 12:21 pages
-rw------- 1 u20456 dyno     93 May 30 12:21 requirements.txt
drwx------ 2 u20456 dyno   4096 May 30 12:21 templates

Why is staticfiles not getting created? Maybe I need to run the command through Docker? Sorry I'm new to Docker, Django, and Heroku, so I might be missing something obvious.


问:
Laravel Spatie Permissions - user and role relation get only id and name
I'm using Laravel Spatie Permissions to manage roles and permissions in my app. I'm traing to retrieve only Role id and name in the relation between users and roles. My UserResource looks like this:

```<code>class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'        => $this->id,
            'name'      => $this->name,
            'surname'   => $this->surname,
            'email'     => $this->email,
            'inactive'  => $this->inactive,
            'roles'     => $this->roles
        ];
    }
}
</code>```

And the json looks like this:

```<code>"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                    "guard_name": "web",
                    "created_at": "2020-05-28 23:18:58",
                    "updated_at": "2020-05-28 23:18:58",
                    "pivot": {
                        "model_id": 1,
                        "role_id": 1,
                        "model_type": "App\\User"
                    }
                }
            ]
        },
]
</code>```

What I really need it's a json like this:

```<code>"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                },
                {
                    "id": 2,
                    "name": "Default",
                },
                {
                    "id": 3,
                    "name": "Guest",
                }
            ]
        },
]
</code>```

I really don't know how to modified my models relations or the parameter $this->roles (in UserResources) to could get this json.

答:
You can create a RoleResource:

```<code>class RoleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}
</code>```

And use it on your UserResource:

```<code>class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'        => $this->id,
            'name'      => $this->name,
            'surname'   => $this->surname,
            'email'     => $this->email,
            'inactive'  => $this->inactive,
            'roles'     => RoleResource::collection($this->roles),
        ];
    }
}
</code>```

Body:
I'm using Laravel Spatie Permissions to manage roles and permissions in my app. I'm traing to retrieve only Role id and name in the relation between users and roles. My UserResource looks like this:

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'        => $this->id,
            'name'      => $this->name,
            'surname'   => $this->surname,
            'email'     => $this->email,
            'inactive'  => $this->inactive,
            'roles'     => $this->roles
        ];
    }
}

And the json looks like this:

"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                    "guard_name": "web",
                    "created_at": "2020-05-28 23:18:58",
                    "updated_at": "2020-05-28 23:18:58",
                    "pivot": {
                        "model_id": 1,
                        "role_id": 1,
                        "model_type": "App\\User"
                    }
                }
            ]
        },
]

What I really need it's a json like this:

"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                },
                {
                    "id": 2,
                    "name": "Default",
                },
                {
                    "id": 3,
                    "name": "Guest",
                }
            ]
        },
]

I really don't know how to modified my models relations or the parameter $this->roles (in UserResources) to could get this json.

Body:
You can create a RoleResource:

class RoleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}

And use it on your UserResource:

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'        => $this->id,
            'name'      => $this->name,
            'surname'   => $this->surname,
            'email'     => $this->email,
            'inactive'  => $this->inactive,
            'roles'     => RoleResource::collection($this->roles),
        ];
    }
}


问:
Import multiple csv files into pandas and concatenate into one DataFrame where 1st column same in all csv and no headers of data just file name
Import multiple CSV files into pandas and concatenate into one DataFrame where 1st column same in all csv and no headers of data just file name.

In all CSV only file name described the meaning of data in it.
No header in all CSV files.
1st column is common in all CSV files.

how to merge all CSV files to one dataset in python.
code:

```<code>import os
import pandas as pd
import glob

path= "....\\data"
os.chdir(path)
results = pd.DataFrame()

for counter, current_file in enumerate(glob.glob("*.csv")):
    namedf = pd.read_csv(current_file, header=None)
    print(namedf)
    results = results.merge(namedf, on='0')

results.to_csv('Combined.csv', index=None, header=None)
</code>```

答:
As you wrote no headers, I assume that reading should be performed rather
with header=None. Using header=filename is a very weird concept.

I assume that you have first 2 input DataFrames something like below:

```<code>   0     1     2
0  A  Bbb1  Ccc1
1  B  Bbb2  Ccc2
2  C  Bbb3  Ccc3
3  D  Bbb4  Ccc4

   0     1     2
0  A  Ddd1  Eee1
1  B  Ddd2  Eee2
2  C  Ddd3  Eee3
3  D  Ddd4  Eee4
</code>```

with the same content in the first column.

As I understand, you want to join (actually merge) them horizontally,
on common values in the first column.

To merge first 2 DataFrames, say df and df2 you can do:

```<code>df = pd.merge(df, df2, on=[0], how='outer')
df.columns = [ n for n in range(len(df.columns)) ]
</code>```

Then the merged content is back in df and columns are renamed to
consecutive integers:

```<code>   0     1     2     3     4
0  A  Bbb1  Ccc1  Ddd1  Eee1
1  B  Bbb2  Ccc2  Ddd2  Eee2
2  C  Bbb3  Ccc3  Ddd3  Eee3
3  D  Bbb4  Ccc4  Ddd4  Eee4
</code>```

This way you don't repeat the first column (the merge key).

So your loop to read and merge source files can be something like:

```<code>for counter, current_file in enumerate(glob.glob("*.csv")):
    print(f'{counter}: {current_file}')
    if counter == 0:
        df = pd.read_csv(current_file, header=None)
    else:
        df2 = pd.read_csv(current_file, header=None)
        df = pd.merge(df, df2, on=[0], how='outer')
        df.columns = [ n for n in range(len(df.columns)) ]
</code>```

Body:
Import multiple CSV files into pandas and concatenate into one DataFrame where 1st column same in all csv and no headers of data just file name.

In all CSV only file name described the meaning of data in it.
No header in all CSV files.
1st column is common in all CSV files.

how to merge all CSV files to one dataset in python.
code:

import os
import pandas as pd
import glob

path= "....\\data"
os.chdir(path)
results = pd.DataFrame()

for counter, current_file in enumerate(glob.glob("*.csv")):
    namedf = pd.read_csv(current_file, header=None)
    print(namedf)
    results = results.merge(namedf, on='0')

results.to_csv('Combined.csv', index=None, header=None)

Body:
As you wrote no headers, I assume that reading should be performed rather
with header=None. Using header=filename is a very weird concept.

I assume that you have first 2 input DataFrames something like below:

   0     1     2
0  A  Bbb1  Ccc1
1  B  Bbb2  Ccc2
2  C  Bbb3  Ccc3
3  D  Bbb4  Ccc4

   0     1     2
0  A  Ddd1  Eee1
1  B  Ddd2  Eee2
2  C  Ddd3  Eee3
3  D  Ddd4  Eee4

with the same content in the first column.

As I understand, you want to join (actually merge) them horizontally,
on common values in the first column.

To merge first 2 DataFrames, say df and df2 you can do:

df = pd.merge(df, df2, on=[0], how='outer')
df.columns = [ n for n in range(len(df.columns)) ]

Then the merged content is back in df and columns are renamed to
consecutive integers:

   0     1     2     3     4
0  A  Bbb1  Ccc1  Ddd1  Eee1
1  B  Bbb2  Ccc2  Ddd2  Eee2
2  C  Bbb3  Ccc3  Ddd3  Eee3
3  D  Bbb4  Ccc4  Ddd4  Eee4

This way you don't repeat the first column (the merge key).

So your loop to read and merge source files can be something like:

for counter, current_file in enumerate(glob.glob("*.csv")):
    print(f'{counter}: {current_file}')
    if counter == 0:
        df = pd.read_csv(current_file, header=None)
    else:
        df2 = pd.read_csv(current_file, header=None)
        df = pd.merge(df, df2, on=[0], how='outer')
        df.columns = [ n for n in range(len(df.columns)) ]


问:
Are there legitimate uses for JavaScript's "with" statement?
Alan Storm's comments in response to my answer regarding the with statement got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of with, while avoiding its pitfalls.

Where have you found the with statement useful?

答:
I think the with-statement can come in handy when converting a template language into JavaScript. For example JST in base2, but I've seen it more often. </p>

<p>I agree one can program this without the with-statement. But because it doesn't give any problems it is a legitimate use. </p>

Body:
I think the with-statement can come in handy when converting a template language into JavaScript. For example JST in base2, but I've seen it more often.

I agree one can program this without the with-statement. But because it doesn't give any problems it is a legitimate use.

OwnerDisplayName: doekman

ContentLicense: CC BY-SA 2.5


问:
How to use AntiXss in my Project?
I want to use AntiXss library function in my web application. I have a web application which contain asp.net pages with Jquery code in code behind. Whole asp.net pages run through Jquery js pages. I want to apply the encoding function to some fields, but the problem is how to apply and where to apply the encoding unction - (In jquery page where to set value to show on output window 0r on the server side code where get data API called in cs files.) And which function to use in this scenarios (HtmlEncode, JavascriptEncode, etc)

Thanks in advance

答:
The basic idea behind preventing XSS attacks is that all input data (from user or say external application) should be treated as untrusted/un-safe and hence must be either validated while accepting and/or encoded while reproducing in output (html, js etc).

AFAIK, AntiXss is an server side library, so you cannot use it to encode values in browser. You have to apply encoding (to html/html attribute/JS etc) at server side before sending those values to client (e.g. in aspx page or in asmx/SCF services that are sending data to client where java-script is going to treat the data as an html or script).

See this article - although its dated, it is still a good resource to start with AntiXss lib and it also lists scenarios for using various encoding methods under "Determining Encoding Method to Use"

Title: How to use AntiXss in my Project?


问:
Should I end an expression with ; inside a loop?
I just started learning Rust and I often have some questions that I can't find any answer. I don't really know how and where to post my question, so I'll try SO.

I started to read the Rust documentation on the website and I did the Guessing game example.

I realized that the match cmp expression inside the loop could be turned into a statement and everything still works. So I wonder why and what version should really be preferred?

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        } // <=== here should it be ended as statement (;) or not?
    }
}
```

答: In Rust, loop blocks expect a "return" type of the empty type (). This is the type that's returned when you end with a statement and don't return anything at all (e.g. {f();}). println! returns the empty type, so the code you posted works either way, however I would say it makes more sense to end it with a semicolon.


问:
UICollectionView Height resizes on first load
I have a UITableViewCell (MyTableViewCell) that contains a stackview. The first item in the stackview is a subview (MyHeaderView) which contains a few labels and a UICollectionView.
I have a problem when the tableview initially loads where the height of the UICollectionView is larger than the content and it then retracts/jumps to the correct size (the initial height is about twice that of the content). It also only happens when the items in the UICollectionView runs over more than 1 row.

```<code>class MyHeaderView: UIView {

    private var identifierLabel = UILabel()
    private var statementLabel = UILabel()
    private var referenceIdLabel = UILabel()

    private var tagsCollectionView: DynamicHeightCollectionView!

    private var tagsArray = [String]()
    private var tags = [String]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        initTagsCollectionViewLayout()

        backgroundColor = .red
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        contentView.addSubview(identifierLabel)
        contentView.addSubview(tagsCollectionView)
        contentView.addSubview(statementLabel)
        contentView.addSubview(referenceIdLabel)

        identifierLabel.layer.borderWidth = 4
        identifierLabel.layer.borderColor = UIColor.white.cgColor
        identifierLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.lessThanOrEqualTo(30)
            make.height.equalTo(30)
        }

        tagsCollectionView.snp.makeConstraints { make in
            make.top.equalTo(identifierLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        referenceIdLabel.numberOfLines = 0
        referenceIdLabel.snp.makeConstraints { make in
            make.top.equalTo(tagsCollectionView.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        statementLabel.numberOfLines = 0
        statementLabel.snp.makeConstraints { make in
            make.top.equalTo(referenceIdLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    lazy var contentView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 400))
        view.layer.borderWidth = 4
        view.layer.borderColor = UIColor.white.cgColor

        view.backgroundColor = UIColor.red
        return view
    }()

    func initTagsCollectionViewLayout() {
        let flowLayout = LeftAlignedCollectionViewFlowLayout()

        tagsCollectionView = DynamicHeightCollectionView(frame: .zero, collectionViewLayout: flowLayout)

        tagsCollectionView.delegate = self
        tagsCollectionView.dataSource = self
        tagsCollectionView.isScrollEnabled = false
        tagsCollectionView.backgroundColor = .white

        flowLayout.estimatedItemSize = CGSize(width: 50, height: 20)
        flowLayout.minimumInteritemSpacing = 4
        flowLayout.minimumLineSpacing = 8
        flowLayout.scrollDirection = .vertical

        self.tagsCollectionView.collectionViewLayout = flowLayout
        self.tagsCollectionView.layoutIfNeeded()
        self.tagsCollectionView.register(UINib.init(nibName: Constants.tagsCollectionCellNibName, bundle: nil), forCellWithReuseIdentifier: Constants.tagsCollectionCellReuseID)
    }

    // MARK: Set up view
    func setUpView(observation: Observation) {
        identifierLabel.text = observation.identifier
        statementLabel.text = observation.statement
        referenceIdLabel.text = observation.referenceID

        tagsArray = [String]()

        if let tags = observation.tags, tags.count > 0 {
            for tag in tags {
                tagsArray.append(tag)
            }
        }

        if tagsArray.count > 0 {
            tagsCollectionView.reloadData()
            //tagsCollectionView.setNeedsLayout()
            tagsCollectionView.layoutIfNeeded()
        }
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        if (self.superview != nil) {
            self.superview?.layoutIfNeeded()
        }

        return tagsCollectionView.contentSize
    }
}

extension MyHeaderView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tagsArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = UICollectionViewCell()

        switch collectionView {
        case tagsCollectionView:
            let tagsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.tagsCollectionCellReuseID, for: indexPath) as! TagsCollectionViewCell

            tagsCollectionViewCell.initRequirementTag(tagText: self.tagsArray[indexPath.item])

            cell = tagsCollectionViewCell

        default:
            break
        }

        return cell
    }
}

// MARK: - Constants
private enum Constants {
    static let tagsCollectionCellReuseID = "TagsCollectionViewCell"
    static let tagsCollectionCellNibName = "TagsCollectionViewCell"
}

class MyTableViewCell: UITableViewCell {

    private var stackView = UIStackView()
    private var myHeaderView = MyHeaderView()
    private var observation: Observation?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        self.addSubview(stackView)

        stackView.axis = .vertical
        stackView.spacing = 4
        stackView.distribution = .fillProportionally
        stackView.alignment = .fill
        stackView.arrangedSubviews.forEach({ $0.removeFromSuperview() }) // clear stack view on each load

        stackView.addArrangedSubview(myHeaderView)

        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            //make.width.equalToSuperview()
        }

        myHeaderView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

    }

    func setupView(observation: Observation) {
        self.observation = observation

        myHeaderView.setUpView(observation: observation)
    }

}

class DynamicHeightCollectionView: UICollectionView {

    override func layoutSubviews() {
        super.layoutSubviews()
        if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        return contentSize
    }
}

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0
        attributes?.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                leftMargin = sectionInset.left
            }

            layoutAttribute.frame.origin.x = leftMargin

            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY , maxY)
        }

        return attributes
    }
}

// in tableview controller
var obs1 = Observation(identifier: "1.1", statement: "custom statement test", referenceID: "reference id test", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8", "tag 9", "tag 10", "tag 11", "tag 12", "tag 13", "tag 14", "tag 15", "tag 16", "tag 17", "tag 18", "tag 19", "tag 20"])

    var obs2 = Observation(identifier: "1.2", statement: "custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines", referenceID: "reference id test that runs onto multiple lines, reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8"])

    var obs3 = Observation(identifier: "1.3", statement: "custom statement test", referenceID: "reference id test", tags: [])

    var obs4 = Observation(identifier: "1.4", statement: "custom statement test", referenceID: "reference id test", tags: [])

var obs: [Observation]
obs.append(obs1)
obs.append(obs2)
obs.append(obs3)
obs.append(obs4)

struct Observation {
    var identifier: String
    var statement: String
    var referenceID: String
    var tags: [String]
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ObservationTableViewCellV2") as! ObservationTableViewCellV2

        let observation = obs[indexPath.row] as! Observation
        cell.setupView(observation: observation)

        return cell
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return obs.count
    }
</code>```

I have tried changing the estimated item size and the UICollectionViewDelegateFlowLayout sizeForItemAt but it makes no difference.

The UICollectionView is highlighted in blue. On first load it appears as:

Then a split second later it resizes to the correct size:

答: In storyboard inside Size Inspector section make Estimate Size on the Collection View from Automatic to None.

Body:
I have a UITableViewCell (MyTableViewCell) that contains a stackview. The first item in the stackview is a subview (MyHeaderView) which contains a few labels and a UICollectionView.
I have a problem when the tableview initially loads where the height of the UICollectionView is larger than the content and it then retracts/jumps to the correct size (the initial height is about twice that of the content). It also only happens when the items in the UICollectionView runs over more than 1 row.

class MyHeaderView: UIView {

    private var identifierLabel = UILabel()
    private var statementLabel = UILabel()
    private var referenceIdLabel = UILabel()

    private var tagsCollectionView: DynamicHeightCollectionView!

    private var tagsArray = [String]()
    private var tags = [String]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        initTagsCollectionViewLayout()

        backgroundColor = .red
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        contentView.addSubview(identifierLabel)
        contentView.addSubview(tagsCollectionView)
        contentView.addSubview(statementLabel)
        contentView.addSubview(referenceIdLabel)

        identifierLabel.layer.borderWidth = 4
        identifierLabel.layer.borderColor = UIColor.white.cgColor
        identifierLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.lessThanOrEqualTo(30)
            make.height.equalTo(30)
        }

        tagsCollectionView.snp.makeConstraints { make in
            make.top.equalTo(identifierLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        referenceIdLabel.numberOfLines = 0
        referenceIdLabel.snp.makeConstraints { make in
            make.top.equalTo(tagsCollectionView.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        statementLabel.numberOfLines = 0
        statementLabel.snp.makeConstraints { make in
            make.top.equalTo(referenceIdLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    lazy var contentView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 400))
        view.layer.borderWidth = 4
        view.layer.borderColor = UIColor.white.cgColor

        view.backgroundColor = UIColor.red
        return view
    }()

    func initTagsCollectionViewLayout() {
        let flowLayout = LeftAlignedCollectionViewFlowLayout()

        tagsCollectionView = DynamicHeightCollectionView(frame: .zero, collectionViewLayout: flowLayout)

        tagsCollectionView.delegate = self
        tagsCollectionView.dataSource = self
        tagsCollectionView.isScrollEnabled = false
        tagsCollectionView.backgroundColor = .white

        flowLayout.estimatedItemSize = CGSize(width: 50, height: 20)
        flowLayout.minimumInteritemSpacing = 4
        flowLayout.minimumLineSpacing = 8
        flowLayout.scrollDirection = .vertical

        self.tagsCollectionView.collectionViewLayout = flowLayout
        self.tagsCollectionView.layoutIfNeeded()
        self.tagsCollectionView.register(UINib.init(nibName: Constants.tagsCollectionCellNibName, bundle: nil), forCellWithReuseIdentifier: Constants.tagsCollectionCellReuseID)
    }

    // MARK: Set up view
    func setUpView(observation: Observation) {
        identifierLabel.text = observation.identifier
        statementLabel.text = observation.statement
        referenceIdLabel.text = observation.referenceID

        tagsArray = [String]()

        if let tags = observation.tags, tags.count > 0 {
            for tag in tags {
                tagsArray.append(tag)
            }
        }

        if tagsArray.count > 0 {
            tagsCollectionView.reloadData()
            //tagsCollectionView.setNeedsLayout()
            tagsCollectionView.layoutIfNeeded()
        }
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        if (self.superview != nil) {
            self.superview?.layoutIfNeeded()
        }

        return tagsCollectionView.contentSize
    }
}

extension MyHeaderView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tagsArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = UICollectionViewCell()

        switch collectionView {
        case tagsCollectionView:
            let tagsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.tagsCollectionCellReuseID, for: indexPath) as! TagsCollectionViewCell

            tagsCollectionViewCell.initRequirementTag(tagText: self.tagsArray[indexPath.item])

            cell = tagsCollectionViewCell

        default:
            break
        }

        return cell
    }
}

// MARK: - Constants
private enum Constants {
    static let tagsCollectionCellReuseID = "TagsCollectionViewCell"
    static let tagsCollectionCellNibName = "TagsCollectionViewCell"
}

class MyTableViewCell: UITableViewCell {

    private var stackView = UIStackView()
    private var myHeaderView = MyHeaderView()
    private var observation: Observation?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        self.addSubview(stackView)

        stackView.axis = .vertical
        stackView.spacing = 4
        stackView.distribution = .fillProportionally
        stackView.alignment = .fill
        stackView.arrangedSubviews.forEach({ $0.removeFromSuperview() }) // clear stack view on each load

        stackView.addArrangedSubview(myHeaderView)

        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            //make.width.equalToSuperview()
        }

        myHeaderView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

    }

    func setupView(observation: Observation) {
        self.observation = observation

        myHeaderView.setUpView(observation: observation)
    }

}

class DynamicHeightCollectionView: UICollectionView {

    override func layoutSubviews() {
        super.layoutSubviews()
        if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        return contentSize
    }
}

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0
        attributes?.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                leftMargin = sectionInset.left
            }

            layoutAttribute.frame.origin.x = leftMargin

            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY , maxY)
        }

        return attributes
    }
}

// in tableview controller
var obs1 = Observation(identifier: "1.1", statement: "custom statement test", referenceID: "reference id test", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8", "tag 9", "tag 10", "tag 11", "tag 12", "tag 13", "tag 14", "tag 15", "tag 16", "tag 17", "tag 18", "tag 19", "tag 20"])

    var obs2 = Observation(identifier: "1.2", statement: "custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines", referenceID: "reference id test that runs onto multiple lines, reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8"])

    var obs3 = Observation(identifier: "1.3", statement: "custom statement test", referenceID: "reference id test", tags: [])

    var obs4 = Observation(identifier: "1.4", statement: "custom statement test", referenceID: "reference id test", tags: [])

var obs: [Observation]
obs.append(obs1)
obs.append(obs2)
obs.append(obs3)
obs.append(obs4)

struct Observation {
    var identifier: String
    var statement: String
    var referenceID: String
    var tags: [String]
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ObservationTableViewCellV2") as! ObservationTableViewCellV2

        let observation = obs[indexPath.row] as! Observation
        cell.setupView(observation: observation)

        return cell
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return obs.count
    }

I have tried changing the estimated item size and the UICollectionViewDelegateFlowLayout sizeForItemAt but it makes no difference.

The UICollectionView is highlighted in blue. On first load it appears as:

Then a split second later it resizes to the correct size:


问:
How to compile an OpenGL project on Ubuntu?
I am new to OpenGL and I am using Visual Studio Code on Ubuntu 18.04.4.

I have a homework and I am provided with a visual studio project. There is a bunch of files that I don't understand. I don't know some of the extensions and how they all work together. How can I compile this project? The files are named like this:

FragmentShader.fs

GeometricDefinitions.h

glad.c

Object3D.cpp

Object3D.h

OpenGLProject.cpp

OpenGLProject.vcxproj

ply.h

plyfile.c

rectangle.ply

Shader.h

VertexShader.sh

I built necessary libraries and ran a sample code to see it works.

答:
The files in your directory can be arranged in a few groups:

C and C++ source files

These files would be compiled by gcc (or another compiler collection).

glad.c

Object3D.cpp

OpenGLProject.cpp

plyfile.c

C and C++ header files

These files can be ignored by you while building. The compiler will pull them in as needed.

GeometricDefinitions.h

Object3D.h

ply.h

Shader.h

OpenGL shaders

These files (probably) contain OpenGL shader data.

FragmentShader.fs

VertexShader.sh

Polygons?

I don't recognize this file type, but my guess is that it contains the definition of the surface to which the shaders should be applied.

rectangle.ply

Visual Studio project

This file would be rather useful if you find an IDE extension that allows you to open Visual Studio projects. Without such an extension, it is just a reference for what Visual Studio would do (it should be XML, so human-readable to some extent).

OpenGLProject.vcxproj

Based on just the file names, I don't know how to make the project work in Visual Studio Code. It would be convenient if there is a Visual Studio Code extension that reads Visual Studio projects (but I don't know of one myself).


问:
How do I run a python script that is located on the AWS EC2 server?
I want to use python code on my computer to run a python script that is located on the server (EC2 ubuntu 18). I understand that you can use boto for this, but I didn't find a full-fledged example where it would be written here is the server, we connect to it like this, we execute the script like this.</p>

答:
Take a look at AWS SSM - Run Command.

From your local Python script you can run the send-command

You can either:

Create your own document

Use the AWS-RunShellScript document.

To execute you this, you will need to ensure that the target instance has SSM Agent is intalled, and that instance has a role with the correct privileges.
Example command

```<code>import boto3
client = boto3.client('ssm')

client.send_command(
    InstanceIds=[
        'i-01234567',
    ],
    DocumentName='AWS-RunShellScript',
    Parameters={
        'commands': [
            'python3 /home/ec2-user/main.py',
        ]
    }
)
</code>```

Body:
Take a look at AWS SSM - Run Command.

From your local Python script you can run the send-command

You can either:

Create your own document

Use the AWS-RunShellScript document.

To execute you this, you will need to ensure that the target instance has SSM Agent is intalled, and that instance has a role with the correct privileges.
Example command

import boto3
client = boto3.client('ssm')

client.send_command(
    InstanceIds=[
        'i-01234567',
    ],
    DocumentName='AWS-RunShellScript',
    Parameters={
        'commands': [
            'python3 /home/ec2-user/main.py',
        ]
    }
)


问:
Tensorflow : logits and labels must have the same first dimension
I am new in tensoflow and I want to adapt the MNIST tutorial https://www.tensorflow.org/tutorials/layers with my own data (images of 40x40).
This is my model function :

```<code>def cnn_model_fn(features, labels, mode):
        # Input Layer
        input_layer = tf.reshape(features, [-1, 40, 40, 1])

        # Convolutional Layer #1
        conv1 = tf.layers.conv2d(
                inputs=input_layer,
                filters=32,
                kernel_size=[5, 5],
                #  To specify that the output tensor should have the same width and height values as the input tensor
                # value can be "same" ou "valid"
                padding="same",
                activation=tf.nn.relu)

        # Pooling Layer #1
        pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

        # Convolutional Layer #2 and Pooling Layer #2
        conv2 = tf.layers.conv2d(
                inputs=pool1,
                filters=64,
                kernel_size=[5, 5],
                padding="same",
                activation=tf.nn.relu)
        pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

        # Dense Layer
        pool2_flat = tf.reshape(pool2, [-1, 10 * 10 * 64])
        dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
        dropout = tf.layers.dropout(
                inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

        # Logits Layer
        logits = tf.layers.dense(inputs=dropout, units=2)

        predictions = {
            # Generate predictions (for PREDICT and EVAL mode)
            "classes":       tf.argmax(input=logits, axis=1),
            # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
            # `logging_hook`.
            "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
        }

        if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

        # Calculate Loss (for both TRAIN and EVAL modes)
        loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

        # Configure the Training Op (for TRAIN mode)
        if mode == tf.estimator.ModeKeys.TRAIN:
            optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
            train_op = optimizer.minimize(
                    loss=loss,
                    global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

        # Add evaluation metrics (for EVAL mode)
        eval_metric_ops = {
            "accuracy": tf.metrics.accuracy(
                    labels=labels, predictions=predictions["classes"])}
        return tf.estimator.EstimatorSpec(
                mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
</code>```

I have a shape size error between labels and logits :

InvalidArgumentError (see above for traceback): logits and labels must have the same first dimension, got logits shape [3,2] and labels shape [1]

filenames_array is an array of 16 string

```<code>["file1.png", "file2.png", "file3.png", ...]
</code>```

and labels_array is an array of 16 integer

```<code>[0,0,1,1,0,1,0,0,0,...]
</code>```

The main function is :

```<code># Create the Estimator
mnist_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir="/tmp/test_convnet_model")

# Train the model
cust_train_input_fn = lambda: train_input_fn_custom(
        filenames_array=filenames, labels_array=labels, batch_size=1)

mnist_classifier.train(
        input_fn=cust_train_input_fn,
        steps=20000,
        hooks=[logging_hook])
</code>```

I tried to reshape logits without success :

logits = tf.reshape(logits, [1, 2])

I need your help, thanks

EDIT

After more time to search, in the first line of my model function

```<code>input_layer = tf.reshape(features, [-1, 40, 40, 1])
</code>```

the "-1" that signifies that the batch_size dimension will be dynamically calculated have here the value "3". The same "3" as in my error : logits and labels must have the same first dimension, got logits shape [3,2] and labels shape [1]

If I force the value to "1" I have this new error :

Input to reshape is a tensor with 4800 values, but the requested shape has 1600

Maybe a problem with my features ?

EDIT2 :

the complete code is here : https://gist.github.com/geoffreyp/cc8e97aab1bff4d39e10001118c6322e

EDIT3

I updated the gist with

```<code>logits = tf.layers.dense(inputs=dropout, units=1)
</code>```

https://gist.github.com/geoffreyp/cc8e97aab1bff4d39e10001118c6322e

But I don't completely understand your answer about the batch size, how the batch size can be 3 here whereas I choose a batch size of 1 ?

If I choose a batch_size = 3 I have this error :
logits and labels must have the same first dimension, got logits shape [9,1] and labels shape [3]

I tried to reshape labels :

```<code>labels = tf.reshape(labels, [3, 1])
</code>```

and I updated features and labels structure :

```<code>    filenames_train = [['blackcorner-data/1.png', 'blackcorner-data/2.png', 'blackcorner-data/3.png',
                   'blackcorner-data/4.png', 'blackcorner-data/n1.png'],
                   ['blackcorner-data/n2.png',
                   'blackcorner-data/n3.png', 'blackcorner-data/n4.png',
                   'blackcorner-data/11.png', 'blackcorner-data/21.png'],
                   ['blackcorner-data/31.png',
                   'blackcorner-data/41.png', 'blackcorner-data/n11.png', 'blackcorner-data/n21.png',
                   'blackcorner-data/n31.png']
                   ]

labels = [[0, 0, 0, 0, 1], [1, 1, 1, 0, 0], [0, 0, 1, 1, 1]]
</code>```

but without success...

答:
I already had this problem in my first time using tensorflow, i figured out that my problem was forgetting to add the attribute class_mode='sparse' / class_mode='binary' to the function that uploads tha training data and validation data :

So try to look after the class_mode option

```<code>image_gen_val = ImageDataGenerator(rescale=1./255)
val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,
                                                 directory=val_dir,
                                                 target_size=(IMG_SHAPE, IMG_SHAPE),
                                                 class_mode='sparse')
</code>```

Body:
I am new in tensoflow and I want to adapt the MNIST tutorial https://www.tensorflow.org/tutorials/layers with my own data (images of 40x40).
This is my model function :

def cnn_model_fn(features, labels, mode):
        # Input Layer
        input_layer = tf.reshape(features, [-1, 40, 40, 1])

        # Convolutional Layer #1
        conv1 = tf.layers.conv2d(
                inputs=input_layer,
                filters=32,
                kernel_size=[5, 5],
                #  To specify that the output tensor should have the same width and height values as the input tensor
                # value can be "same" ou "valid"
                padding="same",
                activation=tf.nn.relu)

        # Pooling Layer #1
        pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

        # Convolutional Layer #2 and Pooling Layer #2
        conv2 = tf.layers.conv2d(
                inputs=pool1,
                filters=64,
                kernel_size=[5, 5],
                padding="same",
                activation=tf.nn.relu)
        pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

        # Dense Layer
        pool2_flat = tf.reshape(pool2, [-1, 10 * 10 * 64])
        dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
        dropout = tf.layers.dropout(
                inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

        # Logits Layer
        logits = tf.layers.dense(inputs=dropout, units=2)

        predictions = {
            # Generate predictions (for PREDICT and EVAL mode)
            "classes":       tf.argmax(input=logits, axis=1),
            # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
            # `logging_hook`.
            "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
        }

        if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

        # Calculate Loss (for both TRAIN and EVAL modes)
        loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

        # Configure the Training Op (for TRAIN mode)
        if mode == tf.estimator.ModeKeys.TRAIN:
            optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
            train_op = optimizer.minimize(
                    loss=loss,
                    global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

        # Add evaluation metrics (for EVAL mode)
        eval_metric_ops = {
            "accuracy": tf.metrics.accuracy(
                    labels=labels, predictions=predictions["classes"])}
        return tf.estimator.EstimatorSpec(
                mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

I have a shape size error between labels and logits :

InvalidArgumentError (see above for traceback): logits and labels must have the same first dimension, got logits shape [3,2] and labels shape [1]

filenames_array is an array of 16 string

["file1.png", "file2.png", "file3.png", ...]

and labels_array is an array of 16 integer

[0,0,1,1,0,1,0,0,0,...]

The main function is :

# Create the Estimator
mnist_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir="/tmp/test_convnet_model")

# Train the model
cust_train_input_fn = lambda: train_input_fn_custom(
        filenames_array=filenames, labels_array=labels, batch_size=1)

mnist_classifier.train(
        input_fn=cust_train_input_fn,
        steps=20000,
        hooks=[logging_hook])

I tried to reshape logits without success :

logits = tf.reshape(logits, [1, 2])

I need your help, thanks

EDIT

After more time to search, in the first line of my model function

input_layer = tf.reshape(features, [-1, 40, 40, 1])

the "-1" that signifies that the batch_size dimension will be dynamically calculated have here the value "3". The same "3" as in my error : logits and labels must have the same first dimension, got logits shape [3,2] and labels shape [1]

If I force the value to "1" I have this new error :

Input to reshape is a tensor with 4800 values, but the requested shape has 1600

Maybe a problem with my features ?

EDIT2 :

the complete code is here : https://gist.github.com/geoffreyp/cc8e97aab1bff4d39e10001118c6322e

EDIT3

I updated the gist with

logits = tf.layers.dense(inputs=dropout, units=1)

https://gist.github.com/geoffreyp/cc8e97aab1bff4d39e10001118c6322e

But I don't completely understand your answer about the batch size, how the batch size can be 3 here whereas I choose a batch size of 1 ?

If I choose a batch_size = 3 I have this error :
logits and labels must have the same first dimension, got logits shape [9,1] and labels shape [3]

I tried to reshape labels :

labels = tf.reshape(labels, [3, 1])

and I updated features and labels structure :

    filenames_train = [['blackcorner-data/1.png', 'blackcorner-data/2.png', 'blackcorner-data/3.png',
                   'blackcorner-data/4.png', 'blackcorner-data/n1.png'],
                   ['blackcorner-data/n2.png',
                   'blackcorner-data/n3.png', 'blackcorner-data/n4.png',
                   'blackcorner-data/11.png', 'blackcorner-data/21.png'],
                   ['blackcorner-data/31.png',
                   'blackcorner-data/41.png', 'blackcorner-data/n11.png', 'blackcorner-data/n21.png',
                   'blackcorner-data/n31.png']
                   ]

labels = [[0, 0, 0, 0, 1], [1, 1, 1, 0, 0], [0, 0, 1, 1, 1]]

but without success...

Body:
I already had this problem in my first time using tensorflow, i figured out that my problem was forgetting to add the attribute class_mode='sparse' / class_mode='binary' to the function that uploads tha training data and validation data :

So try to look after the class_mode option

image_gen_val = ImageDataGenerator(rescale=1./255)
val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,
                                                 directory=val_dir,
                                                 target_size=(IMG_SHAPE, IMG_SHAPE),
                                                 class_mode='sparse')


问:
Keep messages when I use the Messenger component with Doctrine
I am using the Messenger component configured with Doctrine to store the messages in a database table.

I see that in the default configuration the table "messenger_messages" is automatically created. In it there is a "delivered_at" field.

I want to keep all the messages that are dispatched but when the messages are consumed the corresponding records are automatically deleted.

When I run the process via php bin/console messenger:consume async -vv I see that a timestamp is written to the "delivered_at" field but then the entire record is deleted.

Is there a way that the records are not erased and that the date and time of sending the message is recorded?

答:
It may not express the problem correctly. My application dispatches emails using the Messenger component.

Every email that is dispatched by the application is audited in a file. I can know the amount of mail that the application sends in a period of time.

However, the audited number is not real. The application counts everything that is dispatched. It does not count those that actually reach their destination.

Messenger processes the queue and does not know if the mail is sent by the Mail Server. Just dispatch.

What happen? Emails are obtained from an HTML form. Malformed domains are counted by the application and by Messenger as sent emails.

What I want to obtain is an indicator of how many emails the Mail Server has successfully processed.

I suppose that the solution to my problem is not through the application or the Messenger component, but rather by obtaining some kind of audit from the Mail Server itself.

I tried what Jakumi suggested but the trigger captures all the messages that get to the queue. Even malformed domains like foo@hotmai or bar@aaa.com. The count in this table matches my audit file that records sent emails.

My problem is to count the effectively sent.

Thank you very much for the comments and suggestions.

PS: I apologize for my English. I have used Google's translation services. Wait you understand.