问:
Smart way to get the public Internet IP address/geo loc
I have a computer on the local network, behind a NAT router. I have some 192.168.0.x addresses, but I really want to know my public IP address, not something mentioned in

How to get the IP address of the server on which my C# application is running on?

or

How to get the IP address of a machine in C#

I need C# code.

Is it possible? If so, how?

答:
After some search, and by expanding my requirements, I found out that this will get me not only the IP, but GEO-location as well:

```<code>class GeoIp
{
    static public GeoIpData GetMy()
    {
        string url = "http://freegeoip.net/xml/";
        WebClient wc = new WebClient();
        wc.Proxy = null;
        MemoryStream ms = new MemoryStream(wc.DownloadData(url));
        XmlTextReader rdr = new XmlTextReader(url);
        XmlDocument doc = new XmlDocument();
        ms.Position = 0;
        doc.Load(ms);
        ms.Dispose();
        GeoIpData retval = new GeoIpData();
        foreach (XmlElement el in doc.ChildNodes[1].ChildNodes)
        {
            retval.KeyValue.Add(el.Name, el.InnerText);
        }
        return retval;
    }
}
</code>```

XML returned, and thus key/value dictionary will be filled as such:

```<code><Response>
    <Ip>93.139.127.187</Ip>
    <CountryCode>HR</CountryCode>
    <CountryName>Croatia</CountryName>
    <RegionCode>16</RegionCode>
    <RegionName>Varazdinska</RegionName>
    <City>Varazdinske Toplice</City>
    <ZipCode/>
    <Latitude>46.2092</Latitude>
    <Longitude>16.4192</Longitude>
    <MetroCode/>
</Response>
</code>```

And for convenience, return class:

```<code>class GeoIpData
{
    public GeoIpData()
    {
        KeyValue = new Dictionary<string, string>();
    }
    public Dictionary<string, string> KeyValue;
}
</code>```

Body:
After some search, and by expanding my requirements, I found out that this will get me not only the IP, but GEO-location as well:

class GeoIp
{
    static public GeoIpData GetMy()
    {
        string url = "http://freegeoip.net/xml/";
        WebClient wc = new WebClient();
        wc.Proxy = null;
        MemoryStream ms = new MemoryStream(wc.DownloadData(url));
        XmlTextReader rdr = new XmlTextReader(url);
        XmlDocument doc = new XmlDocument();
        ms.Position = 0;
        doc.Load(ms);
        ms.Dispose();
        GeoIpData retval = new GeoIpData();
        foreach (XmlElement el in doc.ChildNodes[1].ChildNodes)
        {
            retval.KeyValue.Add(el.Name, el.InnerText);
        }
        return retval;
    }
}

XML returned, and thus key/value dictionary will be filled as such:

<Response>
    <Ip>93.139.127.187</Ip>
    <CountryCode>HR</CountryCode>
    <CountryName>Croatia</CountryName>
    <RegionCode>16</RegionCode>
    <RegionName>Varazdinska</RegionName>
    <City>Varazdinske Toplice</City>
    <ZipCode/>
    <Latitude>46.2092</Latitude>
    <Longitude>16.4192</Longitude>
    <MetroCode/>
</Response>

And for convenience, return class:

class GeoIpData
{
    public GeoIpData()
    {
        KeyValue = new Dictionary<string, string>();
    }
    public Dictionary<string, string> KeyValue;
}


来源: stackexchange

问:
Security Rules in Firestore after 30 days
I have been working on a project in firestore, As I was starting I selected the Test mode for firestore that apparently gives you a 30 day "trial", after that  I have to change security stuff, but I have programmed all the gather data and other functions inside my firestore already. If I add a line of code to the security part will I get of these 30 days "trial"?
 I went to change the security rules so I don't lose my database, The normal rules are:

```<code>rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {

// This rule allows anyone on the internet to view, edit, and delete
// all data in your Firestore database. It is useful for getting
// started, but it is configured to expire after 30 days because it
// leaves your app open to attackers. At that time, all client
// requests to your Firestore database will be denied.
//
// Make sure to write security rules for your app before that time, or else
// your app will lose access to your Firestore database
match /{document=**} {
  allow read, write: if request.time < timestamp.date(2020, 6, 2);
}
}
 }
</code>```

If I add this rule to this, will I not lose the firestore stuff that I have?

```<code>match /users/{uid} {
    allow read;
  allow write: if request.auth.uid == uid;
}
</code>```

This is how the final code looks:

```<code>rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {

// This rule allows anyone on the internet to view, edit, and delete
// all data in your Firestore database. It is useful for getting
// started, but it is configured to expire after 30 days because it
// leaves your app open to attackers. At that time, all client
// requests to your Firestore database will be denied.
//
// Make sure to write security rules for your app before that time, or else
// your app will lose access to your Firestore database
match /{document=**} {
  allow read, write: if request.time < timestamp.date(2020, 6, 2);
}

match /users/{uid} {
    allow read;
  allow write: if request.auth.uid == uid;
}
}
}
</code>```

答:
If your goal is to extend your "trial" (which it is not, really - it's a reminder that you really should come up with proper rules), then all you have to do is extend the date that been coded into the rule you've been given.

If you don't remove that original rule completely and come up with proper rules, you will continue to get emails from Firebase reminding you that you have a significant security problem with your rules.  If you just add rules to it, that won't improve the situation, since the rule is effectively giving the world full access to everything else, no matter what.  You will eventually need to remove the rule and replace it with something that accurately describes the security requirements of your system.

ContentLicense: CC BY-SA 4.0

Body:
I have been working on a project in firestore, As I was starting I selected the Test mode for firestore that apparently gives you a 30 day "trial", after that  I have to change security stuff, but I have programmed all the gather data and other functions inside my firestore already. If I add a line of code to the security part will I get of these 30 days "trial"?
 I went to change the security rules so I don't lose my database, The normal rules are:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {

// This rule allows anyone on the internet to view, edit, and delete
// all data in your Firestore database. It is useful for getting
// started, but it is configured to expire after 30 days because it
// leaves your app open to attackers. At that time, all client
// requests to your Firestore database will be denied.
//
// Make sure to write security rules for your app before that time, or else
// your app will lose access to your Firestore database
match /{document=**} {
  allow read, write: if request.time < timestamp.date(2020, 6, 2);
}
}
 }

If I add this rule to this, will I not lose the firestore stuff that I have?

match /users/{uid} {
    allow read;
  allow write: if request.auth.uid == uid;
}

This is how the final code looks:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {

// This rule allows anyone on the internet to view, edit, and delete
// all data in your Firestore database. It is useful for getting
// started, but it is configured to expire after 30 days because it
// leaves your app open to attackers. At that time, all client
// requests to your Firestore database will be denied.
//
// Make sure to write security rules for your app before that time, or else
// your app will lose access to your Firestore database
match /{document=**} {
  allow read, write: if request.time < timestamp.date(2020, 6, 2);
}

match /users/{uid} {
    allow read;
  allow write: if request.auth.uid == uid;
}
}
}


问:
Find level of categories in a hierarchy
I have a script to find the hierarchy of a list of categories. However I would need to know the depth of the level to find all corresponding categories. So my question is there a better way to rewrite the code so that it can drill down to the lowest level without my need to specify how deep to go. As the example below, I had to know that the category level goes to 5 level deep to find all categories.</p>

```<code>WITH rCTE AS
(
    SELECT
        *,
        0 AS Level
    FROM dbo.inv_category ic
    WHERE ic.Primary_org_id = 56392

    UNION ALL

    SELECT
        t.*,
        r.Level + 1 AS Level
    FROM dbo.inv_category t
    INNER JOIN rCTE r ON t.Parent_id = r.Category_id
)
SELECT DISTINCT
    c1.Parent_id, c1.Category_id, c1.Category,
    c2.Category, c2.Category_id, c2.Parent_id,
    c3.Category, c3.Category_id, c3.Parent_id,
    c4.Category, c4.Category_id, c4.Parent_id,
    c5.Category, c5.Category_id, c5.Parent_id
FROM
    rCTE c1
LEFT OUTER JOIN
    rCTE c2 ON c1.Category_id = c2.Parent_id
LEFT OUTER JOIN
    rCTE c3 ON c2.Category_id = c3.Parent_id
LEFT OUTER JOIN
    rCTE c4 ON c3.Category_id = c4.Parent_id
LEFT OUTER JOIN
    rCTE c5 ON c4.Category_id = c5.Parent_id
WHERE
    c1.Parent_id = 0
ORDER BY
    c1.Category, c2.Category
</code>```

答:
Your problem is that you want the parent categories in different columns, which makes the task more complicated that it could be.

One option to shorten the query and avoid multiple joins uses conditional aggregation:

```<code>with rcte as (...)
select
    max(case when level = 0 then parent_id   end) parent_id_0,
    max(case when level = 0 then category_id end) category_id_0,
    max(case when level = 0 then category    end) category_0,
    max(case when level = 1 then parent_id   end) parent_id_1,
    max(case when level = 1 then category_id end) category_id_1,
    max(case when level = 1 then category    end) category_1,
    ...
from rcte
</code>```

You can add more triplets of conditional expression to manage as many maximum levels as needed; when the actual hierarchy of the product exhausts, the following columns will come out empty.

Another option is string aggregation. This generates a unique column for each original column, with all values concatenated in the order in which they appear in the hierarchy:

```<code>with rcte as (...)
select
    string_agg(parent_id,      ' > ') within group(order by level) parent_ids,
    string_agg(category_id_id, ' > ') within group(order by level) category_ids,
    string_agg(category,       ' > ') within group(order by level) categories
from rcte
</code>```

Title: Find level of categories in a hierarchy

Body:
I have a script to find the hierarchy of a list of categories. However I would need to know the depth of the level to find all corresponding categories. So my question is there a better way to rewrite the code so that it can drill down to the lowest level without my need to specify how deep to go. As the example below, I had to know that the category level goes to 5 level deep to find all categories.

WITH rCTE AS
(
    SELECT
        *,
        0 AS Level
    FROM dbo.inv_category ic
    WHERE ic.Primary_org_id = 56392

    UNION ALL

    SELECT
        t.*,
        r.Level + 1 AS Level
    FROM dbo.inv_category t
    INNER JOIN rCTE r ON t.Parent_id = r.Category_id
)
SELECT DISTINCT
    c1.Parent_id, c1.Category_id, c1.Category,
    c2.Category, c2.Category_id, c2.Parent_id,
    c3.Category, c3.Category_id, c3.Parent_id,
    c4.Category, c4.Category_id, c4.Parent_id,
    c5.Category, c5.Category_id, c5.Parent_id
FROM
    rCTE c1
LEFT OUTER JOIN
    rCTE c2 ON c1.Category_id = c2.Parent_id
LEFT OUTER JOIN
    rCTE c3 ON c2.Category_id = c3.Parent_id
LEFT OUTER JOIN
    rCTE c4 ON c3.Category_id = c4.Parent_id
LEFT OUTER JOIN
    rCTE c5 ON c4.Category_id = c5.Parent_id
WHERE
    c1.Parent_id = 0
ORDER BY
    c1.Category, c2.Category

Body:
Your problem is that you want the parent categories in different columns, which makes the task more complicated that it could be.

One option to shorten the query and avoid multiple joins uses conditional aggregation:

with rcte as (...)
select
    max(case when level = 0 then parent_id   end) parent_id_0,
    max(case when level = 0 then category_id end) category_id_0,
    max(case when level = 0 then category    end) category_0,
    max(case when level = 1 then parent_id   end) parent_id_1,
    max(case when level = 1 then category_id end) category_id_1,
    max(case when level = 1 then category    end) category_1,
    ...
from rcte

You can add more triplets of conditional expression to manage as many maximum levels as needed; when the actual hierarchy of the product exhausts, the following columns will come out empty.

Another option is string aggregation. This generates a unique column for each original column, with all values concatenated in the order in which they appear in the hierarchy:

with rcte as (...)
select
    string_agg(parent_id,      ' > ') within group(order by level) parent_ids,
    string_agg(category_id_id, ' > ') within group(order by level) category_ids,
    string_agg(category,       ' > ') within group(order by level) categories
from rcte


问:
verilog ; can't use "string" type in $display
I'm using a recent master branch build of icarus verilog.

Should I expect the following to run?

```<code>module string_display ();

//reg [10:0][7:0] x = "initial";
string x = "initial";

always @* begin
  $display ("x = %s",x);
end

initial begin

  // Assign new string
  x = "aaaaa";
  #1

  // Assign new string
  x = "bbbb";
  #1

  #1 $finish;
end

endmodule
</code>```

The above gives

```<code>internal error: 18vvp_fun_anyedge_sa: recv_string(initial) not implemented
vvp: vvp_net.cc:2972: virtual void vvp_net_fun_t::recv_string(vvp_net_ptr_t, const string&, vvp_context_t): Assertion `0' failed.
</code>```

However, if I define 'x' as a reg by uncommenting the line above then it works as expected ...

```<code>x =       aaaaa
x =        bbbb
</code>```

答:
No, you should not expect Icarus Verilog to support the string keyword, which was introduced in the IEEE Std 1800 for SystemVerilog.

According to the Icarus website:

The compiler proper is intended to parse and elaborate design
  descriptions written to the IEEE standard IEEE Std 1364-2005. This is
  a fairly large and complex standard, so it will take some time to fill
  all the dark alleys of the standard, but that's the goal.

There is no mention of IEEE Std 1800.

You can look at the extensions.txt file from the github site, which states:

Icarus Verilog supports certain extensions to the baseline IEEE1364
  standard. Some of these are picked from extended variants of the
  language, such as SystemVerilog, ...

But, there is no mention of string there.

I tried your code with the -g2012 option on edaplayground, but I get the same error.  You could try it on your version.

Body:
I'm using a recent master branch build of icarus verilog.

Should I expect the following to run?

module string_display ();

//reg [10:0][7:0] x = "initial";
string x = "initial";

always @* begin
  $display ("x = %s",x);
end

initial begin

  // Assign new string
  x = "aaaaa";
  #1

  // Assign new string
  x = "bbbb";
  #1

  #1 $finish;
end

endmodule

The above gives

internal error: 18vvp_fun_anyedge_sa: recv_string(initial) not implemented
vvp: vvp_net.cc:2972: virtual void vvp_net_fun_t::recv_string(vvp_net_ptr_t, const string&, vvp_context_t): Assertion `0' failed.

However, if I define 'x' as a reg by uncommenting the line above then it works as expected ...

x =       aaaaa
x =        bbbb


问:
How to avoid function calling again and again
I created a function called remove_role which used to remove permission based on the role.  I can able to achieve by calling function again and again. Is there any other way  to avoid calling function repeatedly ?</p>

```<code>    remove_role('author', 'edit_others_pages');
    remove_role('author', 'upload_files');
    remove_role('author', 'manage_categories');```

</code>```

答:
It all very much depends on what is in your remove_role function but one approach would be to use an array and then loop through it in your function e.g.</p>

```<code>$protectedPages = ['edit_other_pages','upload_files','manage_categories']
remove_role('author', $protectedPages);

public function remove_role($role, $pages) {

     foreach($pages as $page) {
        // Do what you need to do here
    }
}
</code>```

Body:
I created a function called remove_role which used to remove permission based on the role.  I can able to achieve by calling function again and again. Is there any other way  to avoid calling function repeatedly ?

    remove_role('author', 'edit_others_pages');
    remove_role('author', 'upload_files');
    remove_role('author', 'manage_categories');```

Body:
It all very much depends on what is in your remove_role function but one approach would be to use an array and then loop through it in your function e.g.

$protectedPages = ['edit_other_pages','upload_files','manage_categories']
remove_role('author', $protectedPages);

public function remove_role($role, $pages) {

     foreach($pages as $page) {
        // Do what you need to do here
    }
}


问:
Spring Data JPA: How to join two entities using annotations
I have two entities(Student and Project) and want to join them by foreign key "student_id"

```<code>@Entity
@Data
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private Long student_id;
}
</code>```

```<code>@Entity
@Data
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany
    private List<Project> projects;
}
</code>```

Simply, I want to get students with project list when I send GET request to Student repository.

For example;

```<code>// > json for POST to Project
{
    "title":"java",
    "student_id":1
}
</code>```

```<code>// > json for POST to Student
{
    "name":"Bill Gates"
}
</code>```

What I expect to see when I send GET request to Student is simply like this below;

```<code>[
   {
      "id":1,
      "name":"java",
      "projects":[
         {
            "id":1,
            "title":"java"
         }
      ]
   }
]
</code>```

Is it applicable using only JPA annotations? Thanks in advance.

答:
Yes, it's applicable.
First, you need to change the student_id to student class like this in your Project class

```<code>@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "student_id",nullable = false)
private Student student;
</code>```

Second, you need to add 'map' parameter to you oneToMany annotation

```<code>@OneToMany(mappedBy = "student")
private List<Project> projects;
</code>```

and that's it.

Side note: you can also consider manytomany relationship if more than one student can be assigned to the same project

Body:
I have two entities(Student and Project) and want to join them by foreign key "student_id"

@Entity
@Data
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private Long student_id;
}

@Entity
@Data
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany
    private List<Project> projects;
}

Simply, I want to get students with project list when I send GET request to Student repository.

For example;

// > json for POST to Project
{
    "title":"java",
    "student_id":1
}

// > json for POST to Student
{
    "name":"Bill Gates"
}

What I expect to see when I send GET request to Student is simply like this below;

[
   {
      "id":1,
      "name":"java",
      "projects":[
         {
            "id":1,
            "title":"java"
         }
      ]
   }
]

Is it applicable using only JPA annotations? Thanks in advance.

Body:
Yes, it's applicable.
First, you need to change the student_id to student class like this in your Project class

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "student_id",nullable = false)
private Student student;

Second, you need to add 'map' parameter to you oneToMany annotation

@OneToMany(mappedBy = "student")
private List<Project> projects;

and that's it.

Side note: you can also consider manytomany relationship if more than one student can be assigned to the same project


问:
How do i convert a textfile to lower case and find the frequencies of the letters?
I am writing a code that reads a text file and outputs the frequency of the letters. I used a FileInputStream method to read the file and I have no idea on how to convert the uppercase to lower case.

The code runs but only lower case letters are being read. How do i rectify the issue?

答:
Your program works fairly well.  To convert to lower case see the following:

```<code>while ((d = fileInputStream.read()) != -1) {
    d = Character.toLowerCase(d); // <-- add this line here
    char ch = 'a';
    for (int i = 0; i < 26; i++) {

       if (d == ch) {
           f[i] = f[i] + 1;
       }
       ch++;
    }
}
</code>```

A couple other suggestions.

put a catch block at then end of your try block.

```<code>} catch (IOException e) {
    e.printStackTrace();
}
</code>```

And when you print out the characters, ignore those with zero count to make your frequency count more readable.

And primitive number arrays are initialized to 0's so you don't need to do that.

Body:
Your program works fairly well.  To convert to lower case see the following:

while ((d = fileInputStream.read()) != -1) {
    d = Character.toLowerCase(d); // <-- add this line here
    char ch = 'a';
    for (int i = 0; i < 26; i++) {

       if (d == ch) {
           f[i] = f[i] + 1;
       }
       ch++;
    }
}

A couple other suggestions.

put a catch block at then end of your try block.

} catch (IOException e) {
    e.printStackTrace();
}

And when you print out the characters, ignore those with zero count to make your frequency count more readable.

And primitive number arrays are initialized to 0's so you don't need to do that.


问:
printing of xml
I want to print the array into xml format but i am unable to print it.
Here is the code

```<code>if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){
</code>```

print("".$data['user_id']."".$data['$task_id']."\n");

```<code>}
print("</joblist>\n");

}
}
</code>```

even i am unable to see

```<code><?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>
</code>```

when i am doing view source its showing

```<code><?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>
</code>```

now what to be done to display on the web page

答:
I see at least two problems:

I don't think print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>"); will generate valid xml, shouldn´t it be:

print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");

I don´t think print("<job><id>$data[$user_id]</id><taskid>$data[$task_id]</taskid></job>\n"); is going to work, try something like:

print("<job><id>".$data[$user_id]."</id><taskid>".$data[$task_id]."</taskid></job>\n");

ContentLicense: CC BY-SA 3.0

Title: printing of xml

Body:
I want to print the array into xml format but i am unable to print it.
Here is the code

if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){

print("".$data['user_id']."".$data['$task_id']."\n");

}
print("</joblist>\n");

}
}

even i am unable to see

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>

when i am doing view source its showing

<?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>

now what to be done to display on the web page


问:
Python/NumPy: find the first index of zero, then replace all elements with zero after that for each row
I have an numpy array like this:

```<code>a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])
</code>```

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

```<code>a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])
</code>```

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

答:
I prefer Ayrat's creative answer for the first question, but if you need to slice different columns for different rows in large size, this could help you:

```<code>indexer = tuple(np.s_[i:a.shape[1]] for i in (a==0).argmax(axis=1))
for i,j in enumerate(indexer):
    a[i,j]=0
</code>```

indexer:

```<code>(slice(1, 5, None), slice(4, 5, None), slice(1, 5, None), slice(1, 5, None))
</code>```

or:

```<code>indexer = (a==0).argmax(axis=1)
for i in range(a.shape[0]):
    a[i,indexer[i]:]=0
</code>```

indexer:

```<code>[1 4 1 1]
</code>```

output:

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

Body:
I have an numpy array like this:

a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

Body:
I prefer Ayrat's creative answer for the first question, but if you need to slice different columns for different rows in large size, this could help you:

indexer = tuple(np.s_[i:a.shape[1]] for i in (a==0).argmax(axis=1))
for i,j in enumerate(indexer):
    a[i,j]=0

indexer:

(slice(1, 5, None), slice(4, 5, None), slice(1, 5, None), slice(1, 5, None))

or:

indexer = (a==0).argmax(axis=1)
for i in range(a.shape[0]):
    a[i,indexer[i]:]=0

indexer:

[1 4 1 1]

output:

[[1 0 0 0 0]
 [1 1 1 1 0]
 [1 0 0 0 0]
 [1 0 0 0 0]]


问:
Border with Kivy/KivyMD
I am looking to add a border to the main screen of my application but I'm not sure how.
I tried to take some tips from this question:
 Kivy-how can i make my canvas height smaller than the parent height
But I can't seem to figure it out.

The issue is that I am also using a KivyMD's Navigation Drawer, I would like the border be separate from the top bar, enclosing everything below the bar. Please let me know if I'm not being clear.

Here is some sample code that replicates my setup.

Perhaps I could add some random rectangles to act as a border?

EDIT:

Okay almost there, I got the 'border' but I now need the size_hint added in the AnchorLayout to ignore the top portion of the screen where the menu bar is. Here is the updated code.

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

from kivymd.app import MDApp

kv = '''
#:import hex kivy.utils.get_color_from_hex

NavigationLayout:
    canvas.before:
        Color:
            rgb: hex('#C0C0C0')
        Rectangle:
            size: self.size
            pos: self.pos
    ScreenManager:
        id: screen_manager
        Screen:
            name: "home_screen"
            BoxLayout:
                orientation: 'vertical'
                MDToolbar:
                    title: 'Name of the App!'
                    elevation: 10
                Widget:
            FloatLayout:

                orientation: 'vertical'
                AnchorLayout:
                    anchor_x: 'center'
                    anchor_y: 'center'
                    Widget:
                        canvas.before:
                            Color:
                                rgb: hex('#F5F5F5')
                            Rectangle:
                                size: self.size
                                pos: self.pos
                        size_hint: .95, .95
                MDLabel:
                    text: "Some More Text"
                    halign: "center"
                    color: 0,0,0,1
                    pos_hint: {"center_x": .5, "center_y": .75}
                    size_hint: .7, .1

    MDNavigationDrawer:
        id: nav_drawer
        ContentNavigationDrawer:
            orientation: "vertical"
            padding: "8dp"
            spacing: "8dp"
            AnchorLayout:
                anchor_x: "left"
                size_hint_y: None
                height: avatar.height
                Image:
                    id: avatar
                    source: "image.jpg"
            MDLabel:
                text: "Text here"
                font_style: "Button"
                size_hint_y: None
                height: self.texture_size[1]
    '''
class ContentNavigationDrawer(BoxLayout):
    pass

class MyApp(MDApp):
    def build(self):
        return Builder.load_string(kv)

MyApp().run()

</code>```

答:
I think you will get what you want if you indent the FloatLayout so that it is in the BoxLayout. Like this:

```<code>#:import hex kivy.utils.get_color_from_hex

NavigationLayout:
    canvas.before:
        Color:
            rgb: hex('#C0C0C0')
        Rectangle:
            size: self.size
            pos: self.pos
    ScreenManager:
        id: screen_manager
        Screen:
            name: "home_screen"
            BoxLayout:
                orientation: 'vertical'
                MDToolbar:
                    title: 'Name of the App!'
                    elevation: 10
                # Widget:  # not needed
                FloatLayout:

                    orientation: 'vertical'
                    AnchorLayout:
                        anchor_x: 'center'
                        anchor_y: 'center'
                        Widget:
                            canvas.before:
                                Color:
                                    rgb: hex('#F5F5F5')
                                Rectangle:
                                    size: self.size
                                    pos: self.pos
                            size_hint: .95, .95
                    MDLabel:
                        text: "Some More Text"
                        halign: "center"
                        color: 0,0,0,1
                        pos_hint: {"center_x": .5, "center_y": .75}
                        size_hint: .7, .1

    MDNavigationDrawer:
        id: nav_drawer
        ContentNavigationDrawer:
            orientation: "vertical"
            padding: "8dp"
            spacing: "8dp"
            AnchorLayout:
                anchor_x: "left"
                size_hint_y: None
                height: avatar.height
                Image:
                    id: avatar
                    # source: "image.jpg"
                    source: 'tester.png'
            MDLabel:
                text: "Text here"
                font_style: "Button"
                size_hint_y: None
                height: self.texture_size[1]
</code>```

Title: Border with Kivy/KivyMD

Body:
I am looking to add a border to the main screen of my application but I'm not sure how.
I tried to take some tips from this question:
 Kivy-how can i make my canvas height smaller than the parent height
But I can't seem to figure it out.

The issue is that I am also using a KivyMD's Navigation Drawer, I would like the border be separate from the top bar, enclosing everything below the bar. Please let me know if I'm not being clear.

Here is some sample code that replicates my setup.

Perhaps I could add some random rectangles to act as a border?

EDIT:

Okay almost there, I got the 'border' but I now need the size_hint added in the AnchorLayout to ignore the top portion of the screen where the menu bar is. Here is the updated code.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

from kivymd.app import MDApp

kv = '''
#:import hex kivy.utils.get_color_from_hex

NavigationLayout:
    canvas.before:
        Color:
            rgb: hex('#C0C0C0')
        Rectangle:
            size: self.size
            pos: self.pos
    ScreenManager:
        id: screen_manager
        Screen:
            name: "home_screen"
            BoxLayout:
                orientation: 'vertical'
                MDToolbar:
                    title: 'Name of the App!'
                    elevation: 10
                Widget:
            FloatLayout:

                orientation: 'vertical'
                AnchorLayout:
                    anchor_x: 'center'
                    anchor_y: 'center'
                    Widget:
                        canvas.before:
                            Color:
                                rgb: hex('#F5F5F5')
                            Rectangle:
                                size: self.size
                                pos: self.pos
                        size_hint: .95, .95
                MDLabel:
                    text: "Some More Text"
                    halign: "center"
                    color: 0,0,0,1
                    pos_hint: {"center_x": .5, "center_y": .75}
                    size_hint: .7, .1

    MDNavigationDrawer:
        id: nav_drawer
        ContentNavigationDrawer:
            orientation: "vertical"
            padding: "8dp"
            spacing: "8dp"
            AnchorLayout:
                anchor_x: "left"
                size_hint_y: None
                height: avatar.height
                Image:
                    id: avatar
                    source: "image.jpg"
            MDLabel:
                text: "Text here"
                font_style: "Button"
                size_hint_y: None
                height: self.texture_size[1]
    '''
class ContentNavigationDrawer(BoxLayout):
    pass

class MyApp(MDApp):
    def build(self):
        return Builder.load_string(kv)

MyApp().run()

Body:
I think you will get what you want if you indent the FloatLayout so that it is in the BoxLayout. Like this:

#:import hex kivy.utils.get_color_from_hex

NavigationLayout:
    canvas.before:
        Color:
            rgb: hex('#C0C0C0')
        Rectangle:
            size: self.size
            pos: self.pos
    ScreenManager:
        id: screen_manager
        Screen:
            name: "home_screen"
            BoxLayout:
                orientation: 'vertical'
                MDToolbar:
                    title: 'Name of the App!'
                    elevation: 10
                # Widget:  # not needed
                FloatLayout:

                    orientation: 'vertical'
                    AnchorLayout:
                        anchor_x: 'center'
                        anchor_y: 'center'
                        Widget:
                            canvas.before:
                                Color:
                                    rgb: hex('#F5F5F5')
                                Rectangle:
                                    size: self.size
                                    pos: self.pos
                            size_hint: .95, .95
                    MDLabel:
                        text: "Some More Text"
                        halign: "center"
                        color: 0,0,0,1
                        pos_hint: {"center_x": .5, "center_y": .75}
                        size_hint: .7, .1

    MDNavigationDrawer:
        id: nav_drawer
        ContentNavigationDrawer:
            orientation: "vertical"
            padding: "8dp"
            spacing: "8dp"
            AnchorLayout:
                anchor_x: "left"
                size_hint_y: None
                height: avatar.height
                Image:
                    id: avatar
                    # source: "image.jpg"
                    source: 'tester.png'
            MDLabel:
                text: "Text here"
                font_style: "Button"
                size_hint_y: None
                height: self.texture_size[1]


问:
Getting returning value from multithreading in python 3
I'm trying to get one or several returning values from a thread in a multithreading process. The code I show get cycled with no way to interrupt it with Ctrl-C, Ctrl+D.

```<code>import queue as Queue
import threading

class myThread (threading.Thread):
   def __init__(self, threadID, name, region):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.region = region
   def run(self):
      GetSales(self.region)

def GetSales(strReg):
    print("Thread-" + strReg)
    return "Returning-" + strReg

def Main():

    RegionList = []
    RegionList.append("EMEA")
    RegionList.append("AP")
    RegionList.append("AM")

    # Create threads
    threads = []
    x = 0
    for region in RegionList:
        x += 1
        rthread = myThread(x, "Thread-" + region, region)   # Create new thread
        rthread.start()                                     # Start new thread
        threads.append(rthread)                             # Add new thread to threads list

    que = Queue.Queue()

    # Wait for all threads to complete
    for t in threads:
        t.join()
        result = que.get()
        print(t.name + " -> Done")

Main()
</code>```

If I comment line "result = que.get()" the program runs with no issues.

答:
What you are looking for is future and async management.

Firstly, your program loop indefinitely because of the line que.get(), because there is nothing in the queue, it wait that something happen, which will never happen. You don't use it.

What you want to do is an async task and get the result :

import asyncio

async def yourExpensiveTask():
    // some long calculation
    return 42

async main():
    tasks = []
    tasks += [asyncio.create_task(yourExpensiveTask())]
    tasks += [asyncio.create_task(yourExpensiveTask())]

    for task in tasks:
        result = await task
        print(result)

```

See also https://docs.python.org/3/library/asyncio-task.html

Body:
I'm trying to get one or several returning values from a thread in a multithreading process. The code I show get cycled with no way to interrupt it with Ctrl-C, Ctrl+D.

import queue as Queue
import threading

class myThread (threading.Thread):
   def __init__(self, threadID, name, region):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.region = region
   def run(self):
      GetSales(self.region)

def GetSales(strReg):
    print("Thread-" + strReg)
    return "Returning-" + strReg

def Main():

    RegionList = []
    RegionList.append("EMEA")
    RegionList.append("AP")
    RegionList.append("AM")

    # Create threads
    threads = []
    x = 0
    for region in RegionList:
        x += 1
        rthread = myThread(x, "Thread-" + region, region)   # Create new thread
        rthread.start()                                     # Start new thread
        threads.append(rthread)                             # Add new thread to threads list

    que = Queue.Queue()

    # Wait for all threads to complete
    for t in threads:
        t.join()
        result = que.get()
        print(t.name + " -> Done")

Main()

If I comment line "result = que.get()" the program runs with no issues.

Body:
What you are looking for is future and async management.

Firstly, your program loop indefinitely because of the line que.get(), because there is nothing in the queue, it wait that something happen, which will never happen. You don't use it.

What you want to do is an async task and get the result :

import asyncio

async def yourExpensiveTask():
    // some long calculation
    return 42

async main():
    tasks = []
    tasks += [asyncio.create_task(yourExpensiveTask())]
    tasks += [asyncio.create_task(yourExpensiveTask())]

    for task in tasks:
        result = await task
        print(result)

See also https://docs.python.org/3/library/asyncio-task.html


问:
How to generate random URL in urls.py each time the user logs in (Django)?
I am trying to create a random URL that can be accessed only once after the user logs in.

I am using django-sesame to generate different URLs each time the user logs in. To do this, I have set the SESAME_ONE_TIME setting to True in settings.py, and I am able to redirect the user to the random URL like this:

views.py:

```<code>from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .models import my_model
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
import sesame

@login_required()
def password_form(request):

    url_extension = sesame.utils.get_query_string(request.user)

    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            return redirect('/success/' + url_extension)
    else:
        form = PasswordChangeForm(request.user)

    context = {'form': form}
    return render(request, "form.html", context)
</code>```

However, in urls.py I don't know how to add the URL to urlpatterns properly. This probably sounds weird, but, for a lack of better wording, is there any way you can add a parameter that can accept a randomly generated value in path, like:

urls.py:

```<code>from app.views import password_form

urlpatterns = [path('success/' + random_variable, password_form),]
</code>```

If not, is there any way I can make the url_extension variable global, so that I can use it in urls.py, by bypassing the need for request (e.g. setting url_extension as an attribute to a function in views.py and using it as function.url_extension in urls.py)?

答: You should use a regular expression where you allow success at the starting and the anything after that. Your regular expression in url will be something like this - success/.*$. This check for a success and then allows *(everything) after /.</p>

Body:
I am trying to create a random URL that can be accessed only once after the user logs in.

I am using django-sesame to generate different URLs each time the user logs in. To do this, I have set the SESAME_ONE_TIME setting to True in settings.py, and I am able to redirect the user to the random URL like this:

views.py:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .models import my_model
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
import sesame

@login_required()
def password_form(request):

    url_extension = sesame.utils.get_query_string(request.user)

    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            return redirect('/success/' + url_extension)
    else:
        form = PasswordChangeForm(request.user)

    context = {'form': form}
    return render(request, "form.html", context)

However, in urls.py I don't know how to add the URL to urlpatterns properly. This probably sounds weird, but, for a lack of better wording, is there any way you can add a parameter that can accept a randomly generated value in path, like:

urls.py:

from app.views import password_form

urlpatterns = [path('success/' + random_variable, password_form),]

If not, is there any way I can make the url_extension variable global, so that I can use it in urls.py, by bypassing the need for request (e.g. setting url_extension as an attribute to a function in views.py and using it as function.url_extension in urls.py)?


问:
jquery choosing methods
I love using the hide()  and show() methods, but I've come across someone's scripting where they never use it.

Instead I see them using attr() for anything related to display.

```<code>$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");
</code>```

Is this just purely preferential?

Or is it more beneficial to use one vs the other?

答:
Hide() and show() effectively remove the element from the source HTML.

Visibility rules only affect whether or not you can see the elements' contents; the space they take up is still reserved, and becomes a blank spot.

Title: jquery choosing methods

Body:
I love using the hide()  and show() methods, but I've come across someone's scripting where they never use it.

Instead I see them using attr() for anything related to display.

$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");

Is this just purely preferential?

Or is it more beneficial to use one vs the other?


问:
Multer-S3 with sharp upload and resize
I've been able to upload to s3 an image file using multer-s3 library but now I'm trying to add the sharp library to resize and rotate but can't figure out where or how it needs to go.  This is my current code that works for uploading:

```<code>var options = {
'endpoint' : 'https://xxx',
'accessKeyId' : '123',
'secretAccessKey' : '123abc',
'region' : 'xxx'
};

 const s3 = new aws.S3(options);

const upload = multer({
storage: multerS3({
    s3: s3,
    bucket: 'wave',
    acl: 'public-read',
    metadata: function (req, file, cb) {
      cb(null, Object.assign({}, req.body));
    },
    key: function (request, file, cb) {
        console.log('inside multerS3',file);
        cb(null, file.originalname);
    }
})
}).array('file', 1);

app.post('/upload/', (req,res) => {
   upload(req,res, async function (error) {
     if(error){
        res.send({ status : error });
     }else{
        console.log(req.files[0]);
        res.send({ status : 'true' });
     }
    });
 });
</code>```

And do something like this with the file:

```<code> sharp(input)
 .resize({ width: 100 })
 .toBuffer()
 .then(data => {
   // 100 pixels wide, auto-scaled height
 });
</code>```

Any help would be greatly appreciated :)

答:
Edit (12/24/2020):
I can no longer recommend this package and I'm no longer using it in my projects. This package lacks many of the other features multerS3 has, including AUTO_CONTENT_TYPE which I use often to automatically set the content-type in S3.
I highly recommend just sticking to multerS3 or not even using multerS3 at all and handling the multipart form data yourself with something like multiparty.

Original post:
I found this package on npm called multer-sharp-s3 Link: https://www.npmjs.com/package/multer-sharp-s3.

I'm using this implementation:

var upload = multer({
    storage: multerS3({
        s3: s3,
        ACL: 'public-read',
        Bucket: s3Bucket,
        Key: (req, file, cb) => {
            cb(null, file.originalname);
        },
        resize: {
            width: 100,
            height: 100
        }
    }),
    fileFilter: fileFilter
});
```

Hope this helps!

Title: Multer-S3 with sharp upload and resize

Body:
I've been able to upload to s3 an image file using multer-s3 library but now I'm trying to add the sharp library to resize and rotate but can't figure out where or how it needs to go.  This is my current code that works for uploading:

var options = {
'endpoint' : 'https://xxx',
'accessKeyId' : '123',
'secretAccessKey' : '123abc',
'region' : 'xxx'
};

 const s3 = new aws.S3(options);

const upload = multer({
storage: multerS3({
    s3: s3,
    bucket: 'wave',
    acl: 'public-read',
    metadata: function (req, file, cb) {
      cb(null, Object.assign({}, req.body));
    },
    key: function (request, file, cb) {
        console.log('inside multerS3',file);
        cb(null, file.originalname);
    }
})
}).array('file', 1);

app.post('/upload/', (req,res) => {
   upload(req,res, async function (error) {
     if(error){
        res.send({ status : error });
     }else{
        console.log(req.files[0]);
        res.send({ status : 'true' });
     }
    });
 });

And do something like this with the file:

 sharp(input)
 .resize({ width: 100 })
 .toBuffer()
 .then(data => {
   // 100 pixels wide, auto-scaled height
 });

Any help would be greatly appreciated :)

Body:
Edit (12/24/2020):
I can no longer recommend this package and I'm no longer using it in my projects. This package lacks many of the other features multerS3 has, including AUTO_CONTENT_TYPE which I use often to automatically set the content-type in S3.
I highly recommend just sticking to multerS3 or not even using multerS3 at all and handling the multipart form data yourself with something like multiparty.

Original post:
I found this package on npm called multer-sharp-s3 Link: https://www.npmjs.com/package/multer-sharp-s3.

I'm using this implementation:

var upload = multer({
    storage: multerS3({
        s3: s3,
        ACL: 'public-read',
        Bucket: s3Bucket,
        Key: (req, file, cb) => {
            cb(null, file.originalname);
        },
        resize: {
            width: 100,
            height: 100
        }
    }),
    fileFilter: fileFilter
});

Hope this helps!


问:
Angular Firestore - Get document ID as a property to use it again in an other function - Typescript
So here is my code :

```<code>getOutfitsCollectionData(): Promise<any> {
    let outfitsRef = this.afStore.collection('outfits');
    let allOutfits = outfitsRef.snapshotChanges().pipe(
        map(actions=>{
            return actions.map(a=>{
                const id = a.payload.doc.id;
                return id
            })
        })
    )
    let outfitsID =  allOutfits.forEach(outID=>{
        console.log(outID)
        return outID
    })
    return outfitsID
}
}
</code>```

When I do this part

```<code>let outfitsID =  allOutfits.forEach(outID=>{
        console.log(outID)
        return outID
    })
</code>```

The console is giving me this :

console perfect

It's exactly what I want, I just want to rename the array and set it as the result of my function but every console.log I put under these lines doesn't do anything so it seems that every line under isn't doing anything.

If I'm not clear, tell me guys !

What I'm trying to do is get each documents id of my collection to use it in an other function on the same tab.

I think that it might be easier to create a service but I don't really know how to do it.

Please don't make me ban one more time, I'm just trying to learn ... It won't be really smart to send me to a really general subject.

I'm not just trying to have pro that give a code that works, I want to understand and get better.

Thanks for your help guys !

( BTW sorry for my bad English, I'm French :) )

So just a little edit :

I tried this code, I don't really understand why when I console.log allOutfits, I'm not getting the good value :

```<code>async getOutfitsCollectionData(){
    let outfitsRef = this.afStore.collection('outfits');
    let allOutfits = await outfitsRef.get().toPromise().then((step)=>{
        return step.forEach(doc=>{
        if (!doc.exists){
            console.log('Zut !')
        }else{
            console.log(doc.id)
            return doc.id
        }
    })
})
.catch(err=>{
    console.log('Error getting outfits', err)
})
console.log(allOutfits)
return allOutfits
}
</code>```

答:
Problem lies in this code:

```<code>return step.forEach(doc=>{
        if (!doc.exists){
            console.log('Zut !')
        }else{
            console.log(doc.id)
            return doc.id
        }
</code>```

step is a QuerySnapshot so you should access the documents using step.docs. The function forEach does not return you the the array, but returns undefined instead.
use map which actually returns the transformed data:

```<code>return steps.docs.map(doc => doc.id);
</code>```

Body:
So here is my code :

getOutfitsCollectionData(): Promise<any> {
    let outfitsRef = this.afStore.collection('outfits');
    let allOutfits = outfitsRef.snapshotChanges().pipe(
        map(actions=>{
            return actions.map(a=>{
                const id = a.payload.doc.id;
                return id
            })
        })
    )
    let outfitsID =  allOutfits.forEach(outID=>{
        console.log(outID)
        return outID
    })
    return outfitsID
}
}

When I do this part

let outfitsID =  allOutfits.forEach(outID=>{
        console.log(outID)
        return outID
    })

The console is giving me this :

console perfect

It's exactly what I want, I just want to rename the array and set it as the result of my function but every console.log I put under these lines doesn't do anything so it seems that every line under isn't doing anything.

If I'm not clear, tell me guys !

What I'm trying to do is get each documents id of my collection to use it in an other function on the same tab.

I think that it might be easier to create a service but I don't really know how to do it.

Please don't make me ban one more time, I'm just trying to learn ... It won't be really smart to send me to a really general subject.

I'm not just trying to have pro that give a code that works, I want to understand and get better.

Thanks for your help guys !

( BTW sorry for my bad English, I'm French :) )

So just a little edit :

I tried this code, I don't really understand why when I console.log allOutfits, I'm not getting the good value :

async getOutfitsCollectionData(){
    let outfitsRef = this.afStore.collection('outfits');
    let allOutfits = await outfitsRef.get().toPromise().then((step)=>{
        return step.forEach(doc=>{
        if (!doc.exists){
            console.log('Zut !')
        }else{
            console.log(doc.id)
            return doc.id
        }
    })
})
.catch(err=>{
    console.log('Error getting outfits', err)
})
console.log(allOutfits)
return allOutfits
}

Body:
Problem lies in this code:

return step.forEach(doc=>{
        if (!doc.exists){
            console.log('Zut !')
        }else{
            console.log(doc.id)
            return doc.id
        }

step is a QuerySnapshot so you should access the documents using step.docs. The function forEach does not return you the the array, but returns undefined instead.
use map which actually returns the transformed data:

return steps.docs.map(doc => doc.id);


问:
Using the value in one column to specify from which row to retrieve a value for a new column
I'm looking for an automated way of converting this:

dat = tribble(
    ~a, ~b, ~c
    , 'x', 1, 'y'
    , 'y', 2, NA
    , 'q', 4, NA
    , 'z', 3, 'q'
)
```

<p>to:</p>

<pre class="lang-r prettyprint-override"><code>tribble(
    ~a, ~b, ~d
    , 'x', 1, 2
    , 'z', 3, 4
)
</code>```

So, the column c in dat encodes which row in dat to look at to grab a value for a new column d, and if c is NA, toss that row from the output. Any tips?

答:
We can join dat with itself using c and a columns.

```<code>library(dplyr)

dat %>%
  inner_join(dat %>% select(-c) %>% rename(d = 'b'),
             by = c('c' = 'a'))

# A tibble: 2 x 4
#  a         b c         d
#  <chr> <dbl> <chr> <dbl>
#1 x         1 y         2
#2 z         3 q         4
</code>```

In base R, we can do this with merge :

```<code>merge(dat, dat[-3], by.x = 'c', by.y = 'a')
</code>```

Body:
I'm looking for an automated way of converting this:

dat = tribble(
    ~a, ~b, ~c
    , 'x', 1, 'y'
    , 'y', 2, NA
    , 'q', 4, NA
    , 'z', 3, 'q'
)

to:

tribble(
    ~a, ~b, ~d
    , 'x', 1, 2
    , 'z', 3, 4
)

So, the column c in dat encodes which row in dat to look at to grab a value for a new column d, and if c is NA, toss that row from the output. Any tips?

Body:
We can join dat with itself using c and a columns.

library(dplyr)

dat %>%
  inner_join(dat %>% select(-c) %>% rename(d = 'b'),
             by = c('c' = 'a'))

# A tibble: 2 x 4
#  a         b c         d
#  <chr> <dbl> <chr> <dbl>
#1 x         1 y         2
#2 z         3 q         4

In base R, we can do this with merge :

merge(dat, dat[-3], by.x = 'c', by.y = 'a')


问:
R: ggplot2 - Scaling a secondary 'year quarter' x date axis based on a primary 'month' x date axis
I would like to have two x axes. One of them (primary preferably) having year quarter and the second one having the months. I'm trying to do this, since my date observations are not uniform/sequential. i.e I can have only Jan in Q1, but the whole 3 months in Q2.

My attempt was to use scale_x_date having the date in the standard date format (as.Date()) and using date_labels and breaks.
For the secondary axis, I've used dup_axis and passed zoo::as.yearqtr.

```<code>library("zoo")
library("ggplot2")
set.seed(44)

## Creating a reproducible data-frame ##

df <- data.frame("id" = sample(1:100, 3, replace=TRUE),
                 "date" = c("2020-01-01","2020-02-01","2020-03-01",
                            "2020-04-01",
                            "2020-07-01","2020-09-01",
                            "2020-10-01","2020-11-01","2020-12-01")
                 )
## Plotting ##
df %>%
{
ggplot(data = ., aes(x = as.Date(date), y = id, group = 1)) +
  geom_line() +
  geom_point() +
  scale_x_date(date_labels = "%b", breaks = "1 month",
               sec.axis = dup_axis(name = "month", breaks = scales::date_breaks("3 month"),  labels = as.yearqtr)
               )
}

</code>```

Here is a plot image of my attempt:

The downsides I'm facing here:

The quarter is being plotted for the last 3rd month (i.e it will
match March), I'd like for it to match January instead.

Extras - Other low severity issues are:

All dates are plotted, I guess it's because I'm using
scale_x_date and we should use scale_x_discrete .. It would be
helpful if we wrote labels for only points that exist, otherwise I'm
okay for the viewer to match/interpret the points with his eyes.

This is the lowest severity, but I would like to pass arguments
    to function as.yearqtr so I can format quarter. i.e This will
    yield as.yearqtr(Sys.Date()) %>% format("%y Q%q") "20 Q2" instead
    of "2020 Q2"

答:
I've changed my attempt to another perspective, the solution is the following:

1- For the main issue, the solution is to use sec_axis instead of dup_axis.

Extras - Other low severity solutions are:

1- For plotting only existing observations, I've used unique(). This is listed in that SO thread link

2- From function as.yearqtr documentation, I can see format as a function parameter, but passing parameters didn't work, so I've used this workaround labels = function(x) format(as.yearqtr(x),"%y Q%q"). Thanks @Axeman for providing the syntax/way.

```<code>df %>%
{
ggplot(data = ., aes(x = as.Date(date), y = id, group = 1)) +
  geom_line() +
  geom_point() +
  scale_x_date(breaks = unique(as.Date(.$date)), date_labels = "%b",
               sec.axis = sec_axis(name = "quarter", trans = ~ ., labels = function(x) format(as.yearqtr(x),"%y Q%q"))
  ) +
  xlab("month")
}
</code>```

Solution plot result:

Body:
I would like to have two x axes. One of them (primary preferably) having year quarter and the second one having the months. I'm trying to do this, since my date observations are not uniform/sequential. i.e I can have only Jan in Q1, but the whole 3 months in Q2.

My attempt was to use scale_x_date having the date in the standard date format (as.Date()) and using date_labels and breaks.
For the secondary axis, I've used dup_axis and passed zoo::as.yearqtr.

library("zoo")
library("ggplot2")
set.seed(44)

## Creating a reproducible data-frame ##

df <- data.frame("id" = sample(1:100, 3, replace=TRUE),
                 "date" = c("2020-01-01","2020-02-01","2020-03-01",
                            "2020-04-01",
                            "2020-07-01","2020-09-01",
                            "2020-10-01","2020-11-01","2020-12-01")
                 )
## Plotting ##
df %>%
{
ggplot(data = ., aes(x = as.Date(date), y = id, group = 1)) +
  geom_line() +
  geom_point() +
  scale_x_date(date_labels = "%b", breaks = "1 month",
               sec.axis = dup_axis(name = "month", breaks = scales::date_breaks("3 month"),  labels = as.yearqtr)
               )
}

Here is a plot image of my attempt:

The downsides I'm facing here:

The quarter is being plotted for the last 3rd month (i.e it will
match March), I'd like for it to match January instead.

Extras - Other low severity issues are:

All dates are plotted, I guess it's because I'm using
scale_x_date and we should use scale_x_discrete .. It would be
helpful if we wrote labels for only points that exist, otherwise I'm
okay for the viewer to match/interpret the points with his eyes.

This is the lowest severity, but I would like to pass arguments
    to function as.yearqtr so I can format quarter. i.e This will
    yield as.yearqtr(Sys.Date()) %>% format("%y Q%q") "20 Q2" instead
    of "2020 Q2"

Body:
I've changed my attempt to another perspective, the solution is the following:

1- For the main issue, the solution is to use sec_axis instead of dup_axis.

Extras - Other low severity solutions are:

1- For plotting only existing observations, I've used unique(). This is listed in that SO thread link

2- From function as.yearqtr documentation, I can see format as a function parameter, but passing parameters didn't work, so I've used this workaround labels = function(x) format(as.yearqtr(x),"%y Q%q"). Thanks @Axeman for providing the syntax/way.

df %>%
{
ggplot(data = ., aes(x = as.Date(date), y = id, group = 1)) +
  geom_line() +
  geom_point() +
  scale_x_date(breaks = unique(as.Date(.$date)), date_labels = "%b",
               sec.axis = sec_axis(name = "quarter", trans = ~ ., labels = function(x) format(as.yearqtr(x),"%y Q%q"))
  ) +
  xlab("month")
}

Solution plot result:


问:
Running an application with WebRTC within a local network that doesn't have internet access
I'm looking to use WebRTC in a project where I need to livestream video from one computer, a robot with a wifi hotspot and USB camera, over a local network to another computer, a controller for the robot. Both computers in this case are single board computers and the video stream is one-way. I'd also like the two computers to communicate data to each other in both directions. I found WebRTC in my research and it seems to have both of these functionalities that I'm looking for.

From initial testing with the demo NodeJS programs, WebRTC seems to be almost exactly what I'm looking for. One big bump I've been trying to get over though is that it seems to require by default an online signaling server to be used between the two clients. I researched and found that it's possible to create the signaling server within the local network with a third computer, but such a setup isn't appropriate for my project.

I've looked into other solutions and came across OpenVidu which implements WebRTC but allows the signaling server to be built into one of the client computers (at least that's what I've read in another stack overflow post). I have yet to test this tool to see if it resolves my issue, but I'm blocked currently by the docker image used by the project not supporting ARM processors, which are employed by my single board computers, and thus requiring special installation.

Before I go through that process which may or may not work, I wanted to ask if there's another simpler solution to running WebRTC without internet access and without needing a third computer as a signaling server or if there were any suggestions for tools other than WebRTC that would be better for my application. I'm very new to the technology and could definitely be missing an easy or existing solution. Any help on this matter would be greatly appreciated.

For those curious, the single board computers being used are NVidia Jetson Nanos.

答:
Found the solution. Using the Google Codelabs example, the fix involved just removing the default ice server in the config. Essentially, it meant changing

```<code>const config = {
  iceServers: [
    {urls: ["stun:stun.l.google.com:19302"]}
  ]
}
</code>```

to

```<code>const config = {
  iceServers: []
}
</code>```

Body:
Found the solution. Using the Google Codelabs example, the fix involved just removing the default ice server in the config. Essentially, it meant changing

const config = {
  iceServers: [
    {urls: ["stun:stun.l.google.com:19302"]}
  ]
}

to

const config = {
  iceServers: []
}


问:
jquery how to figure out what the JSON Object contains
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

```<code>$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});
</code>```

If I do this - I get an object, but I don't know what it contains.

答:
Since groups_url is returning json, you could just point your browser to that url and check out the response.

You can also use firebug or the dev console in chrome. Simply go to the network tab and you should see the ajax requests listed there along with the relevant headers and response.

Body:
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});

If I do this - I get an object, but I don't know what it contains.


问:
Is this implementation of malloc a bump allocator?
I recently wrote a small malloc and was wondering if it was a bump allocator. I wonder this because (correct me if I am wrong) I believe the actual malloc (while using mmap instead of sbrk) uses the same technique (sort of), but a bump allocator just increments the heap location. Here is my code:

#include <cstdio>
#include <cstddef>
#include <unistd.h>

#define word_size sizeof(intptr_t)
#define align(n) ((n + word_size - 1) & ~(word_size - 1))

void* my_malloc(size_t size) {
    void* p = sbrk(0);
    if (sbrk(align(size)) == (void*) -1)
        return NULL; // failed
    return p;
}

int main() {
    int* foo = (int*) my_malloc(1);
    *foo = 100;
    printf("%d\n", *foo);
}
```

答:
So I had never heard the term "bump allocator" before, but the concept is straightforward.

It's a really naive allocator that can be very fast due to the tiny amount of housekeeping involved, but you have to live with a pretty heavy constraint: there's no "free" operation for individual request - you just destroy the whole thing.

In your case, you're calling sbrk(0) to get the first address at the end of the program's whole data segment - this will be the return value - then "bump" the end of memory with sbrk(nbytes) after suitably rounding it up.

This means that the program's data space just grows up for each request, and trying to free something doesn't make any sense because you can't just put a hole in the address space (well, there's probably some funky VM stuff that would work, but that gets complicated).

```<code>static void *bump_arena_start = 0;

void* my_malloc(size_t size) {
    void* p = sbrk(0);

    if (bump_arena_start == 0) bump_arena_start = p;

    if (sbrk(align(size)) == (void*) -1)
        return NULL; // failed
    return p;
}

void destroy_bump_arena(void)
{
    if (bump_arena_start) brk(bump_arena_start);
}
</code>```

This would probably be a bump allocator, but it would be a terrible one for a bunch of reasons.

First: it assumes that nobody else is allocating memory, it would have to override all other operations: malloc, C++ new, everything in the C runtime, etc.

Imagine what would happen if you're doing your own thing with the break, and then some other function calls sbrk() to allocate some memory. Now they are in the middle of your arena but you mostly don't know it.  So far no problem, but as soon as you go to destroy your arena, it kills everything else.

The way you'd actually use such a thing is when you have a lot of tiny allocations that you don't want to keep track of and can release all at once, so you might use the system allocator (malloc()) and ask for a large-enough chunk to handle your needs - let's call it 32kbytes - and stuff this into some object representing this bump arena.

You allocate lots of little bits here and there, do whatever task you need to do, then destroy all of it by freeing that initial 32-kbyte chunk.

The thing is: you have to be super careful that you don't let one of these pointers escape to other parts of the system, because they aren't allowed to live beyond the lifetime of your arena.

This is just a really specialized use case that's probably not generally useful, and unless you're doing embedded work (where you are essentially controlling your own runtime), you couldn't really do one with the system break this way.

Side note: you can get into trouble with alignment if you have objects larger than the size of an integer pointer. What if you did this?

```<code>   int      *foo1 = my_malloc(sizeof(int));       // 8 bytes (usually)
   __int128 *foo2 = my_malloc(sizeof(__int128));  // 16 bytes
</code>```

The naive alignment would put the int on an 8-byte boundary, but so would the 128-bit value (which is 16 bytes), not aligned to its own size; on some platforms that's probably an error, and it's almost always inefficient.

To do it right you'd query the current next-value via sbrk(0) and insure it was aligned properly for the size, possibly bumping up the break a bit.

EDIT: I have looked into this a bit more, and it's pretty clear that your example doesn't quite count as a bump allocator. Here's why.

The memory system not only keeps track of the "next" pointer, but how many allocations have been performed, and it supports a pseudo-free operation that ignores the pointer value but just decrements the allocation counter.

If the allocation counter ever reaches zero, this means nobody else has any of that memory, so it can free everything by rewinding the break to the initial value, essentially starting over with a clean slate.

To use this properly you'd have to really be careful about your deallocations, and a double-free could be very painful.

Really useful reference: https://os.phil-opp.com/allocator-designs/

EDIT2 - a bit more about alignment per request.

You have to have at least some awareness of alignment no matter what platform you're on, because even if the platform allows unaligned access to memory, it's almost always slower.

The super easy way to always get it right is to figure out the largest possible scalar object supported on the platform, and use that as your alignment modulo, perhaps __int128. If you're always rounding up to the nearest 16 bytes, you'll pretty much never run into an alignment issue (plus it's easy).

But it's also space-inefficient: if you're allocating space for a two-byte short, it will waste the 14 bytes after it. That might be no big deal in your application, or it might be a thing.

I have never written a memory allocator myself, so I'm doing a lot of handwaving here, but anybody using a bump allocator has some specialized requirements and is probably OK with making specialized requests.

So: I could imagine an allocator that takes not just the size, but also the alignment required, and it would take the sbrk(0) pointer and round that up the required alignment, save that as the return value, then call sbrk(size) to bump the end marker.

Note that you're not aligning to the size of the allocation, but only the size of the low-level item: asking for an array of 20 short values means you're asking for 40 bytes but with an alignment of 2, and 100 bytes for a string means you just take the next 100 bytes w/o any alignment.

```<code>void *my_malloc(size_t nbytes, size_t align = 8)
{
    void *p = sbrk(0);
    p += round up but too hard to think on Friday
    sbrk(nbytes);
    num_allocations++;
    return p;
}
</code>```

This way, if you don't give an alignment size, it makes the same safe assumption you did, but you could always ask if you wanted to be special.

Again: I'm mostly just making this up, I've never had to think about it this way, but I do know that if I'm working on a memory-constrained platform such as an Arduino with RAM measured in kilobytes, you have to think about this.

Body:
So I had never heard the term "bump allocator" before, but the concept is straightforward.

It's a really naive allocator that can be very fast due to the tiny amount of housekeeping involved, but you have to live with a pretty heavy constraint: there's no "free" operation for individual request - you just destroy the whole thing.

In your case, you're calling sbrk(0) to get the first address at the end of the program's whole data segment - this will be the return value - then "bump" the end of memory with sbrk(nbytes) after suitably rounding it up.

This means that the program's data space just grows up for each request, and trying to free something doesn't make any sense because you can't just put a hole in the address space (well, there's probably some funky VM stuff that would work, but that gets complicated).

static void *bump_arena_start = 0;

void* my_malloc(size_t size) {
    void* p = sbrk(0);

    if (bump_arena_start == 0) bump_arena_start = p;

    if (sbrk(align(size)) == (void*) -1)
        return NULL; // failed
    return p;
}

void destroy_bump_arena(void)
{
    if (bump_arena_start) brk(bump_arena_start);
}

This would probably be a bump allocator, but it would be a terrible one for a bunch of reasons.

First: it assumes that nobody else is allocating memory, it would have to override all other operations: malloc, C++ new, everything in the C runtime, etc.

Imagine what would happen if you're doing your own thing with the break, and then some other function calls sbrk() to allocate some memory. Now they are in the middle of your arena but you mostly don't know it.  So far no problem, but as soon as you go to destroy your arena, it kills everything else.

The way you'd actually use such a thing is when you have a lot of tiny allocations that you don't want to keep track of and can release all at once, so you might use the system allocator (malloc()) and ask for a large-enough chunk to handle your needs - let's call it 32kbytes - and stuff this into some object representing this bump arena.

You allocate lots of little bits here and there, do whatever task you need to do, then destroy all of it by freeing that initial 32-kbyte chunk.

The thing is: you have to be super careful that you don't let one of these pointers escape to other parts of the system, because they aren't allowed to live beyond the lifetime of your arena.

This is just a really specialized use case that's probably not generally useful, and unless you're doing embedded work (where you are essentially controlling your own runtime), you couldn't really do one with the system break this way.

Side note: you can get into trouble with alignment if you have objects larger than the size of an integer pointer. What if you did this?

   int      *foo1 = my_malloc(sizeof(int));       // 8 bytes (usually)
   __int128 *foo2 = my_malloc(sizeof(__int128));  // 16 bytes

The naive alignment would put the int on an 8-byte boundary, but so would the 128-bit value (which is 16 bytes), not aligned to its own size; on some platforms that's probably an error, and it's almost always inefficient.

To do it right you'd query the current next-value via sbrk(0) and insure it was aligned properly for the size, possibly bumping up the break a bit.

EDIT: I have looked into this a bit more, and it's pretty clear that your example doesn't quite count as a bump allocator. Here's why.

The memory system not only keeps track of the "next" pointer, but how many allocations have been performed, and it supports a pseudo-free operation that ignores the pointer value but just decrements the allocation counter.

If the allocation counter ever reaches zero, this means nobody else has any of that memory, so it can free everything by rewinding the break to the initial value, essentially starting over with a clean slate.

To use this properly you'd have to really be careful about your deallocations, and a double-free could be very painful.

Really useful reference: https://os.phil-opp.com/allocator-designs/

EDIT2 - a bit more about alignment per request.

You have to have at least some awareness of alignment no matter what platform you're on, because even if the platform allows unaligned access to memory, it's almost always slower.

The super easy way to always get it right is to figure out the largest possible scalar object supported on the platform, and use that as your alignment modulo, perhaps __int128. If you're always rounding up to the nearest 16 bytes, you'll pretty much never run into an alignment issue (plus it's easy).

But it's also space-inefficient: if you're allocating space for a two-byte short, it will waste the 14 bytes after it. That might be no big deal in your application, or it might be a thing.

I have never written a memory allocator myself, so I'm doing a lot of handwaving here, but anybody using a bump allocator has some specialized requirements and is probably OK with making specialized requests.

So: I could imagine an allocator that takes not just the size, but also the alignment required, and it would take the sbrk(0) pointer and round that up the required alignment, save that as the return value, then call sbrk(size) to bump the end marker.

Note that you're not aligning to the size of the allocation, but only the size of the low-level item: asking for an array of 20 short values means you're asking for 40 bytes but with an alignment of 2, and 100 bytes for a string means you just take the next 100 bytes w/o any alignment.

void *my_malloc(size_t nbytes, size_t align = 8)
{
    void *p = sbrk(0);
    p += round up but too hard to think on Friday
    sbrk(nbytes);
    num_allocations++;
    return p;
}

This way, if you don't give an alignment size, it makes the same safe assumption you did, but you could always ask if you wanted to be special.

Again: I'm mostly just making this up, I've never had to think about it this way, but I do know that if I'm working on a memory-constrained platform such as an Arduino with RAM measured in kilobytes, you have to think about this.


问:
Flutter unit testing - unable to pump full widget tree
I am just getting started with unit testing in Flutter, and I have hit a bit of a wall. I have a fairly simple app located here:
https://github.com/chuckntaylor/kwjs_flutter_demo

The app is essentially a list view of events where you can tap on one to read more details about the event.

I have two screens for this: events_screen.dart for the list view, and event_screen.dart for the details. I have been trying to write my tests in events_screen_test.dart

My testing difficulties are with the events screen (the list view). After running await tester.pumpWidget(MaterialApp(home: EventsScreen()) I can use find.text('Events') for example to find the title in the AppBar, but I cannot find any of the elements that make up the list.

To clarify further. I am using get_it as a serviceLocator to get the viewModel for the EventsScreen when it loads. The viewModel is the ChangeNotifierProvider, and EventsScreen contains a Consumer to update the list. in EventsScreen initState(), it calls loadEvents() on the viewModel. After loadEvents() is done, the viewModel calls notifyListeners(), so that EventsScreen can update.

How do I ensure that all these steps occur so that I can properly test if the EventsScreen is rendering properly?

I could be approaching this all wrong, so any advice is appreciated.

答:
I have solved my problem, but perhaps someone can shed some light on this. In the end I executed:

```<code>await tester.pumpWidget(MaterialApp(home: EventsScreen(),));
// followed immediately by this second pump without arguments
await tester.pump();
</code>```

At this point,  the Widget tree was complete and I could create Finders as I hoped and could run all my expect statements without issue.

I am not sure exactly why this works though.

Body:
I have solved my problem, but perhaps someone can shed some light on this. In the end I executed:

await tester.pumpWidget(MaterialApp(home: EventsScreen(),));
// followed immediately by this second pump without arguments
await tester.pump();

At this point,  the Widget tree was complete and I could create Finders as I hoped and could run all my expect statements without issue.

I am not sure exactly why this works though.


问:
Issue getting credential spec (gMSA) working in docker-compose
I have a gMSA credential spec working with docker run but not with docker-compose. Details for the compose file and the docker run command are below. I'm completely lost as to what I'm missing. I did a lot of googling and I'm not sure what's going on. My primary thoughts is that something with the docker-compose file is off, but I'm not sure.

Docker-compose

```<code>version: '3.3'

services:
  basic:
    image: mcr.microsoft.com/windows/servercore:ltsc2019
    entrypoint: ping -t localhost
    hostname: server01
    security_opt:
      - credentialspec=file://server01.json
    dns:
      - "192.168.43.2"
    user: "NT AUTHORITY\\NETWORK SERVICE"

networks:
  default:
    external:
      name: "Net"
</code>```

After running docker-compose up

```<code>C:\Users\administrator> docker exec -it b9e2a783ab09 powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\> ipconfig

Windows IP Configuration

Ethernet adapter vEthernet (Ethernet) 10:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::4416:3381:8d1a:122a%43
   Autoconfiguration IPv4 Address. . : 169.254.18.42
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :
PS C:\> ipconfig /renew

Windows IP Configuration

Ethernet adapter vEthernet (Ethernet) 10:

   Connection-specific DNS Suffix  . : localdomain
   Link-local IPv6 Address . . . . . : fe80::4416:3381:8d1a:122a%43
   IPv4 Address. . . . . . . . . . . : 192.168.43.198
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
PS C:\> nslookup testdomain.local
Server:  UnKnown
Address:  192.168.43.2

Name:    testdomain.local
Addresses:  192.168.43.2
          192.168.52.133

PS C:\> nltest /sc_verify:testdomain.local
I_NetLogonControl failed: Status = 5 0x5 ERROR_ACCESS_DENIED
</code>```

docker run

```<code>docker run -it --security-opt "credentialspec=file://server01.json" --user="nt authority\system" --hostname="server01" --network="Net" --dns="192.168.43.2" mcr.microsoft.com/windows/servercore:ltsc2019 powershell
</code>```

```<code>PS C:\> nslookup testdomain.local
Server:  UnKnown
Address:  192.168.43.2

Name:    testdomain.local
Addresses:  192.168.43.2
          192.168.52.133

PS C:\> nltest /sc_verify:testdomain.local
Flags: b0 HAS_IP  HAS_TIMESERV
Trusted DC Name \\dc01.testdomain.local
Trusted DC Connection Status Status = 0 0x0 NERR_Success
Trust Verification Status = 0 0x0 NERR_Success
The command completed successfully
PS C:\>
</code>```

答:
Hey so I'm leaving this up as a mark of shame.

Notice that I used different users? Turns out I needed to use system and not the network service account. That fixed it.

Body:
I have a gMSA credential spec working with docker run but not with docker-compose. Details for the compose file and the docker run command are below. I'm completely lost as to what I'm missing. I did a lot of googling and I'm not sure what's going on. My primary thoughts is that something with the docker-compose file is off, but I'm not sure.

Docker-compose

version: '3.3'

services:
  basic:
    image: mcr.microsoft.com/windows/servercore:ltsc2019
    entrypoint: ping -t localhost
    hostname: server01
    security_opt:
      - credentialspec=file://server01.json
    dns:
      - "192.168.43.2"
    user: "NT AUTHORITY\\NETWORK SERVICE"

networks:
  default:
    external:
      name: "Net"

After running docker-compose up

C:\Users\administrator> docker exec -it b9e2a783ab09 powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\> ipconfig

Windows IP Configuration

Ethernet adapter vEthernet (Ethernet) 10:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::4416:3381:8d1a:122a%43
   Autoconfiguration IPv4 Address. . : 169.254.18.42
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :
PS C:\> ipconfig /renew

Windows IP Configuration

Ethernet adapter vEthernet (Ethernet) 10:

   Connection-specific DNS Suffix  . : localdomain
   Link-local IPv6 Address . . . . . : fe80::4416:3381:8d1a:122a%43
   IPv4 Address. . . . . . . . . . . : 192.168.43.198
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
PS C:\> nslookup testdomain.local
Server:  UnKnown
Address:  192.168.43.2

Name:    testdomain.local
Addresses:  192.168.43.2
          192.168.52.133

PS C:\> nltest /sc_verify:testdomain.local
I_NetLogonControl failed: Status = 5 0x5 ERROR_ACCESS_DENIED

docker run

docker run -it --security-opt "credentialspec=file://server01.json" --user="nt authority\system" --hostname="server01" --network="Net" --dns="192.168.43.2" mcr.microsoft.com/windows/servercore:ltsc2019 powershell

PS C:\> nslookup testdomain.local
Server:  UnKnown
Address:  192.168.43.2

Name:    testdomain.local
Addresses:  192.168.43.2
          192.168.52.133

PS C:\> nltest /sc_verify:testdomain.local
Flags: b0 HAS_IP  HAS_TIMESERV
Trusted DC Name \\dc01.testdomain.local
Trusted DC Connection Status Status = 0 0x0 NERR_Success
Trust Verification Status = 0 0x0 NERR_Success
The command completed successfully
PS C:\>


问:
Listener to innerHTML
I have 5x countdown and i want to click the image below if the timer is "00:00".
Now i have it like the code below but i must refresh the page everytime to click. Is there something like eventlistener for innerhtml. I solved it with timer which checks the innerhtml but i dont want to use a timer.

```<code>  var ct1 = document.querySelector("#countdown1 > span").innerText
  if (ct1 == "00:00") { document.querySelector("#farmimage_1").click(); }

  var ct2 = document.querySelector("#countdown2 > span").innerText
  if (ct2 == "00:00") { document.querySelector("#farmimage_2").click(); }

  var ct3 = document.querySelector("#countdown3 > span").innerText
  if (ct3 == "00:00") { document.querySelector("#farmimage_3").click(); }

  var ct4 = document.querySelector("#countdown4 > span").innerText
  if (ct4 == "00:00") { document.querySelector("#farmimage_4").click(); }

  var ct5 = document.querySelector("#countdown5 > span").innerText
  if (ct5 == "00:00") { document.querySelector("#farmimage_5").click(); }

</code>```

答:
The MutationObserver interface can do the trick:

function toggle() {
  let div = document.getElementById('d0');
  div.textContent = div.textContent == 'foo'? 'bar':'foo';
}

window.onload = function(){

  document.getElementById('b0').addEventListener('click', toggle, false);

  let div = document.getElementById('d0');
  let observer = new MutationObserver(function() {
    console.log('textContent changed to ' + div.textContent);
  });
  observer.observe(div, {childList: true});

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="d0">foo</div>
<button id="b0">Toggle foo/bar</button></code>```

Using with a timer:

// Simple countdown
function timer(){
  let div = document.getElementById('timer');
  let time = div.textContent;
  let intervalID = setInterval(() => {
    div.textContent = --time;
    if (time == 0) clearInterval(intervalID);
  }, 1000);
}

window.onload = function() {

  // Create observer
  let div = document.getElementById('timer');
  let observer = new MutationObserver(function() {
    if (div.textContent == '0') {
      console.log('Zero!!');
    }
  });
  // Start observing
  observer.observe(div, {
    childList: true
  });
  // Start timer
  timer();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="timer">5</div></code>```

Title: Listener to innerHTML

Body:
I have 5x countdown and i want to click the image below if the timer is "00:00".
Now i have it like the code below but i must refresh the page everytime to click. Is there something like eventlistener for innerhtml. I solved it with timer which checks the innerhtml but i dont want to use a timer.

  var ct1 = document.querySelector("#countdown1 > span").innerText
  if (ct1 == "00:00") { document.querySelector("#farmimage_1").click(); }

  var ct2 = document.querySelector("#countdown2 > span").innerText
  if (ct2 == "00:00") { document.querySelector("#farmimage_2").click(); }

  var ct3 = document.querySelector("#countdown3 > span").innerText
  if (ct3 == "00:00") { document.querySelector("#farmimage_3").click(); }

  var ct4 = document.querySelector("#countdown4 > span").innerText
  if (ct4 == "00:00") { document.querySelector("#farmimage_4").click(); }

  var ct5 = document.querySelector("#countdown5 > span").innerText
  if (ct5 == "00:00") { document.querySelector("#farmimage_5").click(); }

Body:
The MutationObserver interface can do the trick:

function toggle() {
  let div = document.getElementById('d0');
  div.textContent = div.textContent == 'foo'? 'bar':'foo';
}

window.onload = function(){

  document.getElementById('b0').addEventListener('click', toggle, false);

  let div = document.getElementById('d0');
  let observer = new MutationObserver(function() {
    console.log('textContent changed to ' + div.textContent);
  });
  observer.observe(div, {childList: true});

}

<div id="d0">foo</div>
<button id="b0">Toggle foo/bar</button>

Using with a timer:

// Simple countdown
function timer(){
  let div = document.getElementById('timer');
  let time = div.textContent;
  let intervalID = setInterval(() => {
    div.textContent = --time;
    if (time == 0) clearInterval(intervalID);
  }, 1000);
}

window.onload = function() {

  // Create observer
  let div = document.getElementById('timer');
  let observer = new MutationObserver(function() {
    if (div.textContent == '0') {
      console.log('Zero!!');
    }
  });
  // Start observing
  observer.observe(div, {
    childList: true
  });
  // Start timer
  timer();
};

<div id="timer">5</div>


问:
How do I identify if a runc container is running as privileged?
Regardless of docker/crio/containerd starting the container, is there a way to understand if the runc container is running as privileged one?

docker inspect does show privilegedness but I want to find out at the runc layer.

答:
The state and the configuration of every runc container may be obtained from the $ROOT_DIR/$CONTAINER_ID/state.json file, where $ROOT_DIR is a root directory for a group of containers (usually managed by a specific higher-level runtime like Docker). For example, on my machine Docker uses the root dir /run/docker/runtime-runc/moby, thus, I can find the runc-level configuration of some container as follows:

# jq .config /run/docker/runtime-runc/moby/$CONTAINER_ID/state.json
{
  "no_pivot_root": false,
  "parent_death_signal": 0,
  "rootfs": "/var/lib/docker/overlay2/<CONTAINER_ID>/merged",
  "readonlyfs": false,
...
}
```

You can easily find out that this file does not contain fields like privileged. A quick search through runc source code shows that it does not have a notion of a privileged container, i.e. this is an abstraction from the higher levels. This means, in turn, that there is no simple way to determine, whether the container was started as a privileged one or not, from the runc level.

However, it is still possible to say whether the container has the same privileges as those which are granted by --privileged argument at the Docker level: the state.json file contains a list of capabilities, granted to the container; a list of device nodes, available to the container; seccomp mode and so on. From practical standpoint, it is unwise to waste your time on checking all these settings, so it is better just to look at docker inspect.

Body:
The state and the configuration of every runc container may be obtained from the $ROOT_DIR/$CONTAINER_ID/state.json file, where $ROOT_DIR is a root directory for a group of containers (usually managed by a specific higher-level runtime like Docker). For example, on my machine Docker uses the root dir /run/docker/runtime-runc/moby, thus, I can find the runc-level configuration of some container as follows:

# jq .config /run/docker/runtime-runc/moby/$CONTAINER_ID/state.json
{
  "no_pivot_root": false,
  "parent_death_signal": 0,
  "rootfs": "/var/lib/docker/overlay2/<CONTAINER_ID>/merged",
  "readonlyfs": false,
...
}

You can easily find out that this file does not contain fields like privileged. A quick search through runc source code shows that it does not have a notion of a privileged container, i.e. this is an abstraction from the higher levels. This means, in turn, that there is no simple way to determine, whether the container was started as a privileged one or not, from the runc level.

However, it is still possible to say whether the container has the same privileges as those which are granted by --privileged argument at the Docker level: the state.json file contains a list of capabilities, granted to the container; a list of device nodes, available to the container; seccomp mode and so on. From practical standpoint, it is unwise to waste your time on checking all these settings, so it is better just to look at docker inspect.