问:
React render component only for few seconds
In my existing react component, I need to render another react component for a specific time period.
As soon as the parent component mounts/or data loads, the new-component (or child component) should be visible after 1-2 seconds and then after another few seconds, the new-component should be hidden. This needs to be done only if there is no data available.

This is what currently I've tried to achieve:

```<code>import React, { useState, useEffect } from "react";

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const sampleData = [];

  useEffect(() => {
    if (sampleData.length === 0) {
      setTimeout(() => {
        setShowComponent(true);
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    setTimeout(() => {
      setShowComponent(false);
    }, 4000);
  }, []);

  const componentTwo = () => {
    return <h2>found error</h2>;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;
</code>```

The current implementation is not working as expected. The new-component renders in a blink fashion.

Here is the working snippet attached:

Any help to resolve this is appreciated!

答:
I have modified the code to work, hope this how you are expecting it to work.

```<code>import React, { useState, useEffect } from "react";

const sampleData = [];
// this has to be out side or passed as a prop
/*
reason: when the component render (caued when calling setShowComponent)
a new reference is created for "sampleData", this cause the useEffect run every time the component re-renders,
 resulting "<h2>found error</h2>" to flicker.
*/

function App() {
  const [showComponent, setShowComponent] = useState(false);

  useEffect(() => {
    if (sampleData.length === 0) {
      const toRef = setTimeout(() => {
        setShowComponent(true);
        clearTimeout(toRef);
        // it is good practice to clear the timeout (but I am not sure why)
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    if (showComponent) {
      const toRef = setTimeout(() => {
        setShowComponent(false);
        clearTimeout(toRef);
      }, 4000);
    }
  }, [showComponent]);

  const componentTwo = () => {
    return <h2>found error</h2>;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;
</code>```

Body:
In my existing react component, I need to render another react component for a specific time period.
As soon as the parent component mounts/or data loads, the new-component (or child component) should be visible after 1-2 seconds and then after another few seconds, the new-component should be hidden. This needs to be done only if there is no data available.

This is what currently I've tried to achieve:

import React, { useState, useEffect } from "react";

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const sampleData = [];

  useEffect(() => {
    if (sampleData.length === 0) {
      setTimeout(() => {
        setShowComponent(true);
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    setTimeout(() => {
      setShowComponent(false);
    }, 4000);
  }, []);

  const componentTwo = () => {
    return
found error
;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;

The current implementation is not working as expected. The new-component renders in a blink fashion.

Here is the working snippet attached:

Any help to resolve this is appreciated!

Body:
I have modified the code to work, hope this how you are expecting it to work.

import React, { useState, useEffect } from "react";

const sampleData = [];
// this has to be out side or passed as a prop
/*
reason: when the component render (caued when calling setShowComponent)
a new reference is created for "sampleData", this cause the useEffect run every time the component re-renders,
 resulting "<h2>found error</h2>" to flicker.
*/

function App() {
  const [showComponent, setShowComponent] = useState(false);

  useEffect(() => {
    if (sampleData.length === 0) {
      const toRef = setTimeout(() => {
        setShowComponent(true);
        clearTimeout(toRef);
        // it is good practice to clear the timeout (but I am not sure why)
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    if (showComponent) {
      const toRef = setTimeout(() => {
        setShowComponent(false);
        clearTimeout(toRef);
      }, 4000);
    }
  }, [showComponent]);

  const componentTwo = () => {
    return <h2>found error</h2>;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;


来源: stackexchange

问:
How to access the files in bin/debug within the project folder in Visual studio 2010?
I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

```<code> WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();
</code>```

Please Guide me to put correct valid path to access docx.xsl file...

答:
If you add the file as resource you don't need to deal with paths at runtime.

Add the file to the visual studio project and set the build action to "Embedded Resource".

The name of the resource is the project default namespace + any folders just like any code file in the project.

```<code>string resourceName = "DefaultNamespace.Folder.docx.xsl";
</code>```

If you have the code in the same folder you can do like this

```<code>string resourceName = string.Format("{0}.docx.xsl", this.GetType().Namespace);
</code>```

Then you read the file using a resource stream Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)

In your case, it would look like this:

```<code>using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var reader = XmlReader.Create(stream))
    xslt.Load(reader);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

 WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();

Please Guide me to put correct valid path to access docx.xsl file...

Body:
If you add the file as resource you don't need to deal with paths at runtime.

Add the file to the visual studio project and set the build action to "Embedded Resource".

The name of the resource is the project default namespace + any folders just like any code file in the project.

string resourceName = "DefaultNamespace.Folder.docx.xsl";

If you have the code in the same folder you can do like this

string resourceName = string.Format("{0}.docx.xsl", this.GetType().Namespace);

Then you read the file using a resource stream Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)

In your case, it would look like this:

using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var reader = XmlReader.Create(stream))
    xslt.Load(reader);


问:
Using .forEach() after checking if variable is Array type
I have a generic functional component in which I got the following code:

```<code>if(Array.isArray(entry[key as keyof T]) {
    entry[key as keyof T].forEach((item: T) => { ... });
}
</code>```

Where key is a variable string. The .forEach is red underlined with the following error message:

```<code>Property 'forEach' does not exist on type 'T[keyof T]'
</code>```

even though I checked if the value is an array in the conditional statement. How do I work around this?

答:
I'd suggest making it a bit easier for TS:

```<code>const value = entry[key as keyof T]
if (Array.isArray(value)) {
  value.forEach((item: T) => {});
}

</code>```

Edit: Is your entry some kind of recursive structure? Otherwise the typing looks a little odd. Maybe you'd like to share a little bit more of your code/intention.

Edit 2: Playground sample https://www.typescriptlang.org/play?#code/DwFQBApgHgLhB2ATAzmA3gXwHwAoEwCcBPALjBAEowBeLdAKDDAGMB7eZGMAawiJrAByQfUYt2nMADcAhgBsArhAH5iAbV78ZqTawBm5ALpiAlgZwBBAgRlEAdCeRWbRHLMUQKVNGKbuldnqsBACiMswAFjg4JnAAtmSUNHSYFADcYhj0WUA

ContentLicense: CC BY-SA 4.0

Body:
I have a generic functional component in which I got the following code:

if(Array.isArray(entry[key as keyof T]) {
    entry[key as keyof T].forEach((item: T) => { ... });
}

Where key is a variable string. The .forEach is red underlined with the following error message:

Property 'forEach' does not exist on type 'T[keyof T]'

even though I checked if the value is an array in the conditional statement. How do I work around this?

Body:
I'd suggest making it a bit easier for TS:

const value = entry[key as keyof T]
if (Array.isArray(value)) {
  value.forEach((item: T) => {});
}

Edit: Is your entry some kind of recursive structure? Otherwise the typing looks a little odd. Maybe you'd like to share a little bit more of your code/intention.

Edit 2: Playground sample https://www.typescriptlang.org/play?#code/DwFQBApgHgLhB2ATAzmA3gXwHwAoEwCcBPALjBAEowBeLdAKDDAGMB7eZGMAawiJrAByQfUYt2nMADcAhgBsArhAH5iAbV78ZqTawBm5ALpiAlgZwBBAgRlEAdCeRWbRHLMUQKVNGKbuldnqsBACiMswAFjg4JnAAtmSUNHSYFADcYhj0WUA


答:
The static arrays contain definitions, so they need to be in a .c file.

If you put them in .h files, different translation units will define the same constants.

In your case, data is static, so by no means it will be in a .h file.  It is not linked with anything externally, so no need to declare it in a header file.

If the static data is generated by some other program in a file "data", you can do so:

file.c:

```<code>static float coeffs[257][4][8][2] =
{
#include "data"
}
</code>```

and generate "data" as a valid C-input.

Title: Move large static array into a separate file: .c or .h?

Body:
I've got a large pre-calculated 4D array written in C:

static float coeffs[257][4][8][2] =
{
 {
  { { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, -0.000000000000000f }, { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f }, { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f },  },
  { { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f }, { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f }, { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, -0.000000000000000f },  },
  { { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f }, { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f },  },
  { { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f }, { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f }, { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f },  },
  },

 .
 .
 .
 },
}

It's about 1500 lines, so I would like to move it into a separate file.

The array should be static as it is used only in a single C file.

The question is, should such static arrays be moved into a header file and then included as #include "coeffs.h", or should they be a separate C file included as #include "coeffs.c"? Does it matter?

Body:
The static arrays contain definitions, so they need to be in a .c file.

If you put them in .h files, different translation units will define the same constants.

In your case, data is static, so by no means it will be in a .h file.  It is not linked with anything externally, so no need to declare it in a header file.

If the static data is generated by some other program in a file "data", you can do so:

file.c:

static float coeffs[257][4][8][2] =
{
#include "data"
}

and generate "data" as a valid C-input.


问:
Xcode 11.4 compile error 'Missing package product <package name>'
When I integrate a local package in my Xcode project everything is fine initially but when i switch branches and want to run the app Xcode gives me the compile error Missing package product <package name>. When I quit Xcode and re-open it everything is fine again. Any idea what this can be? An Xcode bug?

We also integrate external packages via Swift Package Manager which works perfectly fine. No issues there.

The issue is also well described in a post by Jesse Squires.

答: Just a silly question: did you set up your git account on Xcode preferences?


问:
need help regex remove first br tag
I want to convert this string

```<code><br>
<br class="MsoNormal" align="justify" style="MARGIN: 0cm 0cm 0pt">
<br class="MsoNormal" align="justify" style="MARGIN: 0cm 0cm 0pt">
<br>
<br>
<br class="MsoNormal" align="justify" style="MARGIN: 0cm 0cm 0pt">
Content here
</code>```

become

```<code>Content here
</code>```

How to do it with regex ?

答:
To match a tag, you can use <[^>]+>, then you can use a replacement method for each matched tag, according to the language you're using.

EDIT:

With php use:

```<code>$nohtml = preg_replace("/<[^>]+>/", "", $html);
</code>```

where $html is a string containing the code you want html free.

Title: need help regex remove first br tag

Body:
I want to convert this string

Content here

become

Content here

How to do it with regex ?

Body:
To match a tag, you can use <[^>]+>, then you can use a replacement method for each matched tag, according to the language you're using.

EDIT:

With php use:

$nohtml = preg_replace("/<[^>]+>/", "", $html);

where $html is a string containing the code you want html free.


问:
Unable to install PHP 7.4 on Ubuntu 16.04 even with Ondrej PPA repository in apache2
I am  trying to install PHP 7.4 on Ubuntu 16.04 for Apache2 server. To install the 7.4 version, I used PPA ondrej repository as follows:

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install -y php7.4
php -v
```
<p>I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.4
E: Couldn't find any package by glob 'php7.4'
E: Couldn't find any package by regex 'php7.4'
</code>```

I tried all the solutions mentioned in answer to this question:

Unable to install PHP 7.3 on Ubuntu 20.04

None of them helped. How can I install this package?

答:
Here are installation instructions for ZendPHP repository - https://help.zend.com/zendphp/current/content/installation/installation.htm

The ZendPHP installation package replaces Ubuntu 16.04 distribution's PHP and supports PHP 5.6, PHP 7.1, PHP 7.2, PHP 7.3, and PHP 7.4 on Ubuntu 16.04.  Zend also offers PHP LTS for versions that are EOL and no longer receiving high and critical security patches

Body:
I am  trying to install PHP 7.4 on Ubuntu 16.04 for Apache2 server. To install the 7.4 version, I used PPA ondrej repository as follows:

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install -y php7.4
php -v

I get the following error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.4
E: Couldn't find any package by glob 'php7.4'
E: Couldn't find any package by regex 'php7.4'

I tried all the solutions mentioned in answer to this question:

Unable to install PHP 7.3 on Ubuntu 20.04

None of them helped. How can I install this package?


问:
Why does "split" on an empty string return a non-empty array?
Split on an empty string returns an array of size 1 :

```<code>scala> "".split(',')
res1: Array[String] = Array("")
</code>```

Consider that this returns empty array:

```<code>scala> ",,,,".split(',')
res2: Array[String] = Array()
</code>```

Please explain :)

答:
use this Function,</p>
```<code>public static ArrayList<String> split(String body) {
    return new ArrayList<>(Arrays.asList(Optional.ofNullable(body).filter(a->!a.isEmpty()).orElse(",").split(",")));
}
</code>```

Body:
Split on an empty string returns an array of size 1 :

scala> "".split(',')
res1: Array[String] = Array("")

Consider that this returns empty array:

scala> ",,,,".split(',')
res2: Array[String] = Array()

Please explain :)

Body:
use this Function,

public static ArrayList<String> split(String body) {
    return new ArrayList<>(Arrays.asList(Optional.ofNullable(body).filter(a->!a.isEmpty()).orElse(",").split(",")));
}


问:
oData - How to dynamically include a relational property for a single result?
I've noticed that oData will automatically include variables for collections.

How can I make this work the same way for an oData query that returns one item?

For example, if I add "$expand=Customer" to this call.  It will work with out me explicitly doing so in linq (.Include(p => p.Customer)

```<code>    public IEnumerable<ProjectEntity> Get()
    {
        return _db.Projects;
    }
</code>```

But this code will not automatically include project with the same syntax:

```<code>public ProjectEntity GetProjectById(int id)
    {
        return _db.Projects.Where(p => p.Id == id).FirstOrDefault();
    }
</code>```

答:
This is often misunderstood about OData, you need to return an IQueryable<T> expression for the $expand query option to be dynamically applied to your response object, there is a special wrapper for this SingleResult<T>.

The key is that you do not want to materialize the expression using .FirstOrDefault() but we still want the response to be a constrained to a single object in the JSON response instead of an array.

```<code>[EnableQuery]
public SingleResult<ProjectEntity> GetProjectById(int id)
{
    return SingleResult.Create(_db.Projects.Where(p => p.Id == id));
}
</code>```

If you didn't want to use SingleResult<T> then a hack would be to pre-emptively load the navigation property by Including it in the query.

```<code>public ProjectEntity GetProjectById(int id)
{
    return _db.Projects.Include(p => p.Customer)
                       .Where(p => p.Id == id)
                       .FirstOrDefault();
}
</code>```

Body:
I've noticed that oData will automatically include variables for collections.

How can I make this work the same way for an oData query that returns one item?

For example, if I add "$expand=Customer" to this call.  It will work with out me explicitly doing so in linq (.Include(p => p.Customer)

    public IEnumerable<ProjectEntity> Get()
    {
        return _db.Projects;
    }

But this code will not automatically include project with the same syntax:

public ProjectEntity GetProjectById(int id)
    {
        return _db.Projects.Where(p => p.Id == id).FirstOrDefault();
    }

Body:
This is often misunderstood about OData, you need to return an IQueryable<T> expression for the $expand query option to be dynamically applied to your response object, there is a special wrapper for this SingleResult<T>.

The key is that you do not want to materialize the expression using .FirstOrDefault() but we still want the response to be a constrained to a single object in the JSON response instead of an array.

[EnableQuery]
public SingleResult<ProjectEntity> GetProjectById(int id)
{
    return SingleResult.Create(_db.Projects.Where(p => p.Id == id));
}

If you didn't want to use SingleResult<T> then a hack would be to pre-emptively load the navigation property by Including it in the query.

public ProjectEntity GetProjectById(int id)
{
    return _db.Projects.Include(p => p.Customer)
                       .Where(p => p.Id == id)
                       .FirstOrDefault();
}


问:
How to store variables in for-loop to print after loop has completed?
I am currently working on a code that determines the floor occupancy rate of a hotel with 8 floors and 30 rooms per floor. I have successfully created the loop to determine the occupancy of each floor, however, after the for loop has completed, I’m supposed to display all the floor occupancy rates and total hotel occupancy rate. Do you guys have any advice? Hopefully the description of what I’m trying to achieve is good enough. Ive attached a picture of how the desired program should run. Thank you in advance!!</p>
```<code>print("this program will calculate a hotel's occupancy rate.")

# variable initialization
roomsOccupied = 0
floorOcupancyRate = (roomsOccupied/30) * 100
totalRoomsOccupied = 0
roomsAvailable = 30
floorOccupancyList = []

# list {1, 2, 3, 4, 5, 6, 7, 8}
# range

# user Input
for floorNbr in {1, 2, 3, 4, 5, 6, 7, 8}:
    print('Current floor: ', floorNbr)
    roomsOccupied = int(input('Please enter the number of rooms occupied on this floor: '))
    if roomsOccupied == True:
        if roomsOccupied <= roomsAvailable:
            floorOccupancyList.append(roomsOccupied)
            floorOccupancyRate = round((roomsOccupied/30)*100, 2)
            totalRoomsOccupied += roomsOccupied
            totalOccupancyRate = round((totalRoomsOccupied/240)*100, 2)
            print('For floor ', str(floorNbr), 'there are a total of ', str(roomsOccupied), 'for a floor occupancy rate of ', str(floorOccupancyRate), '%')
        else:
            print('Invalid occupancy amouont. Please try again.')
    else:
        roomsOccupied =int(input('Please enter a valid room occupacy amount: '))
print('There are a total of ', totalRoomsOccupied, 'rooms occupied for a total hotel occupancy rate of ', totalOccupancyRate, '%')
print(floorOccupancyList)
# Processing
# output
print('The total number of rooms occupied is: ', totalRoomsOccupied)
</code>```

答:
You can take the following approach.</p>
```<code># A List to store Results
res:list = []

# Loop Operation
for i in range(20):
    floor = f'floor-{i}'
    res.append({floor: i})

print(res)
</code>```

Body:
I am currently working on a code that determines the floor occupancy rate of a hotel with 8 floors and 30 rooms per floor. I have successfully created the loop to determine the occupancy of each floor, however, after the for loop has completed, I’m supposed to display all the floor occupancy rates and total hotel occupancy rate. Do you guys have any advice? Hopefully the description of what I’m trying to achieve is good enough. Ive attached a picture of how the desired program should run. Thank you in advance!!

print("this program will calculate a hotel's occupancy rate.")

# variable initialization
roomsOccupied = 0
floorOcupancyRate = (roomsOccupied/30) * 100
totalRoomsOccupied = 0
roomsAvailable = 30
floorOccupancyList = []

# list {1, 2, 3, 4, 5, 6, 7, 8}
# range

# user Input
for floorNbr in {1, 2, 3, 4, 5, 6, 7, 8}:
    print('Current floor: ', floorNbr)
    roomsOccupied = int(input('Please enter the number of rooms occupied on this floor: '))
    if roomsOccupied == True:
        if roomsOccupied <= roomsAvailable:
            floorOccupancyList.append(roomsOccupied)
            floorOccupancyRate = round((roomsOccupied/30)*100, 2)
            totalRoomsOccupied += roomsOccupied
            totalOccupancyRate = round((totalRoomsOccupied/240)*100, 2)
            print('For floor ', str(floorNbr), 'there are a total of ', str(roomsOccupied), 'for a floor occupancy rate of ', str(floorOccupancyRate), '%')
        else:
            print('Invalid occupancy amouont. Please try again.')
    else:
        roomsOccupied =int(input('Please enter a valid room occupacy amount: '))
print('There are a total of ', totalRoomsOccupied, 'rooms occupied for a total hotel occupancy rate of ', totalOccupancyRate, '%')
print(floorOccupancyList)
# Processing
# output
print('The total number of rooms occupied is: ', totalRoomsOccupied)

Body:
You can take the following approach.

# A List to store Results
res:list = []

# Loop Operation
for i in range(20):
    floor = f'floor-{i}'
    res.append({floor: i})

print(res)


问:
How to solve picturebox1 is null?
I'm developing a demo that, for now, simply changes the width and height of a PictureBox according to the user's input.

For this to happen, the user inputs the data in one Windows Forms, and the PictureBox is in another PictureBox.

They exchange data via constructor as exemplified by this code:

```<code>if (pf.GetData().Item1 >= int.Parse(textBox1.Text) && pf.GetData().Item2 >= int.Parse(textBox2.Text))
{
    PictureForm pbf = new PictureForm(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
    pf.Show();
    this.Hide();
}
</code>```

in the first Form

```<code>public PictureForm(int newMaxX, int newMaxY)
{
    pictureBox1.Width = newMaxX;
    pictureBox1.Height = newMaxY;
}
</code>```

and the constructor.

When I debut and input everything, this error message shows:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

pictureBox1 was null.

I really don't understand what's wrong.
Can somebody help me with this?

答:
In the form constructor, you must call InitializeComponent. This creates and configures the controls.

```<code>public PictureForm(int newMaxX, int newMaxY)
{
    InitializeComponent();
    pictureBox1.Width = newMaxX;
    pictureBox1.Height = newMaxY;
}
</code>```

The form is implemented with partial classes. I.e., the Form class is split into two code files: PictureForm.cs (this is where your user code resides) and PictureForm.designer.cs. The latter is created by the forms designer and contains the method InitializeComponent. You can open this file and look what this method does. All the controls with all their properties are created here. This is what is saved, when you save a form. I.e., there is no mysterious file format where the form is stored because everything is stored as C# code (except for resources, like icons that are stored in PictureForm.resx).

Title: How to solve picturebox1 is null?

Body:
I'm developing a demo that, for now, simply changes the width and height of a PictureBox according to the user's input.

For this to happen, the user inputs the data in one Windows Forms, and the PictureBox is in another PictureBox.

They exchange data via constructor as exemplified by this code:

if (pf.GetData().Item1 >= int.Parse(textBox1.Text) && pf.GetData().Item2 >= int.Parse(textBox2.Text))
{
    PictureForm pbf = new PictureForm(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
    pf.Show();
    this.Hide();
}

in the first Form

public PictureForm(int newMaxX, int newMaxY)
{
    pictureBox1.Width = newMaxX;
    pictureBox1.Height = newMaxY;
}

and the constructor.

When I debut and input everything, this error message shows:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

pictureBox1 was null.

I really don't understand what's wrong.
Can somebody help me with this?

Body:
In the form constructor, you must call InitializeComponent. This creates and configures the controls.

public PictureForm(int newMaxX, int newMaxY)
{
    InitializeComponent();
    pictureBox1.Width = newMaxX;
    pictureBox1.Height = newMaxY;
}

The form is implemented with partial classes. I.e., the Form class is split into two code files: PictureForm.cs (this is where your user code resides) and PictureForm.designer.cs. The latter is created by the forms designer and contains the method InitializeComponent. You can open this file and look what this method does. All the controls with all their properties are created here. This is what is saved, when you save a form. I.e., there is no mysterious file format where the form is stored because everything is stored as C# code (except for resources, like icons that are stored in PictureForm.resx).


问:
"Unable to find any implementation of the contract" Exception in LightSwitch extension
I'm teaching myself Visual Studio LightSwitch by porting Excel Importer extension.
I have all the pre-requisites (Visual Studio 2010 SP1 Ultimate edition, Visual Studio 2010 SP1 SDK, Visual Studio LightSwitch 2011 Extensibility Toolkit) except that I'm using LightSwitch Beta 2.

While trying to execute this line,

```<code>IServiceProxy sdkProxy = VsExportProviderService.GetExportedValue<IServiceProxy>();
</code>```

I get the following exception:

The composition produced a single composition error. The root cause is

provided below. Review the CompositionException.Errors property for
    more detailed information.

1) Unable to find any implementation of the contract:
    'Microsoft.LightSwitch.Sdk.Proxy.IServiceProxy'

Any idea on how to resolve this?

答:
So I managed to solve my problem by doing a complete re-install of Visual Studio 2010 SP1 Ultimate edition, Visual Studio 2010 SP1 SDK, Visual Studio LightSwitch 2011 Extensibility Toolkit and LightSwitch.
I tried everything I could think of to avoid this but after finding that the Microsoft samples themselves failed to build with the exact same error, I concluded that some DLL that contained the implementation IServiceProxy was probably out of date or not registered.

I can now build the solution with no issues.

Body:
I'm teaching myself Visual Studio LightSwitch by porting Excel Importer extension.
I have all the pre-requisites (Visual Studio 2010 SP1 Ultimate edition, Visual Studio 2010 SP1 SDK, Visual Studio LightSwitch 2011 Extensibility Toolkit) except that I'm using LightSwitch Beta 2.

While trying to execute this line,

IServiceProxy sdkProxy = VsExportProviderService.GetExportedValue<IServiceProxy>();

I get the following exception:

The composition produced a single composition error. The root cause is

provided below. Review the CompositionException.Errors property for
    more detailed information.

1) Unable to find any implementation of the contract:
    'Microsoft.LightSwitch.Sdk.Proxy.IServiceProxy'

Any idea on how to resolve this?


问:
Jenkins agent as Windows service starts and stops
I am attempting to install a Jenkins agent as a Windows 10 service. I install the service with

```<code>jenkins-slave.exe install
</code>```

and have configured the associated xml file, and the service appears to be properly installed. However, when I start the service, it stops immediately.

A jenkins-slave.wrapper.log file is generated, containing

```<code>2021-09-09 11:30:53,503 DEBUG - Starting WinSW in the CLI mode
2021-09-09 11:30:54,191 INFO  - Installing the service with id 'JenkinsAgent'
2021-09-09 11:30:54,238 DEBUG - Completed. Exit code is 0
2021-09-09 11:31:02,164 DEBUG - Starting WinSW in the service mode
2021-09-09 11:31:02,211 INFO  - Downloading: https://<jenkins-server>/jnlpJars/slave.jar to C:\jenkins-agent\slave.jar. failOnError=False
2021-09-09 11:31:02,321 INFO  - Skipped downloading unmodified resource 'https://<jenkins-server>/jnlpJars/slave.jar'
2021-09-09 11:31:02,321 INFO  - Starting java.exe -Xrs -jar "C:\jenkins-agent\slave.jar" -jnlpUrl https:/<jenkins-server>/computer/jetdamdev2/jenkins-agent.jnlp -secret <secret> -workDir "C:\jenkins-agent"
2021-09-09 11:31:02,336 DEBUG - Completed. Exit code is 0
</code>```

This seems to indicate that the java process is started, but exits about 115ms later.

If I copy the java-launch line into a command-line terminal, it successfully connects to the Jenkins master and stays running.

I have been chasing this issue for quite a while now, with no success. Can someone please tell me what I have done wrong with the service and help me fix this?

答:
I know I am late for the party, but maybe it comes handy for others:
I was following this article: https://hayato-iriumi.net/2019/05/23/how-to-install-jenkins-slave-as-windows-service/
I have faced the same problem with WinSW, and ended up wrapping the whole agent startup command line in a batch file, and run the batch from WinSW. So my jenkins-slave.xml looks like this:

```<code><service>
  <id>JenkinsSlave</id>
  <name>Jenkins agent</name>
  <description>This service runs an agent for Jenkins automation server.</description>
  <executable>c:\jenkins\agent.bat</executable>
  <logmode>rotate</logmode>
</service>
</code>```

And agent.bat like this:

```<code>java -jar agent.jar -jnlpUrl http://<jenkins master URL>/jenkins-agent.jnlp -secret <secret> -workDir "c:\jenkins"
</code>```

For me this solved the problem. I am stuck at an older, 2.319.1 version of Jenkins for legacy reasons.

Body:
I am attempting to install a Jenkins agent as a Windows 10 service. I install the service with

jenkins-slave.exe install

and have configured the associated xml file, and the service appears to be properly installed. However, when I start the service, it stops immediately.

A jenkins-slave.wrapper.log file is generated, containing

2021-09-09 11:30:53,503 DEBUG - Starting WinSW in the CLI mode
2021-09-09 11:30:54,191 INFO  - Installing the service with id 'JenkinsAgent'
2021-09-09 11:30:54,238 DEBUG - Completed. Exit code is 0
2021-09-09 11:31:02,164 DEBUG - Starting WinSW in the service mode
2021-09-09 11:31:02,211 INFO  - Downloading: https://<jenkins-server>/jnlpJars/slave.jar to C:\jenkins-agent\slave.jar. failOnError=False
2021-09-09 11:31:02,321 INFO  - Skipped downloading unmodified resource 'https://<jenkins-server>/jnlpJars/slave.jar'
2021-09-09 11:31:02,321 INFO  - Starting java.exe -Xrs -jar "C:\jenkins-agent\slave.jar" -jnlpUrl https:/<jenkins-server>/computer/jetdamdev2/jenkins-agent.jnlp -secret <secret> -workDir "C:\jenkins-agent"
2021-09-09 11:31:02,336 DEBUG - Completed. Exit code is 0

This seems to indicate that the java process is started, but exits about 115ms later.

If I copy the java-launch line into a command-line terminal, it successfully connects to the Jenkins master and stays running.

I have been chasing this issue for quite a while now, with no success. Can someone please tell me what I have done wrong with the service and help me fix this?

Body:
I know I am late for the party, but maybe it comes handy for others:
I was following this article: https://hayato-iriumi.net/2019/05/23/how-to-install-jenkins-slave-as-windows-service/
I have faced the same problem with WinSW, and ended up wrapping the whole agent startup command line in a batch file, and run the batch from WinSW. So my jenkins-slave.xml looks like this:

<service>
  <id>JenkinsSlave</id>
  <name>Jenkins agent</name>
  <description>This service runs an agent for Jenkins automation server.</description>
  <executable>c:\jenkins\agent.bat</executable>
  <logmode>rotate</logmode>
</service>

And agent.bat like this:

java -jar agent.jar -jnlpUrl http://<jenkins master URL>/jenkins-agent.jnlp -secret <secret> -workDir "c:\jenkins"

For me this solved the problem. I am stuck at an older, 2.319.1 version of Jenkins for legacy reasons.


问:
.Net 6 - Custom Middleware Logging - Mixing responses and requests
I have written custom middleware that logs requests and responses made to our APIs.

What I've realised is that the requests and responses are not matching, they seem to get mixed up, which is very odd.

This seems to happen when a lot of requests are made within a very short time. Not sure how, but it seems like when LogResponse is called, it's not within the same scope as LogRequest.

I've implemented a version of: https://stackoverflow.com/a/43404745/2286743

Am I missing anything?

Trimmed down version of actual code

```<code>using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace Middleware
{
    public class Web
    {
        private readonly RequestDelegate _next;

        private Logging.AuditLog _auditLog;

        public Web(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                EndpointMetadataCollection endpointMetaData = context.Features.Get<IEndpointFeature>()?.Endpoint.Metadata;

                context.Request.EnableBuffering();

                await LogRequest(context);
                await LogResponse(context);
            }
            catch (UnauthorizedAccessException)
            {
                throw;
            }
            catch (Exception ex)
            {
                //Custom exception logging here
            }
        }

        public async Task LogRequest(HttpContext context)
        {
            IHttpRequestFeature features = context.Features.Get<IHttpRequestFeature>();
            string url = $"{features.Scheme}://{context.Request.Host.Value}{features.RawTarget}";

            IFormCollection form = null;
            string formString = string.Empty;

            if (context.Request.HasFormContentType)
            {
                form = context.Request.Form;
            }
            else
            {
                formString = await new StreamReader(context.Request.Body).ReadToEndAsync();
                var injectedRequestStream = new MemoryStream();
                byte[] bytesToWrite = Encoding.UTF8.GetBytes(formString);
                injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
                injectedRequestStream.Seek(0, SeekOrigin.Begin);
                context.Request.Body = injectedRequestStream;
            }

            _auditLog = new Logging.AuditLog()
            {
                RemoteHost = context.Connection.RemoteIpAddress.ToString(),
                HttpURL = url,
                LocalAddress = context.Connection.LocalIpAddress.ToString(),
                Headers = Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Headers),
                Form = form != null ? Newtonsoft.Json.JsonConvert.SerializeObject(form) : formString
            };
        }

        public async Task LogResponse(HttpContext context)
        {
            if (_auditLog == null)
            {
                await _next(context);
                return;
            }

            Stream originalBody = context.Response.Body;

            try
            {

                using (var memStream = new MemoryStream())
                {
                    context.Response.Body = memStream;

                    await _next(context);

                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();

                    _auditLog.ResponseStatusCode = context.Response.StatusCode;
                    _auditLog.ResponseBody = responseBody;
                    _auditLog = _auditLog.Save();

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }
            }
            catch
            {
                _auditLog?.Save();
                throw;
            }
            finally
            {
                context.Response.Body = originalBody;
            }
        }
    }
}

</code>```

答:
So I was able to resolve this after some investigations.

The global variables set, is what was causing the mix-up. They are being re-used by all other endpoints.

private Logging.AuditLog _auditLog; has to be used within the methods to function as intended. If set globally, when a new endpoint is invoked, it will re-write the _auditLog variable with a new object. The other endpoint, still being executed, will have it's object for _auditLog replaced. That caused duplicates and mismatching response to request bodies.

The changes I made:

OLD

```<code>await LogRequest(context);
await LogResponse(context);
</code>```

NEW

```<code>var auditLog = await LogRequest(context);
await LogResponse(context, auditLog);
</code>```

The rest is self explanatory.

Here is the full page:

```<code>using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace Middleware
{
    public class Web
    {
        private readonly RequestDelegate _next;

        public Web(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                EndpointMetadataCollection endpointMetaData = context.Features.Get<IEndpointFeature>()?.Endpoint.Metadata;

                context.Request.EnableBuffering();

                var auditLog = await LogRequest(context);
                await LogResponse(context, auditLog);
            }
            catch (UnauthorizedAccessException)
            {
                throw;
            }
            catch (Exception ex)
            {
                //Custom exception logging here
            }
        }

        public async Task<Logging.AuditLog> LogRequest(HttpContext context)
        {
            IHttpRequestFeature features = context.Features.Get<IHttpRequestFeature>();
            string url = $"{features.Scheme}://{context.Request.Host.Value}{features.RawTarget}";

            IFormCollection form = null;
            string formString = string.Empty;

            if (context.Request.HasFormContentType)
            {
                form = context.Request.Form;
            }
            else
            {
                formString = await new StreamReader(context.Request.Body).ReadToEndAsync();
                var injectedRequestStream = new MemoryStream();
                byte[] bytesToWrite = Encoding.UTF8.GetBytes(formString);
                injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
                injectedRequestStream.Seek(0, SeekOrigin.Begin);
                context.Request.Body = injectedRequestStream;
            }

            return new Logging.AuditLog()
            {
                RemoteHost = context.Connection.RemoteIpAddress.ToString(),
                HttpURL = url,
                LocalAddress = context.Connection.LocalIpAddress.ToString(),
                Headers = Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Headers),
                Form = form != null ? Newtonsoft.Json.JsonConvert.SerializeObject(form) : formString
            };
        }

        public async Task LogResponse(HttpContext context, Logging.AuditLog auditLog)
        {
            if (auditLog == null)
            {
                await _next(context);
                return;
            }

            Stream originalBody = context.Response.Body;

            try
            {

                using (var memStream = new MemoryStream())
                {
                    context.Response.Body = memStream;

                    await _next(context);

                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();

                    auditLog.ResponseStatusCode = context.Response.StatusCode;
                    auditLog.ResponseBody = responseBody;
                    auditLog = auditLog.Save();

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }
            }
            catch
            {
                auditLog?.Save();
                throw;
            }
            finally
            {
                context.Response.Body = originalBody;
            }
        }
    }
}
</code>```

Body:
I have written custom middleware that logs requests and responses made to our APIs.

What I've realised is that the requests and responses are not matching, they seem to get mixed up, which is very odd.

This seems to happen when a lot of requests are made within a very short time. Not sure how, but it seems like when LogResponse is called, it's not within the same scope as LogRequest.

I've implemented a version of: https://stackoverflow.com/a/43404745/2286743

Am I missing anything?

Trimmed down version of actual code

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace Middleware
{
    public class Web
    {
        private readonly RequestDelegate _next;

        private Logging.AuditLog _auditLog;

        public Web(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                EndpointMetadataCollection endpointMetaData = context.Features.Get<IEndpointFeature>()?.Endpoint.Metadata;

                context.Request.EnableBuffering();

                await LogRequest(context);
                await LogResponse(context);
            }
            catch (UnauthorizedAccessException)
            {
                throw;
            }
            catch (Exception ex)
            {
                //Custom exception logging here
            }
        }

        public async Task LogRequest(HttpContext context)
        {
            IHttpRequestFeature features = context.Features.Get<IHttpRequestFeature>();
            string url = $"{features.Scheme}://{context.Request.Host.Value}{features.RawTarget}";

            IFormCollection form = null;
            string formString = string.Empty;

            if (context.Request.HasFormContentType)
            {
                form = context.Request.Form;
            }
            else
            {
                formString = await new StreamReader(context.Request.Body).ReadToEndAsync();
                var injectedRequestStream = new MemoryStream();
                byte[] bytesToWrite = Encoding.UTF8.GetBytes(formString);
                injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
                injectedRequestStream.Seek(0, SeekOrigin.Begin);
                context.Request.Body = injectedRequestStream;
            }

            _auditLog = new Logging.AuditLog()
            {
                RemoteHost = context.Connection.RemoteIpAddress.ToString(),
                HttpURL = url,
                LocalAddress = context.Connection.LocalIpAddress.ToString(),
                Headers = Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Headers),
                Form = form != null ? Newtonsoft.Json.JsonConvert.SerializeObject(form) : formString
            };
        }

        public async Task LogResponse(HttpContext context)
        {
            if (_auditLog == null)
            {
                await _next(context);
                return;
            }

            Stream originalBody = context.Response.Body;

            try
            {

                using (var memStream = new MemoryStream())
                {
                    context.Response.Body = memStream;

                    await _next(context);

                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();

                    _auditLog.ResponseStatusCode = context.Response.StatusCode;
                    _auditLog.ResponseBody = responseBody;
                    _auditLog = _auditLog.Save();

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }
            }
            catch
            {
                _auditLog?.Save();
                throw;
            }
            finally
            {
                context.Response.Body = originalBody;
            }
        }
    }
}

Body:
So I was able to resolve this after some investigations.

The global variables set, is what was causing the mix-up. They are being re-used by all other endpoints.

private Logging.AuditLog _auditLog; has to be used within the methods to function as intended. If set globally, when a new endpoint is invoked, it will re-write the _auditLog variable with a new object. The other endpoint, still being executed, will have it's object for _auditLog replaced. That caused duplicates and mismatching response to request bodies.

The changes I made:

OLD

await LogRequest(context);
await LogResponse(context);

NEW

var auditLog = await LogRequest(context);
await LogResponse(context, auditLog);

The rest is self explanatory.

Here is the full page:

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace Middleware
{
    public class Web
    {
        private readonly RequestDelegate _next;

        public Web(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                EndpointMetadataCollection endpointMetaData = context.Features.Get<IEndpointFeature>()?.Endpoint.Metadata;

                context.Request.EnableBuffering();

                var auditLog = await LogRequest(context);
                await LogResponse(context, auditLog);
            }
            catch (UnauthorizedAccessException)
            {
                throw;
            }
            catch (Exception ex)
            {
                //Custom exception logging here
            }
        }

        public async Task<Logging.AuditLog> LogRequest(HttpContext context)
        {
            IHttpRequestFeature features = context.Features.Get<IHttpRequestFeature>();
            string url = $"{features.Scheme}://{context.Request.Host.Value}{features.RawTarget}";

            IFormCollection form = null;
            string formString = string.Empty;

            if (context.Request.HasFormContentType)
            {
                form = context.Request.Form;
            }
            else
            {
                formString = await new StreamReader(context.Request.Body).ReadToEndAsync();
                var injectedRequestStream = new MemoryStream();
                byte[] bytesToWrite = Encoding.UTF8.GetBytes(formString);
                injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
                injectedRequestStream.Seek(0, SeekOrigin.Begin);
                context.Request.Body = injectedRequestStream;
            }

            return new Logging.AuditLog()
            {
                RemoteHost = context.Connection.RemoteIpAddress.ToString(),
                HttpURL = url,
                LocalAddress = context.Connection.LocalIpAddress.ToString(),
                Headers = Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Headers),
                Form = form != null ? Newtonsoft.Json.JsonConvert.SerializeObject(form) : formString
            };
        }

        public async Task LogResponse(HttpContext context, Logging.AuditLog auditLog)
        {
            if (auditLog == null)
            {
                await _next(context);
                return;
            }

            Stream originalBody = context.Response.Body;

            try
            {

                using (var memStream = new MemoryStream())
                {
                    context.Response.Body = memStream;

                    await _next(context);

                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();

                    auditLog.ResponseStatusCode = context.Response.StatusCode;
                    auditLog.ResponseBody = responseBody;
                    auditLog = auditLog.Save();

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }
            }
            catch
            {
                auditLog?.Save();
                throw;
            }
            finally
            {
                context.Response.Body = originalBody;
            }
        }
    }
}


问:
Python - os.getcwd() doesn't return the full path
At the start of the file, I specified the path using:

```<code>path = r"C:\Documents\Data"
os.chdir(path)
</code>```

Later on, I want to iterate through subfolders in the Data folder. This folder contains 2018, which contains Level2A. I do this with:

```<code>for root, subdirectories, files in os.walk(path):
        for filename in subdirectories:
            if filename.endswith('.SAFE'):
                print(filename)
                print(os.getcwd())
</code>```

When printing the subfolder's name, it works; it prints folder_name.SAFE. When I, however want to print the path which it's currently looking at, I get the following:

```<code>print(os.getcwd())
>>> C:\Documents\Data
</code>```

Why do I not get C:\Documents\Data\2018\Level2A whose file I printed is? What do I have to change to do get this?

答:
everytime you exceute os.getcwd(), you will get your current directory.
if you need full path of filename that contain ".SAFE" on it's filename, you need to print something like this :</p>
```<code>for root, subdirectories, files in os.walk(path):
    for filename in subdirectories:
        if filename.endswith('.SAFE'):
            print(filename)
            print(root+"/"+filename)
</code>```

Body:
At the start of the file, I specified the path using:

path = r"C:\Documents\Data"
os.chdir(path)

Later on, I want to iterate through subfolders in the Data folder. This folder contains 2018, which contains Level2A. I do this with:

for root, subdirectories, files in os.walk(path):
        for filename in subdirectories:
            if filename.endswith('.SAFE'):
                print(filename)
                print(os.getcwd())

When printing the subfolder's name, it works; it prints folder_name.SAFE. When I, however want to print the path which it's currently looking at, I get the following:

print(os.getcwd())
>>> C:\Documents\Data

Why do I not get C:\Documents\Data\2018\Level2A whose file I printed is? What do I have to change to do get this?

Body:
everytime you exceute os.getcwd(), you will get your current directory.
if you need full path of filename that contain ".SAFE" on it's filename, you need to print something like this :

for root, subdirectories, files in os.walk(path):
    for filename in subdirectories:
        if filename.endswith('.SAFE'):
            print(filename)
            print(root+"/"+filename)


问:
Can you put the result of a blackdetect filter in a textfile using ffmpeg?
I'm testing out the "blackdetect" filter in ffmpeg. I want to have the times when the video is black to be read by a script (like actionscript or javascript). I tried:

```<code>ffmpeg -i video1.mp4 -vf "blackdetect=d=2:pix_th=0.00" -an -f null -
</code>```

And I get a nice result in the ffmpeg log:

```<code>ffmpeg version N-55644-g68b63a3 Copyright (c) 2000-2013 the FFmpeg developers
  built on Aug 19 2013 20:32:00 with gcc 4.7.3 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
le-iconv --enable-libass --enable-libbluray --enable-libcaca --enable-libfreetyp
e --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --ena
ble-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-l
ibopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libsp
eex --enable-libtheora --enable-libtwolame --enable-libvo-aacenc --enable-libvo-
amrwbenc --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libxavs --
enable-libxvid --enable-zlib
  libavutil      52. 42.100 / 52. 42.100
  libavcodec     55. 28.100 / 55. 28.100
  libavformat    55. 13.103 / 55. 13.103
  libavdevice    55.  3.100 / 55.  3.100
  libavfilter     3. 82.100 /  3. 82.100
  libswscale      2.  5.100 /  2.  5.100
  libswresample   0. 17.103 /  0. 17.103
  libpostproc    52.  3.100 / 52.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video1.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 1970-01-01 00:00:00
    encoder         : Lavf53.13.0
  Duration: 00:02:01.54, start: 0.000000, bitrate: 275 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 768x432 [
SAR 1:1 DAR 16:9], 211 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 59
 kb/s
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : SoundHandler
Output #0, null, to 'pipe:':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf55.13.103
    Stream #0:0(eng): Video: rawvideo (I420 / 0x30323449), yuv420p, 768x432 [SAR
 1:1 DAR 16:9], q=2-31, 200 kb/s, 90k tbn, 25 tbc
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : VideoHandler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> rawvideo)
Press [q] to stop, [?] for help
[null @ 00000000003279a0] Encoder did not produce proper pts, making some up.
[blackdetect @ 0000000004d5e800] black_start:0 black_end:17.08 black_duration:17
.08
[blackdetect @ 0000000004d5e800] black_start:62.32 black_end:121.48 black_durati
on:59.16
frame= 3038 fps=2317 q=0.0 Lsize=N/A time=00:02:01.52 bitrate=N/A
video:285kB audio:0kB subtitle:0 global headers:0kB muxing overhead -100.007543%
</code>```

And I'm particularly interested in this part:

```<code>[blackdetect @ 0000000004e2e340] black_start:0 black_end:17.08 black_duration:17.08
[blackdetect @ 0000000004e2e340] black_start:62.32 black_end:121.48 black_duration:59.16
</code>```

So my question:

Is there a way to only take the blackdetect filter output and put it in a .txt file?

And if this is possible, is there a way to do this in a statement with multiple video inputs? Like in this example

example:

```<code>ffmpeg -f concat -i mylist.txt -c copy concat.mp4
</code>```

Where mylist.txt is a list of videos:

```<code>file 'video1.mp4'
file 'video2.mp4'
file 'video3.mp4'
file 'video4.mp4'
</code>```

Basically what I want to have is one or more text files containing information about the black frames in every video in this list to be used by another program

答:
For anyone coming across this post looking to use blackdetect in a similar manner to OP, I've made a bash script for creating a blackdetect log that's based on aergistal's answer.

GitHub Link

Body:
I'm testing out the "blackdetect" filter in ffmpeg. I want to have the times when the video is black to be read by a script (like actionscript or javascript). I tried:

ffmpeg -i video1.mp4 -vf "blackdetect=d=2:pix_th=0.00" -an -f null -

And I get a nice result in the ffmpeg log:

ffmpeg version N-55644-g68b63a3 Copyright (c) 2000-2013 the FFmpeg developers
  built on Aug 19 2013 20:32:00 with gcc 4.7.3 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
le-iconv --enable-libass --enable-libbluray --enable-libcaca --enable-libfreetyp
e --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --ena
ble-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-l
ibopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libsp
eex --enable-libtheora --enable-libtwolame --enable-libvo-aacenc --enable-libvo-
amrwbenc --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libxavs --
enable-libxvid --enable-zlib
  libavutil      52. 42.100 / 52. 42.100
  libavcodec     55. 28.100 / 55. 28.100
  libavformat    55. 13.103 / 55. 13.103
  libavdevice    55.  3.100 / 55.  3.100
  libavfilter     3. 82.100 /  3. 82.100
  libswscale      2.  5.100 /  2.  5.100
  libswresample   0. 17.103 /  0. 17.103
  libpostproc    52.  3.100 / 52.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video1.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 1970-01-01 00:00:00
    encoder         : Lavf53.13.0
  Duration: 00:02:01.54, start: 0.000000, bitrate: 275 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 768x432 [
SAR 1:1 DAR 16:9], 211 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 59
 kb/s
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : SoundHandler
Output #0, null, to 'pipe:':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf55.13.103
    Stream #0:0(eng): Video: rawvideo (I420 / 0x30323449), yuv420p, 768x432 [SAR
 1:1 DAR 16:9], q=2-31, 200 kb/s, 90k tbn, 25 tbc
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : VideoHandler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> rawvideo)
Press [q] to stop, [?] for help
[null @ 00000000003279a0] Encoder did not produce proper pts, making some up.
[blackdetect @ 0000000004d5e800] black_start:0 black_end:17.08 black_duration:17
.08
[blackdetect @ 0000000004d5e800] black_start:62.32 black_end:121.48 black_durati
on:59.16
frame= 3038 fps=2317 q=0.0 Lsize=N/A time=00:02:01.52 bitrate=N/A
video:285kB audio:0kB subtitle:0 global headers:0kB muxing overhead -100.007543%

And I'm particularly interested in this part:

[blackdetect @ 0000000004e2e340] black_start:0 black_end:17.08 black_duration:17.08
[blackdetect @ 0000000004e2e340] black_start:62.32 black_end:121.48 black_duration:59.16

So my question:

Is there a way to only take the blackdetect filter output and put it in a .txt file?

And if this is possible, is there a way to do this in a statement with multiple video inputs? Like in this example

example:

ffmpeg -f concat -i mylist.txt -c copy concat.mp4

Where mylist.txt is a list of videos:

file 'video1.mp4'
file 'video2.mp4'
file 'video3.mp4'
file 'video4.mp4'

Basically what I want to have is one or more text files containing information about the black frames in every video in this list to be used by another program


问:
Exiftool::ExiftoolNotInstalled (Exiftool::ExiftoolNotInstalled) after being installed
I'm trying to run a ruby script where I used the exiftool gem, and everytime I'm trying to run it I keep getting this error even after installed it. Also, after running bundler as well.

```<code>Traceback (most recent call last):
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/exiftool-1.2.4/lib/exiftool.rb:60:in `initialize': Exiftool::ExiftoolNotInstalled (Exiftool::ExiftoolNotInstalled)
</code>```

Also, it is running on my cmd. I tried testing it using the irb and the Exiftool isn't being recognized by ruby.

答:
Looks like the exiftool gem does not currently support windows environments. It often appends 2> /dev/null/ when running shell commands.

You could potentually try running the script under WSL, or could try invoking the commands directly.

Body:
I'm trying to run a ruby script where I used the exiftool gem, and everytime I'm trying to run it I keep getting this error even after installed it. Also, after running bundler as well.

Traceback (most recent call last):
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/exiftool-1.2.4/lib/exiftool.rb:60:in `initialize': Exiftool::ExiftoolNotInstalled (Exiftool::ExiftoolNotInstalled)

Also, it is running on my cmd. I tried testing it using the irb and the Exiftool isn't being recognized by ruby.


问:
lock the first value from a groupby in dataframe pandas python
I want to lock the first value from a groupby in dataframe pandas.

Is that possible?

example:

Hope someone can help me...

答:
You need to use groupby+transform.

If you want to replace by the first value:

```<code>df['b'] = df.groupby('a')['b'].transform('first')
</code>```

or by the min value:

```<code>df['b'] = df.groupby('a')['b'].transform('min')
</code>```

output:

```<code>   a    b
0  1  100
1  1  100
2  1  100
3  2  400
4  2  400
5  2  400
6  3  700
7  3  700
8  3  700
</code>```

Body:
You need to use groupby+transform.

If you want to replace by the first value:

df['b'] = df.groupby('a')['b'].transform('first')

or by the min value:

df['b'] = df.groupby('a')['b'].transform('min')

output:

   a    b
0  1  100
1  1  100
2  1  100
3  2  400
4  2  400
5  2  400
6  3  700
7  3  700
8  3  700


问:
From which Dockerfile should composer install be called from
I need to call composer install and unsure from which Dockerfile to call it from - Dockerfile-apache or Dockerfile-php-fpm?

Should I install composer in Dockerfile-apache (and PHP CLI?) and run it from there?

Running composer install from Dockerfile-php-fpm gives me this: Composer could not find a composer.json file in /var/www/html

Docker-php-fpm

```<code># Do we target a specific version? ie. 7.4.25?
FROM php:7.4-fpm

# Need to add zip and other extensions
RUN buildDeps=" \
        libonig-dev \
        libzip-dev \
        libxml2-dev \
    " \
&& apt-get -y update \
&& apt-get install -y $buildDeps zip libicu-dev \
&& docker-php-ext-configure intl \
&& docker-php-ext-install intl mbstring json mysqli opcache pdo pdo_mysql xml \
&& apt-get purge -y --auto-remove $buildDeps \
&& rm -r /var/lib/apt/lists/*

# Copying of base conf files
COPY docker/php-fpm/conf/php-fpm.conf /usr/local/etc
COPY docker/php-fpm/conf/php.ini-development /usr/local/etc/php/php.ini
COPY docker/php-fpm/conf/www.conf /usr/local/etc/php-fpm.d

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

EXPOSE 9000
</code>```

Docker-apache:

```<code>FROM httpd:2.4

# Copy config files
COPY docker/apache/conf/httpd.conf /usr/local/apache2/conf
COPY docker/apache/conf/httpd-vhosts.conf /usr/local/apache2/conf/extra

# Do something about log rotate?

# Create vhost directory
WORKDIR /var/www/html

#Set our application folder as an environment variable
ENV APP_HOME /var/www/html

#copy files
COPY bin ${APP_HOME}/bin
COPY config ${APP_HOME}/config
COPY plugins ${APP_HOME}/plugins
COPY src ${APP_HOME}/src
COPY webroot ${APP_HOME}/webroot
COPY .htaccess ${APP_HOME}
COPY index.php ${APP_HOME}
COPY composer.json ${APP_HOME}
COPY composer.lock ${APP_HOME}
</code>```

Edit #1

docker-compose.yml

```<code>version: "3.2"
services:
  php-fpm:
    container_name: php-fpm
    build:
      context: .
      dockerfile: Dockerfile-php-fpm
    networks:
      - backend
    ports:
      - "9000:9000"
  apache:
    container_name: httpd
    build:
      context: .
      dockerfile: Dockerfile-apache
    depends_on:
      - php
    networks:
      - frontend
      - backend
    ports:
      - "80:80"
      - "443:443"
networks:
  frontend:
  backend:
</code>```

Edit #2

This docker-compose file enables the communication via a common volume. I just need to compile, build and copy the files in Apache at this point.

```<code>version: "3.9"
services:
  php-fpm:
    container_name: php-fpm
    build:
      context: .
      dockerfile: Dockerfile-php-fpm
    volumes:
      - mydata:/var/www/html:rw
    networks:
      - backend
    ports:
      - "9000:9000"
  apache:
    container_name: httpd
    build:
      context: .
      dockerfile: Dockerfile-apache
    depends_on:
      - php
    volumes:
      - mydata:/var/www/html:rw
    networks:
      - frontend
      - backend
    ports:
      - "80:80"
      - "443:443"
networks:
  frontend:
  backend:
volumes:
  mydata:
</code>```

答:
I would go with neither of the above; instead, run composer install locally and copy the resulting vendor directory as part of your application.

Fetching dependencies is fundamentally part of building an application, not part of running it, so Composer shouldn't even be installed on a production host or container. If you were writing a C application which needed to be compiled with gcc, you would run that as an earlier step, and then copy the binary into the container; composer install can be treated the same way.

So for instance, you might have a build script (to run manually, or in a CI server like Jenkins, Github Actions, Azure DevOps, etc) that went through the following steps:

Clone the repo from a git repository

Check out the latest tag

Run composer install

Run a script to minify the client-side JS

Run docker-composer, copying the source code, minified JS, and vendor directory

The software inside the Docker container therefore only needs to be able to run the application, not build it.

Body:
I need to call composer install and unsure from which Dockerfile to call it from - Dockerfile-apache or Dockerfile-php-fpm?

Should I install composer in Dockerfile-apache (and PHP CLI?) and run it from there?

Running composer install from Dockerfile-php-fpm gives me this: Composer could not find a composer.json file in /var/www/html

Docker-php-fpm

# Do we target a specific version? ie. 7.4.25?
FROM php:7.4-fpm

# Need to add zip and other extensions
RUN buildDeps=" \
        libonig-dev \
        libzip-dev \
        libxml2-dev \
    " \
&& apt-get -y update \
&& apt-get install -y $buildDeps zip libicu-dev \
&& docker-php-ext-configure intl \
&& docker-php-ext-install intl mbstring json mysqli opcache pdo pdo_mysql xml \
&& apt-get purge -y --auto-remove $buildDeps \
&& rm -r /var/lib/apt/lists/*

# Copying of base conf files
COPY docker/php-fpm/conf/php-fpm.conf /usr/local/etc
COPY docker/php-fpm/conf/php.ini-development /usr/local/etc/php/php.ini
COPY docker/php-fpm/conf/www.conf /usr/local/etc/php-fpm.d

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

EXPOSE 9000

Docker-apache:

FROM httpd:2.4

# Copy config files
COPY docker/apache/conf/httpd.conf /usr/local/apache2/conf
COPY docker/apache/conf/httpd-vhosts.conf /usr/local/apache2/conf/extra

# Do something about log rotate?

# Create vhost directory
WORKDIR /var/www/html

#Set our application folder as an environment variable
ENV APP_HOME /var/www/html

#copy files
COPY bin ${APP_HOME}/bin
COPY config ${APP_HOME}/config
COPY plugins ${APP_HOME}/plugins
COPY src ${APP_HOME}/src
COPY webroot ${APP_HOME}/webroot
COPY .htaccess ${APP_HOME}
COPY index.php ${APP_HOME}
COPY composer.json ${APP_HOME}
COPY composer.lock ${APP_HOME}

Edit #1

docker-compose.yml

version: "3.2"
services:
  php-fpm:
    container_name: php-fpm
    build:
      context: .
      dockerfile: Dockerfile-php-fpm
    networks:
      - backend
    ports:
      - "9000:9000"
  apache:
    container_name: httpd
    build:
      context: .
      dockerfile: Dockerfile-apache
    depends_on:
      - php
    networks:
      - frontend
      - backend
    ports:
      - "80:80"
      - "443:443"
networks:
  frontend:
  backend:

Edit #2

This docker-compose file enables the communication via a common volume. I just need to compile, build and copy the files in Apache at this point.

version: "3.9"
services:
  php-fpm:
    container_name: php-fpm
    build:
      context: .
      dockerfile: Dockerfile-php-fpm
    volumes:
      - mydata:/var/www/html:rw
    networks:
      - backend
    ports:
      - "9000:9000"
  apache:
    container_name: httpd
    build:
      context: .
      dockerfile: Dockerfile-apache
    depends_on:
      - php
    volumes:
      - mydata:/var/www/html:rw
    networks:
      - frontend
      - backend
    ports:
      - "80:80"
      - "443:443"
networks:
  frontend:
  backend:
volumes:
  mydata:


问:
How to use useState to store multiple key objects?
I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have

```<code>const [data, setData] = useState[]
  useEffect(() => {

    const fetchPrice = async () => {
      const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h

      const btcusd = data.data.results.map(
        (d) => {
          return {
            open: d.open,
            close: d.close,
            low: d.low,
            high: d.high,
            time: toDateStamp(d.datetime),
          };
        }
      );
      setData(btcusd)
    };

    fetchPrice()
  }, []);
</code>```

The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?

Edit:

My bad guys, I have no issues to have the useffect runs again as i have another useeffect for that purpose whenever a user clicks on a new timeframe. My question is how can I store the chosen timeframes into a state and then re-use them again should the user chooses the timeframe that he chose before? This would be nice as I can stop outgoing network request.

答:
can use the spread operator inside setData() to get the old values, then add the new value, something like this:

```<code>setData( oldValues => [ ...oldValues, newValue ] );
</code>```

Body:
I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have

const [data, setData] = useState[]
  useEffect(() => {

    const fetchPrice = async () => {
      const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h

      const btcusd = data.data.results.map(
        (d) => {
          return {
            open: d.open,
            close: d.close,
            low: d.low,
            high: d.high,
            time: toDateStamp(d.datetime),
          };
        }
      );
      setData(btcusd)
    };

    fetchPrice()
  }, []);

The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?

Edit:

My bad guys, I have no issues to have the useffect runs again as i have another useeffect for that purpose whenever a user clicks on a new timeframe. My question is how can I store the chosen timeframes into a state and then re-use them again should the user chooses the timeframe that he chose before? This would be nice as I can stop outgoing network request.

Body:
can use the spread operator inside setData() to get the old values, then add the new value, something like this:

setData( oldValues => [ ...oldValues, newValue ] );


问:
How to take a screenshot of the game view in Unity
How do you take a screenshot of the game view without external sources like Snipping Tool or Lightshot, like to take a screenshot with the resolution i configured in my Game View window.
Like i want to take a 4k screenshot for my desktop, store page or share with friends.</p>

答:
It's suprisingly easy, at the end you capture a screenshot off everything you see in the game view, if you want to dont show the ui, just disable the canvas for it.</p>
```<code>    private void Update(){
        if(Input.GetMouseButtonDown(0)){ // capture screen shot on left mouse button down

            string folderPath = "Assets/Screenshots/"; // the path of your project folder

            if (!System.IO.Directory.Exists(folderPath)) // if this path does not exist yet
                System.IO.Directory.CreateDirectory(folderPath);  // it will get created

            var screenshotName =
                                    "Screenshot_" +
                                    System.DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss") + // puts the current time right into the screenshot name
                                    ".png"; // put youre favorite data format here
            ScreenCapture.CaptureScreenshot(System.IO.Path.Combine(folderPath, screenshotName),2); // takes the sceenshot, the "2" is for the scaled resolution, you can put this to 600 but it will take really long to scale the image up
            Debug.Log(folderPath + screenshotName); // You get instant feedback in the console
        }
    }
</code>```

Body:
It's suprisingly easy, at the end you capture a screenshot off everything you see in the game view, if you want to dont show the ui, just disable the canvas for it.

    private void Update(){
        if(Input.GetMouseButtonDown(0)){ // capture screen shot on left mouse button down

            string folderPath = "Assets/Screenshots/"; // the path of your project folder

            if (!System.IO.Directory.Exists(folderPath)) // if this path does not exist yet
                System.IO.Directory.CreateDirectory(folderPath);  // it will get created

            var screenshotName =
                                    "Screenshot_" +
                                    System.DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss") + // puts the current time right into the screenshot name
                                    ".png"; // put youre favorite data format here
            ScreenCapture.CaptureScreenshot(System.IO.Path.Combine(folderPath, screenshotName),2); // takes the sceenshot, the "2" is for the scaled resolution, you can put this to 600 but it will take really long to scale the image up
            Debug.Log(folderPath + screenshotName); // You get instant feedback in the console
        }
    }


问:
Freezing certain filters in pre-trained model, Tensorflow
Is it possible to load a pre-trained model, say ResNet152, and then to freeze certain weights within particular layers and fine-tune the others within those particular layer? For example:

Say, freeze 50% of filters in a particular conv layer, and fine-tune the remaining 50% in that same particular conv layer?

I can't seem to think of a solid way to implement this. I thought perhaps load the pre-trained model twice, freeze the one and allow the other to fine-tune, but then I'd need to remove filters from both branches.

答:
You can freeze the layers using layer.trainable = False (in Tensorflow or Keras). After you train your network and want to finetune it. You can use something like the following to freeze some of your weights:

```<code>for layer in model.layers[:5]: # freeze first 5 layers
    layer.trainable = False
</code>```

Docpage

Body:
You can freeze the layers using layer.trainable = False (in Tensorflow or Keras). After you train your network and want to finetune it. You can use something like the following to freeze some of your weights:

for layer in model.layers[:5]: # freeze first 5 layers
    layer.trainable = False

Docpage


问:
Flutter GetX controller not calling method when revisit the app screen
I am new to the Flutter GetX package and facing problem when using the flutter GetX package. I have several app screens where one screen for listing all the products from the database.

In my product controller, I am fetching all the data from the database and showing with listview like as given code below and It's working fine.

Problem: When I'm inserting a new record from another controller and come back to the product list controller it'll not showing newly added data. Actually this time onInit method won't fire.

Controller code

```<code>class ProductIndexCtrl extends GetxController {

    var products = [].obs;

    @override
    void onInit() {
     super.onInit();
     getAll();
    }

    void getAll() {
      Product.getAll().then((jsonList) {
        products.value = Product.fromJsonList(jsonList);
      });
    }
}

class ProductCreateCtrl extends GetxController {

     void saveData(Product product) {
        ...
        ...

        //after successful insert
        Get.toNamed('productIndex');

     }

}
</code>```

Product index screen

```<code>final ctrl = Get.put(ProductIndexCtrl());

GetX<ProductIndexCtrl>(builder: (controller) {
    return _listview(controller.products);
}

Widget _listview(data) {
    ...
    ...
}
</code>```

答:
By returning to that page, you can return the new information locally to the previous page

> Controller code

```<code>class ProductIndexCtrl extends GetxController {

var products = [].obs;

@override
void onInit() {
 super.onInit();
 getAll();
}

void getAll() {
  Product.getAll().then((jsonList) {
    products.value = Product.fromJsonList(jsonList);
  });
}
</code>```

}

> Product index screen

```<code>class ProductCreateCtrl extends GetxController {

 void saveData(Product product) {
    ...
    ...

    //after successful insert
    Get.back(result: product);

 }
</code>```

}

and get Data when back

```<code>Get.toName('ProductCreateCtrl').then(result){
 products.add(result);
</code>```

}

Body:
I am new to the Flutter GetX package and facing problem when using the flutter GetX package. I have several app screens where one screen for listing all the products from the database.

In my product controller, I am fetching all the data from the database and showing with listview like as given code below and It's working fine.

Problem: When I'm inserting a new record from another controller and come back to the product list controller it'll not showing newly added data. Actually this time onInit method won't fire.

Controller code

class ProductIndexCtrl extends GetxController {

    var products = [].obs;

    @override
    void onInit() {
     super.onInit();
     getAll();
    }

    void getAll() {
      Product.getAll().then((jsonList) {
        products.value = Product.fromJsonList(jsonList);
      });
    }
}

class ProductCreateCtrl extends GetxController {

     void saveData(Product product) {
        ...
        ...

        //after successful insert
        Get.toNamed('productIndex');

     }

}

Product index screen

final ctrl = Get.put(ProductIndexCtrl());

GetX<ProductIndexCtrl>(builder: (controller) {
    return _listview(controller.products);
}

Widget _listview(data) {
    ...
    ...
}

Body:
By returning to that page, you can return the new information locally to the previous page

> Controller code

class ProductIndexCtrl extends GetxController {

var products = [].obs;

@override
void onInit() {
 super.onInit();
 getAll();
}

void getAll() {
  Product.getAll().then((jsonList) {
    products.value = Product.fromJsonList(jsonList);
  });
}

}

> Product index screen

class ProductCreateCtrl extends GetxController {

 void saveData(Product product) {
    ...
    ...

    //after successful insert
    Get.back(result: product);

 }

}

and get Data when back

Get.toName('ProductCreateCtrl').then(result){
 products.add(result);

}


问:
How to use google analytics with next.js app?
I'm using styled-components with next.js so my styles need to be server-side rendered, hence how can I add google analytics to my website?

I checked next.js google analytics example but as I said my _document file is different because of using styled-components.

// _document.js

import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () => originalRenderPage({
        enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
      })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

export default MyDocument

```

答:
This Answer from a GitHub issue helped me

With React hooks :

_app.js

```<code>import { useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactGA from 'react-ga'
import Layout from '../components/Layout'

function MyApp ({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = (url, { shallow }) => {
      ReactGA.set({ page: url })
      ReactGA.pageview(url)
    }
    ReactGA.initialize('XX-XXXXXXXXX-X', { debug: false })
    ReactGA.set({ page: router.pathname })
    ReactGA.pageview(router.pathname)
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [])

  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

export default MyApp
</code>```

Credits to @RiusmaX. Cheers!!

Body:
This Answer from a GitHub issue helped me

With React hooks :

_app.js

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactGA from 'react-ga'
import Layout from '../components/Layout'

function MyApp ({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = (url, { shallow }) => {
      ReactGA.set({ page: url })
      ReactGA.pageview(url)
    }
    ReactGA.initialize('XX-XXXXXXXXX-X', { debug: false })
    ReactGA.set({ page: router.pathname })
    ReactGA.pageview(router.pathname)
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [])

  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

export default MyApp

Credits to @RiusmaX. Cheers!!


问:
Django DB, finding Categories whose Items are all in a subset
I have a two models:

```<code>class Category(models.Model):
    pass

class Item(models.Model):
    cat = models.ForeignKey(Category)
</code>```

I am trying to return all Categories for which all of that category's items belong to a given subset of item ids (fixed thanks). For example, all categories for which all of the items associated with that category have ids in the set [1,3,5].

How could this be done using Django's query syntax (as of 1.1 beta)?  Ideally, all the work should be done in the database.

答:
I've played around with this a bit.  If QuerySet.extra() accepted a "having" parameter I think it would be possible to do it in the ORM with a bit of raw SQL in the HAVING clause.  But it doesn't, so I think you'd have to write the whole query in raw SQL if you want the database doing the work.

EDIT:

This is the query that gets you part way there:

```<code>from django.db.models import Count
Category.objects.annotate(num_items=Count('item')).filter(num_items=...)
</code>```

The problem is that for the query to work, "..." needs to be a correlated subquery that looks up, for each category, the number of its items in allowed_items.  If .extra had a "having" argument, you'd do it like this:

```<code>Category.objects.annotate(num_items=Count('item')).extra(having="num_items=(SELECT COUNT(*) FROM app_item WHERE app_item.id in % AND app_item.cat_id = app_category.id)", having_params=[allowed_item_ids])
</code>```

OwnerDisplayName: Derek

ContentLicense: CC BY-SA 2.5

Body:
I have a two models:

class Category(models.Model):
    pass

class Item(models.Model):
    cat = models.ForeignKey(Category)

I am trying to return all Categories for which all of that category's items belong to a given subset of item ids (fixed thanks). For example, all categories for which all of the items associated with that category have ids in the set [1,3,5].

How could this be done using Django's query syntax (as of 1.1 beta)?  Ideally, all the work should be done in the database.

LastEditorDisplayName: Derek

Body:
I've played around with this a bit.  If QuerySet.extra() accepted a "having" parameter I think it would be possible to do it in the ORM with a bit of raw SQL in the HAVING clause.  But it doesn't, so I think you'd have to write the whole query in raw SQL if you want the database doing the work.

EDIT:

This is the query that gets you part way there:

from django.db.models import Count
Category.objects.annotate(num_items=Count('item')).filter(num_items=...)

The problem is that for the query to work, "..." needs to be a correlated subquery that looks up, for each category, the number of its items in allowed_items.  If .extra had a "having" argument, you'd do it like this:

Category.objects.annotate(num_items=Count('item')).extra(having="num_items=(SELECT COUNT(*) FROM app_item WHERE app_item.id in % AND app_item.cat_id = app_category.id)", having_params=[allowed_item_ids])

OwnerDisplayName: Carl Meyer

LastEditorDisplayName: Carl Meyer


问:
getting the user click inputs in openlayers and store in postgis
i am developing a web based application for showing the public vehicle routes using GeoServer, PostGIS and OpenLayers. what i need to do is let the user define a route by clicking on the main bus stop nodes on the map and i need to store those nodes of the route in my database. till now i have displayed the map and taken the user click inputs and got the coordinates where the user clicked. so now my problem is how to store those coordinate values in my database. i think this is where WFS-T comes in to transact the data between geoserver and the openlayers but i am not sure about it. am i suppose to use GML/KML to trasact the data.</p>

答: Yes, you are right. You can use WFS-T to edit data in PostGIS via Geoserver. Here's an example of how it works.</p>


答:
You could set data as object with keys as timeframes f.e.</p>
```<code>const [data, setData] = useState();

const TIMEFRAMES = {
  HOUR: '1h',
  HALF_HOUR: '30min',
};

const hourlyNewData = { price: 1 };

setData((prevdata) => {
  ...prevData,
  [TIMEFRAMES.HOUR]: newData,
});

const minutelyNewData = { price: 1.1 };

setData((prevData) => {
  ...prevData,
  [TIMEFRAMES.HALF_HOUR]: minutelyNewData,
});

// and to access data:
const hourlyData = data[TIMEFRAMES.HOUR];
const minutelyData = data[TIMEFRAMES.HALF_HOUR]
</code>```

Title: How to use useState to store multiple key objects?

Body:
You could set data as object with keys as timeframes f.e.

const [data, setData] = useState();

const TIMEFRAMES = {
  HOUR: '1h',
  HALF_HOUR: '30min',
};

const hourlyNewData = { price: 1 };

setData((prevdata) => {
  ...prevData,
  [TIMEFRAMES.HOUR]: newData,
});

const minutelyNewData = { price: 1.1 };

setData((prevData) => {
  ...prevData,
  [TIMEFRAMES.HALF_HOUR]: minutelyNewData,
});

// and to access data:
const hourlyData = data[TIMEFRAMES.HOUR];
const minutelyData = data[TIMEFRAMES.HALF_HOUR]


问:
What is the proper way to create a class instance with an empty dictionary and/or list?
This answer suggests I am creating my empty dictionary the correct way.

```<code>class Board:
    def __init(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()
</code>```

I create an instance of my class

```<code>b = Board()
</code>```

but when I go to call it...

```<code>b.playCard(1, cardPic)
</code>```

I get the error:

```<code>AttributeError: 'Board' object has no attribute 'lastCardsPlayedDict'
</code>```

答:
The first method needs to be __init__ not __init:

```<code>class Board:
    def __init__(self): #notice the change here
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()
</code>```

Body:
This answer suggests I am creating my empty dictionary the correct way.

class Board:
    def __init(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()

I create an instance of my class

b = Board()

but when I go to call it...

b.playCard(1, cardPic)

I get the error:

AttributeError: 'Board' object has no attribute 'lastCardsPlayedDict'

Body:
The first method needs to be __init__ not __init:

class Board:
    def __init__(self): #notice the change here
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()