问:
Convert all french accents into HTML character format
I have for example a bunch of HTML pages like this :

```<code><!DOCTYPE html>
<html>
<head><title>Table des matières</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<!-- 3,html,xhtml,charset="utf-8" -->
<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />
 <script type="text/javascript" src="./jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
$('div.caption span.id').each(function() { var result = $(this).text().replace(':','');
result=capitalizeFirstLetter(result);
$(this).text(result);
});
});
</script>
</head><body
>
<!--l. 125--><div class="crosslinks"><p class="noindent">[<a
href="chapter1.html" >next</a>] [<a
href="#tailcontent.html">tail</a>] [<a
href="/sciences/index.html" >up</a>] </p></div>
<h2 class="likechapterHead"><a
 id="x2-1000"></a>Table des matières</h2>
<div class="tableofcontents">
</code>```

But impossible to convert all french accents in these HTML pages like above the accent in
"Table des matières" with "è" appearing instead of "è".

I tried 2 things :

for i in $(ls *.html); do iconv -f iso-8859-1 -t utf8 $i > $i"_new"; mv -f $i"_new" $i; done

=> the accents are not converted

for i in $(ls *.html); do recode ..html $i; done

=> I have the following errors :

```<code>recode: section5.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section6.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section7.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section8.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section9.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: table_of_contents.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
...
</code>```

I don't know what to do to convert all these french accents ?

Has anyone got an idea or suggestion to convert all possible french accents ? I would like to use iconv, recode or sed commands.

UPDATE 1: taking a basic example, here is the message I get for a single file :

```<code>$ recode ..html table_of_contents.html
recode: table_of_contents.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
</code>```

What's wrong ?

UPDATE 2: here is the output of my original HTML pages :

$file -i index.html

$ index.html: text/x-tex; charset=iso-8859-1

and the head of the index.html :

```<code><!DOCTYPE html>
<html>
<head><title>Table des matières</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<!-- 3,html,xhtml,charset="utf-8" -->
<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />
 <script type="text/javascript" src="./jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
$('div.caption span.id').each(function() { var result = $(this).text().replace(':','');
result=capitalizeFirstLetter(result);
$(this).text(result);
</code>```

If I apply the command :

```<code>$ recode -vfd u8..html index.html

Request: UTF-8..:libiconv:..ISO-10646-UCS-2..HTML_4.0
Shrunk to: UTF-8..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
</code>```

and

```<code><!DOCTYPE html>
<html>
<head><title>Table des matires</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<!-- 3,html,xhtml,charset="utf-8" -->
<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />
 <script type="text/javascript" src="./jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
$('div.caption span.id').each(function() { var result = $(this).text().replace(':','');
result=capitalizeFirstLetter(result);
$(this).text(result);
});
});
</script>
</code>```

as you can see, the "è" has disappeared.

What can I do ?

答:
Assuming the source file encoding is UTF-8. Following command worked in my environment:

```<code>$ recode -vfd u8..html index.html
</code>```

Output:

```<code>$ locale charmap
UTF-8

$ file -i index.html
index.html: text/html; charset=utf-8

$ recode -vfd u8..html index.html
Request: UTF-8..:iconv:..ISO-10646-UCS-2..HTML_4.0
Shrunk to: UTF-8..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
</code>```

You can use the command options to debug the error in this way:

-v Verbose output. Useful to find in which step the error occurred.

-f Forces the completion even if error occurred. You can compare the output file with original to figure out which character/location is giving trouble.

-d For HTML, recode doesn't convert ASCII characters. Avoids conversion of < > " & etc. html characters.

Update If the encoding/charset is iso-8859-1 then you need to use:

```<code>$ recode -vfd iso-8859-1..html index.html
Request: ISO-8859-1..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done

#Or use following.

$ recode -vfd lat1..html index.html
Request: ISO-8859-1..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
</code>```

The ISO-8859-1 has following aliases in recode:

```<code>l1
lat1
latin1
Latin-1
819/CR-LF
CP819/CR-LF
CSISOLATIN1
IBM819/CR-LF
ISO8859-1
iso-ir-100
ISO_8859-1
ISO_8859-1:1987
</code>```

You can use anyone of the above in the command.

Body:
I have for example a bunch of HTML pages like this :

<!DOCTYPE html>

<title>Table des matières</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />

<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />

[next] [tail] [up]

Table des matières

But impossible to convert all french accents in these HTML pages like above the accent in
"Table des matières" with "è" appearing instead of "è".

I tried 2 things :

for i in $(ls *.html); do iconv -f iso-8859-1 -t utf8 $i > $i"_new"; mv -f $i"_new" $i; done

=> the accents are not converted

for i in $(ls *.html); do recode ..html $i; done

=> I have the following errors :

recode: section5.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section6.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section7.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section8.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section9.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: table_of_contents.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
...

I don't know what to do to convert all these french accents ?

Has anyone got an idea or suggestion to convert all possible french accents ? I would like to use iconv, recode or sed commands.

UPDATE 1: taking a basic example, here is the message I get for a single file :

$ recode ..html table_of_contents.html
recode: table_of_contents.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'

What's wrong ?

UPDATE 2: here is the output of my original HTML pages :

$file -i index.html

$ index.html: text/x-tex; charset=iso-8859-1

and the head of the index.html :

<!DOCTYPE html>

<title>Table des matières</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />

<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />

as you can see, the "è" has disappeared.

What can I do ?

Body:
Assuming the source file encoding is UTF-8. Following command worked in my environment:

$ recode -vfd u8..html index.html

Output:

$ locale charmap
UTF-8

$ file -i index.html
index.html: text/html; charset=utf-8

$ recode -vfd u8..html index.html
Request: UTF-8..:iconv:..ISO-10646-UCS-2..HTML_4.0
Shrunk to: UTF-8..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done

You can use the command options to debug the error in this way:

-v Verbose output. Useful to find in which step the error occurred.

-f Forces the completion even if error occurred. You can compare the output file with original to figure out which character/location is giving trouble.

-d For HTML, recode doesn't convert ASCII characters. Avoids conversion of < > " & etc. html characters.

Update If the encoding/charset is iso-8859-1 then you need to use:

$ recode -vfd iso-8859-1..html index.html
Request: ISO-8859-1..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done

#Or use following.

$ recode -vfd lat1..html index.html
Request: ISO-8859-1..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done

The ISO-8859-1 has following aliases in recode:

l1
lat1
latin1
Latin-1
819/CR-LF
CP819/CR-LF
CSISOLATIN1
IBM819/CR-LF
ISO8859-1
iso-ir-100
ISO_8859-1
ISO_8859-1:1987

You can use anyone of the above in the command.


来源: stackexchange

问:
How can I stop the time from displaying in a GridView when displaying a date?
I have a web application that I am working on(ASP.NET 2.0 & C#). In it, I have a gridview that gets data from an Oracle Database. Some of the data that I need to display is dates. But when the dates in my gridview show like this:

2009-04-02 00:00:00

I'd prefer they show without the time. I'm using the codebehind to get the data, so I cant alter the fields of the gridview manually. This is all the code for my gridview :

```<code><asp:GridView ID="Grid" runat="server" EmptyDataText="There are no data records to display." ></asp:GridView>
</code>```

How do I stop the time from displaying?

答:
You can apply a dataformatstring in the gridview column to only show the date.

To get it to work you must make sure that HTMLEncode is set to false.

More information

OwnerDisplayName: zohair

ContentLicense: CC BY-SA 2.5

Body:
I have a web application that I am working on(ASP.NET 2.0 & C#). In it, I have a gridview that gets data from an Oracle Database. Some of the data that I need to display is dates. But when the dates in my gridview show like this:

2009-04-02 00:00:00

I'd prefer they show without the time. I'm using the codebehind to get the data, so I cant alter the fields of the gridview manually. This is all the code for my gridview :

<asp:GridView ID="Grid" runat="server" EmptyDataText="There are no data records to display." ></asp:GridView>

How do I stop the time from displaying?

LastEditorDisplayName: Rich B

OwnerDisplayName: TheTXI

LastEditorDisplayName: TheTXI


问:
Opening a downloaded mht file from Selenium (Help needed)
Long story short, I'm not a coder.
My team used to have this coder who created this Python/Selenium code to extract some information from chrome browser (Echocardiography reports) and/or downloaded mht file (also Echocardiography reports).

This code was working fine until recently, it stopped working.
The program still successfully downloads the mht file via chrome.
However,  it fails to open the file and hence, code continues without extracting any information - resulting in empty extractions.

This is the part I need help figuring out

```<code>                driver.get('chrome://downloads')
                # driver.get('file:///C:/Users/name/Downloads/')

                root1 = driver.find_element_by_tag_name('downloads-manager')
                shadow_root1 = expand_shadow_element(root1)

                time.sleep(2)

                root2 = shadow_root1.find_element_by_css_selector('downloads-item')
                shadow_root2 = expand_shadow_element(root2)

                time.sleep(1.5)

                openEchoFileButton = shadow_root2.find_element_by_id('file-link')
                mhtFileName = openEchoFileButton.text

                driver.get('file:///C:/Users/name/Downloads/' + mhtFileName)  # go to web page
                try:
                    echoDateElement = WebDriverWait(driver, delay).until(
                        EC.presence_of_element_located((By.XPATH, '/html/body/div[3]/p[1]/span[3]')))
                except TimeoutException:
                    print("Loading page took too much time!")
</code>```

I'm trying to figure out why it suddenly fails to open the downloaded mht files.
Last time our team tried using this code is back in 2020 and was successful.
Were there any updates to Chrome perhaps?

Help would be immensely appreciated.
Thank you so much in advance.

答: There are three obvious weaknesses in this code.  The first two are the use of time.sleep() to wait for the element to appear and be manipulable.  What if the machine is busy doing something else, and 1.5 seconds isn't enough?  The right way to do that is to repeatedly check for the element to be ready.  You've got a great example of how to do that using WebDriverWait() in this code already.  The third weakness is the locator used in that presence_of_element_located() call.  XPath locators rooted at "/html" are notoriously fragile, subject to breakage by small changes to the web page.  Try to find something in the page that you can check via a more stable locator - ideally, an element with an ID= attribute.</p>

ContentLicense: CC BY-SA 4.0

Body:
Long story short, I'm not a coder.
My team used to have this coder who created this Python/Selenium code to extract some information from chrome browser (Echocardiography reports) and/or downloaded mht file (also Echocardiography reports).

This code was working fine until recently, it stopped working.
The program still successfully downloads the mht file via chrome.
However,  it fails to open the file and hence, code continues without extracting any information - resulting in empty extractions.

This is the part I need help figuring out

                driver.get('chrome://downloads')
                # driver.get('file:///C:/Users/name/Downloads/')

                root1 = driver.find_element_by_tag_name('downloads-manager')
                shadow_root1 = expand_shadow_element(root1)

                time.sleep(2)

                root2 = shadow_root1.find_element_by_css_selector('downloads-item')
                shadow_root2 = expand_shadow_element(root2)

                time.sleep(1.5)

                openEchoFileButton = shadow_root2.find_element_by_id('file-link')
                mhtFileName = openEchoFileButton.text

                driver.get('file:///C:/Users/name/Downloads/' + mhtFileName)  # go to web page
                try:
                    echoDateElement = WebDriverWait(driver, delay).until(
                        EC.presence_of_element_located((By.XPATH, '/html/body/div[3]/p[1]/span[3]')))
                except TimeoutException:
                    print("Loading page took too much time!")

I'm trying to figure out why it suddenly fails to open the downloaded mht files.
Last time our team tried using this code is back in 2020 and was successful.
Were there any updates to Chrome perhaps?

Help would be immensely appreciated.
Thank you so much in advance.


问:
ASP.NET Core routes GET call to DELETE method
I have an ASP.NET Core web API controller with (among others) two methods that have the same signature.

Shortened down, this looks as follows:

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}", Order = 2)]
    [Route("{*id}", Order = 2)]
    public MyObject Load([FromUri] String id) => new MyObject();

    [HttpDelete("{*id}", Order = 1)]
    [Route("{*id}", Order = 1)]
    public void Delete([FromUri] String id)
    {
    }
}
```

Now, I am issuing a call:

GET my/route/123/456

Shockingly, this call ends up in the Delete method. I literally have a breapoint in the first line of my (in real life, non-empty) Delete method, and the Immediate window in VS tells me HttpContext.Request.Method is "GET", yet I end up in the method explicitly marked as HttpDelete.

What is going on here? Luckily, my call happened from within an automated test to test the web API, but if someone had issued that call to retrieve actual data from the DB, they would have ended up deleting that data instead. Is there any misunderstanding on my side with respect to the [HttpDelete] attribute?

答:
You don't have to use route attribute and order parameter. It might be cause this situation.</p>
```<code>[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}")]
    public MyObject Load([FromUri] String id) => new MyObject();

    [HttpDelete("{*id}")]
    public void Delete([FromUri] String id)
    {
    }
}
</code>```

Body:
I have an ASP.NET Core web API controller with (among others) two methods that have the same signature.

Shortened down, this looks as follows:

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}", Order = 2)]
    [Route("{*id}", Order = 2)]
    public MyObject Load([FromUri] String id) => new MyObject();

    [HttpDelete("{*id}", Order = 1)]
    [Route("{*id}", Order = 1)]
    public void Delete([FromUri] String id)
    {
    }
}

Now, I am issuing a call:

GET my/route/123/456

Shockingly, this call ends up in the Delete method. I literally have a breapoint in the first line of my (in real life, non-empty) Delete method, and the Immediate window in VS tells me HttpContext.Request.Method is "GET", yet I end up in the method explicitly marked as HttpDelete.

What is going on here? Luckily, my call happened from within an automated test to test the web API, but if someone had issued that call to retrieve actual data from the DB, they would have ended up deleting that data instead. Is there any misunderstanding on my side with respect to the [HttpDelete] attribute?

Body:
You don't have to use route attribute and order parameter. It might be cause this situation.

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}")]
    public MyObject Load([FromUri] String id) => new MyObject();

    [HttpDelete("{*id}")]
    public void Delete([FromUri] String id)
    {
    }
}


问:
Kafka consumer - how does rebalance work if one consumer fails
I'm using AWS Kafka MSK and I have a topic with 2 partitions.
I also have a 2 consumers which are part of the same consumer group.

I'm wondering that will happen in the following case:

Consumer A - took messages 1 - 100

Consumer B - took messages 101 - 200

Consumer A failed

Consumer B succeeded

What happens to the messages 1 - 100?

Will the auto Kafka rebalance set consumer B to read messages 1 - 100?
or the new consumer that will startup instead of Consumer A will read the messages?

Thanks in advance.

答:
Offset ranges are for partitions, not topics.

This scenario is not possible for a fresh consumer application unless one of the following is true

Offsets 0-100 of the partition assigned to consumer B have been removed due to retention

Your code calls seek method to skip those offsets

On the other hand, if the consumer group already existed and consumed none of the records of partition assigned to consumer A (say, it had failed before), and did commit offset 100 of the other partition. In this case, perhaps the same thing would happen; the consumer group might fail reading offset 0 of the "first" partition.

When any consumer instance fails, the group will rebalance. Depending on how you handle errors/failures, the previously healthy instance may then be assigned both partitions, and then fail consuming the "first" partition again (since it'll be the same code that died previously). Or, writing code differently, you'll ignore consumer exceptions and optionally mark bad offsets in a dead-letter queue. When logged or ignored, you'd commit offsets for the original consumer and skip those records.


问:
how to change the category code in a category column in pandas
I have a csv that I am reading using pandas.

In the csv, I have a column that has the following values:

```<code>x<1
1<x<2
2<x<3
3<x<4
x<4
</code>```

when I convert them to category and then use category code, I am getting something such as this for category codes

```<code>{
x<1:2
1<x<2:1
2<x<3:3
3<x<4:4
x<4:0
}
</code>```

but I need the code to be as follow:

```<code>{
x<1:0
1<x<2:1
2<x<3:2
3<x<4:3
x<4:4
}
</code>```

How can I change the category code without changing the dataframe?

I used the following code to convert the column to category:

```<code>df['col'] = df['col'].astype('category')
</code>```

答:
You can use pd.api.types.CategoricalDtype to change the category code follows:

Code:

import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'col': ['x<1', '1<x<2', '2<x<3', '3<x<4', 'x<4']})
df['col'] = df['col'].astype('category')

# Get the current category order
category_order1 = df.col.cat.categories.to_list()
print('category_order_1:', category_order1)

# Invert the category order
co = category_order1[::-1]
df['col'] = df['col'].astype(pd.api.types.CategoricalDtype(categories=co, ordered=True))

# Get the current category order
category_order2 = df.col.cat.categories.to_list()
print('category_order_2:', category_order2)

# Define and apply arbitrary category order
co = ['2<x<3', 'x<4', 'x<1', '3<x<4', '1<x<2']
df['col'] = df['col'].astype(pd.api.types.CategoricalDtype(categories=co, ordered=True))

# Get the current category order
category_order3 = df.col.cat.categories.to_list()
print('category_order_3:', category_order3)
```
<h2>Output:</h2>
```category_order_1: ['1<x<2', '2<x<3', '3<x<4', 'x<1', 'x<4']
category_order_2: ['x<4', 'x<1', '3<x<4', '2<x<3', '1<x<2']
category_order_3: ['2<x<3', 'x<4', 'x<1', '3<x<4', '1<x<2']
```

Body:
I have a csv that I am reading using pandas.

In the csv, I have a column that has the following values:

x<1
1<x<2
2<x<3
3<x<4
x<4

when I convert them to category and then use category code, I am getting something such as this for category codes

{
x<1:2
1<x<2:1
2<x<3:3
3<x<4:4
x<4:0
}

but I need the code to be as follow:

{
x<1:0
1<x<2:1
2<x<3:2
3<x<4:3
x<4:4
}

How can I change the category code without changing the dataframe?

I used the following code to convert the column to category:

df['col'] = df['col'].astype('category')

Body:
You can use pd.api.types.CategoricalDtype to change the category code follows:

Code:

import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'col': ['x<1', '1<x<2', '2<x<3', '3<x<4', 'x<4']})
df['col'] = df['col'].astype('category')

# Get the current category order
category_order1 = df.col.cat.categories.to_list()
print('category_order_1:', category_order1)

# Invert the category order
co = category_order1[::-1]
df['col'] = df['col'].astype(pd.api.types.CategoricalDtype(categories=co, ordered=True))

# Get the current category order
category_order2 = df.col.cat.categories.to_list()
print('category_order_2:', category_order2)

# Define and apply arbitrary category order
co = ['2<x<3', 'x<4', 'x<1', '3<x<4', '1<x<2']
df['col'] = df['col'].astype(pd.api.types.CategoricalDtype(categories=co, ordered=True))

# Get the current category order
category_order3 = df.col.cat.categories.to_list()
print('category_order_3:', category_order3)

Output:

category_order_1: ['1<x<2', '2<x<3', '3<x<4', 'x<1', 'x<4']
category_order_2: ['x<4', 'x<1', '3<x<4', '2<x<3', '1<x<2']
category_order_3: ['2<x<3', 'x<4', 'x<1', '3<x<4', '1<x<2']


问:
useState react error Too many re-renders mergin state props input
I am having problems with updating state by mergin selected input props in one string in order to pass a proper path with values to API.

I have something like this in logic :

```<code>    const [data, setData] = useState({ certificate: '', year: '' })

    const merge = () =>{if(data.certificate!==''){(setData(Object.values(data).join("")))}}
      merge()

  useEffect(() => {
    (async () => {
      try {
        const params = {
          data,
        }
        const result = await service.getBackendData({ params})

        if (result.error) throw result.error

        setList(result)
      } catch ({ message }) {
        console.error('error', message)
      }
    })()
  }, [data])
</code>```

The purpose of the code is to get two strings values from the form component (I am using Formik) and this actually works just fine.
But then, two values inside the state (certificate and year props) must be merged in one string in order to send a proper path to API and get response.

useEffect part also works, if i use values separetely, but in this particular matter i must find a way to connect these two above in one string.

I tried to create a merge function under condition that user select and thus pass a certificate value, but that only delayed a render error. After the value is selected, function ofcourse works and join two values, but an infitie loop is created.

I read that changing state in a rendering phase is not a good idea (to put it mildly), so i cannot do this in that way.
So far i run out of ideas. What I am missing ?

Below the part of the Form code, concerning these values. While clicking, user pass from selected options a certificate value, and then i must merge it with year value in one string.

```<code>  const initialValue = {
    CERTIFICATE: '',
    YEAR: '&0',
  }
                     <S.CustomSelect
                      name={certificateInput.certificate.name}
                      placeholder={certificateInput.certificate.placeholder}
                      onClick={setData((prevState) => ({
                        ...prevState,
                        certificate: values.CERTIFICATE,
                      }))}
                    >
                      {certificatesValues.map((item) => (
                        <Option key={item.name} value={item.symbol}>
                          {item.name}
                        </Option>
                      ))}
                    </S.CustomSelect>
</code>```

答:
Your issue is in below part

```<code>const merge = () =>{if(data.certificate!==''){(setData(Object.values(data).join("")))}}
merge()
</code>```

You are calling merge() on the rendering part

I think you can fix this issue by moving merge() to useEffect

```<code>const [data, setData] = useState({ certificate: '', year: '' })

useEffect(() => {
    (async () => {
      let params = data
      if(data.certificate!==''){params = Object.values(data).join(""))}
      try {
        result = await service.getBackendData(params);

        if (result.error) throw result.error

        setList(result)
      } catch ({ message }) {
        console.error('error', message)
      }
    })()
  }, [data])
</code>```

Body:
I am having problems with updating state by mergin selected input props in one string in order to pass a proper path with values to API.

I have something like this in logic :

    const [data, setData] = useState({ certificate: '', year: '' })

    const merge = () =>{if(data.certificate!==''){(setData(Object.values(data).join("")))}}
      merge()

  useEffect(() => {
    (async () => {
      try {
        const params = {
          data,
        }
        const result = await service.getBackendData({ params})

        if (result.error) throw result.error

        setList(result)
      } catch ({ message }) {
        console.error('error', message)
      }
    })()
  }, [data])

The purpose of the code is to get two strings values from the form component (I am using Formik) and this actually works just fine.
But then, two values inside the state (certificate and year props) must be merged in one string in order to send a proper path to API and get response.

useEffect part also works, if i use values separetely, but in this particular matter i must find a way to connect these two above in one string.

I tried to create a merge function under condition that user select and thus pass a certificate value, but that only delayed a render error. After the value is selected, function ofcourse works and join two values, but an infitie loop is created.

I read that changing state in a rendering phase is not a good idea (to put it mildly), so i cannot do this in that way.
So far i run out of ideas. What I am missing ?

Below the part of the Form code, concerning these values. While clicking, user pass from selected options a certificate value, and then i must merge it with year value in one string.

  const initialValue = {
    CERTIFICATE: '',
    YEAR: '&0',
  }
                     <S.CustomSelect
                      name={certificateInput.certificate.name}
                      placeholder={certificateInput.certificate.placeholder}
                      onClick={setData((prevState) => ({
                        ...prevState,
                        certificate: values.CERTIFICATE,
                      }))}
                    >
                      {certificatesValues.map((item) => (
                        <Option key={item.name} value={item.symbol}>
                          {item.name}
                        </Option>
                      ))}
                    </S.CustomSelect>

Body:
Your issue is in below part

const merge = () =>{if(data.certificate!==''){(setData(Object.values(data).join("")))}}
merge()

You are calling merge() on the rendering part

I think you can fix this issue by moving merge() to useEffect

const [data, setData] = useState({ certificate: '', year: '' })

useEffect(() => {
    (async () => {
      let params = data
      if(data.certificate!==''){params = Object.values(data).join(""))}
      try {
        result = await service.getBackendData(params);

        if (result.error) throw result.error

        setList(result)
      } catch ({ message }) {
        console.error('error', message)
      }
    })()
  }, [data])


问:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
I have the following code:

```<code>class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}
</code>```

I know Thing does nothing, but my Hello, World program compiles just fine without it. It's only my defined classes that are failing on me.

And it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either:

I have system level problems (either in DrJava or my Java install) or

I have some basic misunderstanding of how to construct a working program in java.

Any ideas?

答: In my case it was because of one extra '}'</p>

Body:
I have the following code:

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}

I know Thing does nothing, but my Hello, World program compiles just fine without it. It's only my defined classes that are failing on me.

And it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either:

I have system level problems (either in DrJava or my Java install) or

I have some basic misunderstanding of how to construct a working program in java.

Any ideas?


问:
How to paginate and listen to the data and cancel unnecessary listeners in flutter effectively?
Imagine I am trying to get an infinite scrolling similar to that of Instagram by paginating the post and I will also be listening to the post detail changes for each post that have been queried.

I start off by querying the first 10 posts:

```<code>void getPosts(){
postStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

</code>```

As the user scrolls down, I detect the scroll with the listener and query for more posts

```<code>void getMorePosts(){
paginatedPostStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .startAfterDocument(lastPostDocSnapshot)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}
</code>```

When the user no longer needs these post, I'll cancel the stream in the following way:

```<code>postStream.cancel();
paginatedPostStream.cancel();
</code>```

However, I realized that doing so only stopped listening to the earliest and latest paginated stream. For example, the user may have queried in the following way

```<code>10 | 10 | 10 | 10 | 10
^                   ^
</code>```

but the canceling of stream only applies for the first and last 10 posts queried. How can I more effectively cancel the listener to prevent data leakage?

Any suggestion is welcomed. Thank you.

答:
As discussed in the comments, you will need to manage all streams instead of just the first and last one. If you want to limit the resources being consumed, you will need to close each stream as it becomes obsolete.

There is no single best practice here, but most implementation I know of, implement a virtual window of few (say 3-5) screens full of information. So if in your case you can display 10 documents on the screen at once, you'd keep listeners on 3-5 streams of 10 documents: the information that is currently displayed and 1 or 2 screenfull's up and down. Any stream outside of this virtual window can then be cancelled to reduce resource consumption.

Body:
Imagine I am trying to get an infinite scrolling similar to that of Instagram by paginating the post and I will also be listening to the post detail changes for each post that have been queried.

I start off by querying the first 10 posts:

void getPosts(){
postStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

As the user scrolls down, I detect the scroll with the listener and query for more posts

void getMorePosts(){
paginatedPostStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .startAfterDocument(lastPostDocSnapshot)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

When the user no longer needs these post, I'll cancel the stream in the following way:

postStream.cancel();
paginatedPostStream.cancel();

However, I realized that doing so only stopped listening to the earliest and latest paginated stream. For example, the user may have queried in the following way

10 | 10 | 10 | 10 | 10
^                   ^

but the canceling of stream only applies for the first and last 10 posts queried. How can I more effectively cancel the listener to prevent data leakage?

Any suggestion is welcomed. Thank you.


问:
yarn command not found after installing via npm
As per the yarn installation for yarn v2, they want you to install using npm install -g yarn.  So I ran sudo npm install -g yarn on Ubuntu 20.04.  But after I do that, it says command not found.

```<code>❯ sudo npm install -g yarn

> yarn@1.22.10 preinstall /usr/local/lib/node_modules/yarn
> :; (node ./preinstall.js > /dev/null 2>&1 || true)

❯ yarn --version
zsh: command not found: yarn
</code>```

答:
I recently had a similar situation and here is how I solved it.

First I troubleshoot the current npm installation:

```<code>npm config -list
</code>```

I had a ~/.npmrc file that had a different prefix:

```<code>PREFIX=/opt/homebrew
</code>```

That made my npm installation look for globally installed packages under /opt/homebrew.

In my case, I'm using a different npm installation (not with homebrew anymore). A simple fix is to remove this custom PREFIX from the ~/.npmrc file and the problem was solved.

Now npm looks for globally installed packages under /usr/local/bin/.

Body:
As per the yarn installation for yarn v2, they want you to install using npm install -g yarn.  So I ran sudo npm install -g yarn on Ubuntu 20.04.  But after I do that, it says command not found.

❯ sudo npm install -g yarn

> yarn@1.22.10 preinstall /usr/local/lib/node_modules/yarn
> :; (node ./preinstall.js > /dev/null 2>&1 || true)

❯ yarn --version
zsh: command not found: yarn

Body:
I recently had a similar situation and here is how I solved it.

First I troubleshoot the current npm installation:

npm config -list

I had a ~/.npmrc file that had a different prefix:

PREFIX=/opt/homebrew

That made my npm installation look for globally installed packages under /opt/homebrew.

In my case, I'm using a different npm installation (not with homebrew anymore). A simple fix is to remove this custom PREFIX from the ~/.npmrc file and the problem was solved.

Now npm looks for globally installed packages under /usr/local/bin/.


问:
For loop inside for loop for generating strings
I have the following code generating an image url based on an array of objects and their properties:

```<code>for (let s = 0; s < amount; s++) {
   console.log(projects[s].imagelocation + projects[s].images[0]);
}
</code>```

As an example this gives me the following output:

```<code>img/EnergyGoStix-assets/GoStix1.jpg
img/Premier-assets/PremierStudios1.jpg
img/Quickstix-assets/QuickStix1.jpg
img/MotherMonster-assets/MotherMonster1.jpg
img/Stepping-assets/SteppingBooklet1.jpg
</code>```

However, the images property is actually an array. This array contains multiple image sources such as GoStix1.jpg, GoStix2.jpg, etc. This number of image sources varies between the projects.

How do I create a loop within a loop that would incorporate images.length where it will first go through each project and generate all image sources, prior to moving onto the next one?

P.S - Sorry for the terrible post title, had no idea what to call this. If anyone can come up with a better one to help be more precise, please let me know so I can update it.

答:
Just nest the loops, and be careful to use different variable names in the initialization of each.</p>
```<code>for (let s = 0; s < amount; s++) {
  for (let i = 0; i < projects[s].images.length; i++) {
    console.log(projects[s].imagelocation + projects[s].images[i]);
  }
}
</code>```

Body:
I have the following code generating an image url based on an array of objects and their properties:

for (let s = 0; s < amount; s++) {
   console.log(projects[s].imagelocation + projects[s].images[0]);
}

As an example this gives me the following output:

img/EnergyGoStix-assets/GoStix1.jpg
img/Premier-assets/PremierStudios1.jpg
img/Quickstix-assets/QuickStix1.jpg
img/MotherMonster-assets/MotherMonster1.jpg
img/Stepping-assets/SteppingBooklet1.jpg

However, the images property is actually an array. This array contains multiple image sources such as GoStix1.jpg, GoStix2.jpg, etc. This number of image sources varies between the projects.

How do I create a loop within a loop that would incorporate images.length where it will first go through each project and generate all image sources, prior to moving onto the next one?

P.S - Sorry for the terrible post title, had no idea what to call this. If anyone can come up with a better one to help be more precise, please let me know so I can update it.

Body:
Just nest the loops, and be careful to use different variable names in the initialization of each.

for (let s = 0; s < amount; s++) {
  for (let i = 0; i < projects[s].images.length; i++) {
    console.log(projects[s].imagelocation + projects[s].images[i]);
  }
}


问:
What the heck is this: background-image: url("/images/sprites.png?v=3");

Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

```<code>/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }
</code>```

I've seen this used on link tags also on http://html5boilerplate.com/:

```<code>   <link rel="stylesheet" href="css/style.css?v=2">
</code>```

答:
The query string helps to invalidate the browser cache when the image itself is changed.
Context: Usually you want to define long cache expiration date for static resources such as an image, so that browser don't download the image every time they visit the website. However, if the website owner wants to change the image he would need to wait a long time, until the image expires in all of the visitor's browser caches.
Since he has the query string attached, the website owner can increment the number, when the image has been changed. When the new css file is uploaded, all visitors will see the new image, because it is referenced through a new URL that has not been cached yet.</p>

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }

I've seen this used on link tags also on http://html5boilerplate.com/:

   <link rel="stylesheet" href="css/style.css?v=2">


问:
How to calculate the SUM of time in hh:mi format in pandas dataframe
I have a pandas data frame like this:

how can i calculate the SUM of total time per group? the time format is in HH:MI.
for example for G1 we've total (01:30+02:30+05:30)=09:30.
I've checked many solutions like separating each item via ":" by for loop or multiplying it *60 but no success.

答:
You can convert each value to Timedelta than sum them:

```<code>df['SUM'] = pd.to_timedelta(df['HOURS'].str.split(',').explode() + [':00']) \
              .groupby(level=0).sum()
print(df)

# Output
  GROUP              HOURS             SUM
0    G1  01:30,02:30,05:30 0 days 09:30:00
1    G2  02:30,05:30,07:30 0 days 15:30:00
</code>```

Body:
You can convert each value to Timedelta than sum them:

df['SUM'] = pd.to_timedelta(df['HOURS'].str.split(',').explode() + [':00']) \
              .groupby(level=0).sum()
print(df)

# Output
  GROUP              HOURS             SUM
0    G1  01:30,02:30,05:30 0 days 09:30:00
1    G2  02:30,05:30,07:30 0 days 15:30:00


问:
Checking the equality of lists of Comparable objects in Groovy
I'm writing a test using the Spock framework and I found a strange bavior when testing equality of lists.

When I compare two lists like

```<code>sourceList == targetList
</code>```

and those lists contains Comparable objects of the same type, those objects are tested for equality using its compareTo methods instead of equals.

Is there any simple way how to force Groovy to use equals when testing equality on such lists?

Here is a simple test specification where the test should fail, but it does not.

```<code>class Test extends Specification {

def "list test"() {
    when:
        def listA = [[index: 1, text: "1"] as Bean, [index: 2, text: "2"] as Bean]
        def listB = [[index: 1, text: "1"] as Bean, [index: 2, text: "3"] as Bean]

    then:
        listA == listB
}

class Bean implements Comparable<Bean> {

    int index
    String text

    @Override
    public int compareTo(Bean o) {
        return index.compareTo(o.index);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + index;
        result = prime * result + ((text == null) ? 0 : text.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Bean)) {
            return false;
        }
        Bean other = (Bean) obj;
        if (index != other.index) {
            return false;
        }
        if (text == null) {
            if (other.text != null) {
                return false;
            }
        } else if (!text.equals(other.text)) {
            return false;
        }
        return true;
    }

}

}
</code>```

答:
In groovy, "==" is replaced with equals if items are not comparable, or with compareTo if they implement Comparable. I do not know a simple way to force equals, if the collections have no duplicates, you can check the elements of the collection one by one:

```<code>def collectionsEqual (Collection<?> collection1, Collection<?> collection2) {
     if (collection1.size() != collection2.size()) {
         return false
     }
     for (elem1 in collection1) {
         def founded = false;
         for (elem2 in collection2) {
             if (elem1?.equals (elem2)) {
                 founded = true
             }
         }
         if (!founded) {
            return false
         }
     }
     true
}
</code>```

but, in https://www.baeldung.com/java-compareto we have:

It is also strongly recommended, though not required, to keep the
compareTo implementation consistent with the equals method
implementation:

x.compareTo(y) == 0 should have the same boolean value as x.equals(y)
This will ensure that we can safely use objects in sorted sets and
sorted maps.

Body:
I'm writing a test using the Spock framework and I found a strange bavior when testing equality of lists.

When I compare two lists like

sourceList == targetList

and those lists contains Comparable objects of the same type, those objects are tested for equality using its compareTo methods instead of equals.

Is there any simple way how to force Groovy to use equals when testing equality on such lists?

Here is a simple test specification where the test should fail, but it does not.

class Test extends Specification {

def "list test"() {
    when:
        def listA = [[index: 1, text: "1"] as Bean, [index: 2, text: "2"] as Bean]
        def listB = [[index: 1, text: "1"] as Bean, [index: 2, text: "3"] as Bean]

    then:
        listA == listB
}

class Bean implements Comparable<Bean> {

    int index
    String text

    @Override
    public int compareTo(Bean o) {
        return index.compareTo(o.index);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + index;
        result = prime * result + ((text == null) ? 0 : text.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Bean)) {
            return false;
        }
        Bean other = (Bean) obj;
        if (index != other.index) {
            return false;
        }
        if (text == null) {
            if (other.text != null) {
                return false;
            }
        } else if (!text.equals(other.text)) {
            return false;
        }
        return true;
    }

}

}

Body:
In groovy, "==" is replaced with equals if items are not comparable, or with compareTo if they implement Comparable. I do not know a simple way to force equals, if the collections have no duplicates, you can check the elements of the collection one by one:

def collectionsEqual (Collection<?> collection1, Collection<?> collection2) {
     if (collection1.size() != collection2.size()) {
         return false
     }
     for (elem1 in collection1) {
         def founded = false;
         for (elem2 in collection2) {
             if (elem1?.equals (elem2)) {
                 founded = true
             }
         }
         if (!founded) {
            return false
         }
     }
     true
}

but, in https://www.baeldung.com/java-compareto we have:

It is also strongly recommended, though not required, to keep the
compareTo implementation consistent with the equals method
implementation:

x.compareTo(y) == 0 should have the same boolean value as x.equals(y)
This will ensure that we can safely use objects in sorted sets and
sorted maps.


问:
How to scure my APIs on c#.net the best practice
I have built APIs on c#.Net

these APIs works fine, but they are not secure, which means anyone worldwide can use it

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;

namespace CDAPIs.Controllers
{
    public class CallSPController : ApiController
    {

        [Route("api/CallSP")]
        public string Get(string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
        {
            string sDBConn = Functions.GetConn();
            string[] Parms = Ps.Split(',');
            SqlConnection conn = new SqlConnection(sDBConn);
            SqlCommand cmd = new SqlCommand(SP, conn);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.StoredProcedure;

            string P = "";
            for (int i = 0; i < Parms.Length; i++)
            {
                if (i == 0) { P = P0; }
                if (i == 1) { P = P1; }
                if (i == 2) { P = P2; }
                if (i == 3) { P = P3; }
                cmd.Parameters.Add(new SqlParameter("@" + Parms[i].Trim(), P));
            }

            try
            {
                conn.Open();

                if (Type.ToUpper().Trim() == "STRING")
                {
                    string st = cmd.ExecuteScalar().ToString();
                    conn.Close();
                    conn.Dispose();
                    return st;
                }
                else
                {
                    SqlDataReader rdr = cmd.ExecuteReader();
                    var dt = new DataTable();
                    dt.Load(rdr);
                    List<DataRow> result = dt.AsEnumerable().ToList();
                    rdr.Close();
                    conn.Close();
                    conn.Dispose();
                    string json = Functions.DataTableToJSON(dt);
                    //return Json(result, JsonRequestBehavior.AllowGet);
                    return json;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
</code>```

I want to protect these APIs and I would like to how to do that properly

I thought of adding UserID and Password to each API so the use send them as parameters

so it will be like this

```<code>    [Route("api/CallSP")]
    public string Get(string UserID, string Password, string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
    {
</code>```

Is there a better solution?

答:
Your user should authenticate once and then reuse the connection. You should have a login action that would take a username and a password, generate a session id or something of the like and send that back to the client. The client from there on should use the session ID to authenticate and your server should be aware of session IDs.

Because, if for some reason a session ID is stolen, then the user might be temporarily impersonated by a hacker, but, if the user's credentials are stolen, then the user might be locked out from his/her account for good.

So:

a session ID should be temporary, that is, after a week (or the period of your preference) expires, your app should no longer trust the old session id and require authentication again

all the requests need to be encrypted

at password/username change your app should not be satisfied by the session ID/token alone, but should ask for proper authentication as well

it would be good if your app would have a communication channel with the user, like an email address defined at registration time or the like

Body:
I have built APIs on c#.Net

these APIs works fine, but they are not secure, which means anyone worldwide can use it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;

namespace CDAPIs.Controllers
{
    public class CallSPController : ApiController
    {

        [Route("api/CallSP")]
        public string Get(string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
        {
            string sDBConn = Functions.GetConn();
            string[] Parms = Ps.Split(',');
            SqlConnection conn = new SqlConnection(sDBConn);
            SqlCommand cmd = new SqlCommand(SP, conn);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.StoredProcedure;

            string P = "";
            for (int i = 0; i < Parms.Length; i++)
            {
                if (i == 0) { P = P0; }
                if (i == 1) { P = P1; }
                if (i == 2) { P = P2; }
                if (i == 3) { P = P3; }
                cmd.Parameters.Add(new SqlParameter("@" + Parms[i].Trim(), P));
            }

            try
            {
                conn.Open();

                if (Type.ToUpper().Trim() == "STRING")
                {
                    string st = cmd.ExecuteScalar().ToString();
                    conn.Close();
                    conn.Dispose();
                    return st;
                }
                else
                {
                    SqlDataReader rdr = cmd.ExecuteReader();
                    var dt = new DataTable();
                    dt.Load(rdr);
                    List<DataRow> result = dt.AsEnumerable().ToList();
                    rdr.Close();
                    conn.Close();
                    conn.Dispose();
                    string json = Functions.DataTableToJSON(dt);
                    //return Json(result, JsonRequestBehavior.AllowGet);
                    return json;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

I want to protect these APIs and I would like to how to do that properly

I thought of adding UserID and Password to each API so the use send them as parameters

so it will be like this

    [Route("api/CallSP")]
    public string Get(string UserID, string Password, string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
    {

Is there a better solution?


问:
How to show selected date inside the button ---- Date picker -- Flutter
I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button
Also, I want to keep the same format of date, I have specified above in the code
I am providing my code and snapshots

```<code>[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}
</code>```

state of my application before selecting date

state of my application after selecting the date from date picker

答:
That is because you forgot to format the date when the date was chosen.
In the onPressed function where you are setting the state, you have to write it as:

```<code>if (_newDate == null) {
     return;
   } else {
     formattedDate = DateFormat('d-MMM-yy').format(_newDate);
}
</code>```

Hope this solves your problem.

Body:
I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button
Also, I want to keep the same format of date, I have specified above in the code
I am providing my code and snapshots

[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}

state of my application before selecting date

state of my application after selecting the date from date picker

Body:
That is because you forgot to format the date when the date was chosen.
In the onPressed function where you are setting the state, you have to write it as:

if (_newDate == null) {
     return;
   } else {
     formattedDate = DateFormat('d-MMM-yy').format(_newDate);
}

Hope this solves your problem.


问:
uwsgi socket file not created
I am having trouble setting up server using uwsgi and nginx. This is my uwsgi ini file (and symlink in vassals):

```<code># ebook_uwsgi.ini file
[uwsgi]
#emperor = /etc/uwsgi/vassals
#plugins        = python #if uwsgi installed with pip, dont have to use this line
# Django-related settings
# the base directory (full path)
chdir           = /var/www/django/ebook/ebook/wsgi/ebook/
# Django's wsgi file
module          = controller.wsgi:application
# the virtualenv (full path)
home            = /var/www/django/ebook

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10

# the socket (use the full path to be safe
socket         = /var/uwsgi/ebook.sock
# ... with appropriate permissions - may be needed
chmod-socket    = 664
uid             = www-data
gid             = www-data
# clear environment on exit
vacuum          = true

no-site         = True
wsgi-file       = /var/www/django/ebook/ebook/wsgi/ebook/controller/wsgi.py
#env             = DJANGO_SETTINGS_MODULE=controller.settings # set an environment variable
</code>```

and this is my nginx conf file:

```<code># mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    server unix:///var/uwsgi/ebook.sock; # for a file socket
    #server 127.0.0.1:8000; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8000;
    # the domain name it will serve for
    server_name IP; #www.domain.com; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /var/www/django/ebook/ebook/data;  # your Django project's media files - amend as required
    }

    location /static {
        alias /var/www/django/ebook/ebook/wsgi/static/; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        include     /var/www/django/ebook/ebook/uwsgi_params; # the uwsgi_params file you installed
    }
}
</code>```

When I run uwsgi as my user(lucas03)

```<code>uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data
</code>```

this is output:

```<code>*** Starting uWSGI 2.0.10 (64bit) on [Tue May 12 20:43:19 2015] ***
compiled with version: 4.7.2 on 14 April 2015 16:47:40
os: Linux-2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015
nodename: zoltan
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /var
detected binary path: /usr/local/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 2062113
your memory page size is 4096 bytes
detected max file descriptor number: 1024
*** starting uWSGI Emperor ***
*** has_emperor mode detected (fd: 6) ***
[uWSGI] getting INI configuration from ebook_uwsgi.ini
*** Starting uWSGI 2.0.10 (64bit) on [Tue May 12 20:43:19 2015] ***
compiled with version: 4.7.2 on 14 April 2015 16:47:40
os: Linux-2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015
nodename: zoltan
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /etc/uwsgi/vassals
detected binary path: /usr/local/bin/uwsgi
chdir() to /var/www/django/ebook/ebook/wsgi/ebook/
your processes number limit is 2062113
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /var/uwsgi/ebook.sock fd 3
Python version: 2.7.3 (default, Mar 13 2014, 11:26:58)  [GCC 4.7.2]
Set PythonHome to /var/www/django/ebook
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0xea41a0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 800448 bytes (781 KB) for 10 cores
*** Operational MODE: preforking ***
virtualenv is active
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0xea41a0 pid: 6291 (default app)
mountpoint  already configured. skip.
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 6291)
Tue May 12 20:43:19 2015 - [emperor] vassal ebook_uwsgi.ini has been spawned
spawned uWSGI worker 1 (pid: 6292, cores: 1)
spawned uWSGI worker 2 (pid: 6293, cores: 1)
Tue May 12 20:43:19 2015 - [emperor] vassal ebook_uwsgi.ini is ready to accept requests
spawned uWSGI worker 3 (pid: 6294, cores: 1)
spawned uWSGI worker 4 (pid: 6295, cores: 1)
spawned uWSGI worker 5 (pid: 6296, cores: 1)
spawned uWSGI worker 6 (pid: 6297, cores: 1)
spawned uWSGI worker 7 (pid: 6298, cores: 1)
spawned uWSGI worker 8 (pid: 6299, cores: 1)
spawned uWSGI worker 9 (pid: 6300, cores: 1)
spawned uWSGI worker 10 (pid: 6301, cores: 1)
</code>```

ebook.sock is created:

```<code>drwxrwxr-x  2 www-data www-data  3 máj 12 20:43 .
drwxr-xr-x 13 root     root     15 apr 14 16:29 ..
srw-rw-r--  1 lucas03  lucas03   0 máj 12 20:43 ebook.sock
</code>```

but I get 502 Bad Gateway. So I change owner of ebook.sock to www-data sudo chown www-data:www-data ebook.sock, my website is loaded correctly. Well, I thought it was great. Now I just need to run uwsgi so that it can create ebook.sock as user www-data.

So I set uwsgi to start on startup, I edited /etc/rc.local.

```<code>#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data
exit 0
</code>```

However, after I restart server, file ebook.sock is not created at all, although uwsgi runs. (I can see it in ps aux | grep uwsgi). So I thought that it is run same or similar way as if I run that file as root.

So I run file /etc/rc.local and this is output:

```<code>*** Starting uWSGI 2.0.10 (64bit) on [Tue May 12 20:57:35 2015] ***
compiled with version: 4.7.2 on 14 April 2015 16:47:40
os: Linux-2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015
nodename: zoltan
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /var/uwsgi
detected binary path: /usr/local/bin/uwsgi
setgid() to 33
setuid() to 33
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 2062113
your memory page size is 4096 bytes
detected max file descriptor number: 1024
*** starting uWSGI Emperor ***
</code>```

Since output is shorter, I guess config files in /etc/uwsgi/vassals are not loaded and there is some problem running emperor vassals.

Anybody have any idea why?

答:
I know that it is old question but, you got 502 Bad Gateway because you didn't tell nginx where to send requests if someone calls /. You should change location / to:

```<code># Finally, send all non-media requests to the Django server.
location / {
   uwsgi_pass  django; # <- you miss this part
   include     /var/www/django/ebook/ebook/uwsgi_params;
}
</code>```

and yes if you got some files permissions error you should fix it too.

Title: uwsgi socket file not created

Body:
I am having trouble setting up server using uwsgi and nginx. This is my uwsgi ini file (and symlink in vassals):

# ebook_uwsgi.ini file
[uwsgi]
#emperor = /etc/uwsgi/vassals
#plugins        = python #if uwsgi installed with pip, dont have to use this line
# Django-related settings
# the base directory (full path)
chdir           = /var/www/django/ebook/ebook/wsgi/ebook/
# Django's wsgi file
module          = controller.wsgi:application
# the virtualenv (full path)
home            = /var/www/django/ebook

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10

# the socket (use the full path to be safe
socket         = /var/uwsgi/ebook.sock
# ... with appropriate permissions - may be needed
chmod-socket    = 664
uid             = www-data
gid             = www-data
# clear environment on exit
vacuum          = true

no-site         = True
wsgi-file       = /var/www/django/ebook/ebook/wsgi/ebook/controller/wsgi.py
#env             = DJANGO_SETTINGS_MODULE=controller.settings # set an environment variable

and this is my nginx conf file:

# mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    server unix:///var/uwsgi/ebook.sock; # for a file socket
    #server 127.0.0.1:8000; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8000;
    # the domain name it will serve for
    server_name IP; #www.domain.com; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /var/www/django/ebook/ebook/data;  # your Django project's media files - amend as required
    }

    location /static {
        alias /var/www/django/ebook/ebook/wsgi/static/; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        include     /var/www/django/ebook/ebook/uwsgi_params; # the uwsgi_params file you installed
    }
}

When I run uwsgi as my user(lucas03)

uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

this is output:

*** Starting uWSGI 2.0.10 (64bit) on [Tue May 12 20:43:19 2015] ***
compiled with version: 4.7.2 on 14 April 2015 16:47:40
os: Linux-2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015
nodename: zoltan
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /var
detected binary path: /usr/local/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 2062113
your memory page size is 4096 bytes
detected max file descriptor number: 1024
*** starting uWSGI Emperor ***
*** has_emperor mode detected (fd: 6) ***
[uWSGI] getting INI configuration from ebook_uwsgi.ini
*** Starting uWSGI 2.0.10 (64bit) on [Tue May 12 20:43:19 2015] ***
compiled with version: 4.7.2 on 14 April 2015 16:47:40
os: Linux-2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015
nodename: zoltan
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /etc/uwsgi/vassals
detected binary path: /usr/local/bin/uwsgi
chdir() to /var/www/django/ebook/ebook/wsgi/ebook/
your processes number limit is 2062113
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /var/uwsgi/ebook.sock fd 3
Python version: 2.7.3 (default, Mar 13 2014, 11:26:58)  [GCC 4.7.2]
Set PythonHome to /var/www/django/ebook
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0xea41a0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 800448 bytes (781 KB) for 10 cores
*** Operational MODE: preforking ***
virtualenv is active
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0xea41a0 pid: 6291 (default app)
mountpoint  already configured. skip.
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 6291)
Tue May 12 20:43:19 2015 - [emperor] vassal ebook_uwsgi.ini has been spawned
spawned uWSGI worker 1 (pid: 6292, cores: 1)
spawned uWSGI worker 2 (pid: 6293, cores: 1)
Tue May 12 20:43:19 2015 - [emperor] vassal ebook_uwsgi.ini is ready to accept requests
spawned uWSGI worker 3 (pid: 6294, cores: 1)
spawned uWSGI worker 4 (pid: 6295, cores: 1)
spawned uWSGI worker 5 (pid: 6296, cores: 1)
spawned uWSGI worker 6 (pid: 6297, cores: 1)
spawned uWSGI worker 7 (pid: 6298, cores: 1)
spawned uWSGI worker 8 (pid: 6299, cores: 1)
spawned uWSGI worker 9 (pid: 6300, cores: 1)
spawned uWSGI worker 10 (pid: 6301, cores: 1)

ebook.sock is created:

drwxrwxr-x  2 www-data www-data  3 máj 12 20:43 .
drwxr-xr-x 13 root     root     15 apr 14 16:29 ..
srw-rw-r--  1 lucas03  lucas03   0 máj 12 20:43 ebook.sock

but I get 502 Bad Gateway. So I change owner of ebook.sock to www-data sudo chown www-data:www-data ebook.sock, my website is loaded correctly. Well, I thought it was great. Now I just need to run uwsgi so that it can create ebook.sock as user www-data.

So I set uwsgi to start on startup, I edited /etc/rc.local.

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data
exit 0

However, after I restart server, file ebook.sock is not created at all, although uwsgi runs. (I can see it in ps aux | grep uwsgi). So I thought that it is run same or similar way as if I run that file as root.

So I run file /etc/rc.local and this is output:

*** Starting uWSGI 2.0.10 (64bit) on [Tue May 12 20:57:35 2015] ***
compiled with version: 4.7.2 on 14 April 2015 16:47:40
os: Linux-2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015
nodename: zoltan
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /var/uwsgi
detected binary path: /usr/local/bin/uwsgi
setgid() to 33
setuid() to 33
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 2062113
your memory page size is 4096 bytes
detected max file descriptor number: 1024
*** starting uWSGI Emperor ***

Since output is shorter, I guess config files in /etc/uwsgi/vassals are not loaded and there is some problem running emperor vassals.

Anybody have any idea why?

Body:
I know that it is old question but, you got 502 Bad Gateway because you didn't tell nginx where to send requests if someone calls /. You should change location / to:

# Finally, send all non-media requests to the Django server.
location / {
   uwsgi_pass  django; # <- you miss this part
   include     /var/www/django/ebook/ebook/uwsgi_params;
}

and yes if you got some files permissions error you should fix it too.


问:
Why does one of the paddings in my code not work
padding-right doesn't work but padding-left does. I tried putting padding in other places, but it didn't work. Just started to learn, please guide me. Thanks.

https://jsfiddle.net/iorre/L49w7bxa/2/

body {
    background-color: whitesmoke;
    margin: 0;
    font-family: sans-serif;
    padding-left: 100px;
    padding-right: 100px;
}

.header-background {
    background-color: black;
    background-size: cover;
    margin: 0;
    z-index: 1000;
}

.header-text {
    text-align: center;
    color: white;
    font-size: 50px;
}

header {
    position: fixed;
    top: 0;
    width: 100%;
    height: 40px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <body>
        <header>

            <h1 class='header-background header-text'>Lorem Ipsum</h1>
        </header>

    </body></code>```

答:
check if this helps
https://jsfiddle.net/dLj5utz2/</p>
```<code><!DOCTYPE html>
<html lang="ru-RU">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<title>Project number 1</title>
</head>
<body>
<header>
 <h1 class='header-background header-text'>Lorem Ipsum</h1>
</header>
<p style="position: relative; top: 2000px; margin-top: 60px;">qweqdas</p>
<footer>
</footer>
</body>
</html>

body {
background-color: whitesmoke;
margin: 0;
font-family: sans-serif;
padding-left: 0 auto;

}

.header-background {
background-color: black;
background-size: cover;
height: 70px;
margin: 0;
z-index: 1000;
}

.header-text {
 text-align: center;
 color: white;
 font-size: 50px;
 }

 header {
 position: fixed;
 top: 0;
 width: 100%;
 height: 40px;

 }
</code>```

Body:
padding-right doesn't work but padding-left does. I tried putting padding in other places, but it didn't work. Just started to learn, please guide me. Thanks.

https://jsfiddle.net/iorre/L49w7bxa/2/

body {
    background-color: whitesmoke;
    margin: 0;
    font-family: sans-serif;
    padding-left: 100px;
    padding-right: 100px;
}

.header-background {
    background-color: black;
    background-size: cover;
    margin: 0;
    z-index: 1000;
}

.header-text {
    text-align: center;
    color: white;
    font-size: 50px;
}

header {
    position: fixed;
    top: 0;
    width: 100%;
    height: 40px;

}

Lorem Ipsum

Body:
check if this helps
https://jsfiddle.net/dLj5utz2/

<!DOCTYPE html>
<html lang="ru-RU">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<title>Project number 1</title>
</head>
<body>
<header>
 <h1 class='header-background header-text'>Lorem Ipsum</h1>
</header>
<p style="position: relative; top: 2000px; margin-top: 60px;">qweqdas</p>
<footer>
</footer>
</body>
</html>

body {
background-color: whitesmoke;
margin: 0;
font-family: sans-serif;
padding-left: 0 auto;

}

.header-background {
background-color: black;
background-size: cover;
height: 70px;
margin: 0;
z-index: 1000;
}

.header-text {
 text-align: center;
 color: white;
 font-size: 50px;
 }

 header {
 position: fixed;
 top: 0;
 width: 100%;
 height: 40px;

 }


问:
animate move to the left and to the right?
I want is to move my pagination to the left and to the right after clicked on #prev_pag and #next_pag. how is it and solve my problem?

Eg:  http://jsfiddle.net/szVKD/5/

```<code>$('#next_pag').click(function() {
        $('#pagination').animate({
            left: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            left: '+=100px'
        },
        500);
    });
});
</code>```

答:
Needed to delete the last line for javascript to compile and added "position: relative;" to #pagination div.

http://jsfiddle.net/szVKD/9/

Body:
I want is to move my pagination to the left and to the right after clicked on #prev_pag and #next_pag. how is it and solve my problem?

Eg:  http://jsfiddle.net/szVKD/5/

$('#next_pag').click(function() {
        $('#pagination').animate({
            left: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            left: '+=100px'
        },
        500);
    });
});


问:
How to access looped div tag in Typescript file
```<code><div  class="mx-0 p-2 row"  style="box-shadow: 0 -1px 0 0 rgb(0 0 0 / 10%);">
    <div #myDiv (click)="navToOrder(value.agId,value.invoiceId,value.tableNo,value.currStageName)" [style.background-color]="value.currStageColor"

        class="table1 m-3"  *ngFor="let value of dashBoardTableList ;let i=index"
        tooltip={{value.currStageName}} placement="top">
        <span class="homeTopLabel ">{{value.noOfCovers}}</span>
        <span class="leftGlass">
            <i *ngIf="value.currStageName!='Empty'" class="fa fa-glass "></i>
            <i *ngIf="value.currStageName=='Empty'" class=" fa fa-glass fa-flip-vertical"></i>
        </span>
        <span class="fa-stack middlePlate">
            <i class="fa fa-genderless fa-stack-2x" style="font-size:35px;"></i><i class="fa fa-spoon fa-stack-1x"
                style="font-size: 15px;top: 5px;left: -1.5px;"></i>
        </span>
        <span class="rightGlass">
            <i *ngIf="value.currStageName!='Empty'" class="fa fa-glass "></i>
            <i *ngIf="value.currStageName=='Empty'" class=" fa fa-glass fa-flip-vertical"></i>
        </span>

        <span class="homeBlabel">{{value.tableNo}}</span>

    </div>
</div>
</code>```

Here I want to get a specific index of div tag unfortunately Tabindex is not working fine.Is there any other way ?

答:
Applying styles using @ViewChild is generally an Angular anti-pattern.

It sounds like what you really want here is a Directive that takes the index of the element as an argument, something like:

import { AfterViewInit, Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[myStyleDirective]'
})
export class MyStyleDirective implements AfterViewInit {
  @Input() itemIndex!: number;

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngAfterViewInit() {
    const styleValue = this.itemIndex % 2 === 0 ? 'even' : 'odd';
    this.renderer.setStyle(this.el.nativeElement, 'styleToChange', styleValue);
  }
}
```
<p>You then place the directive on your element:</p>
<pre class="lang-html prettyprint-override"><code><div *ngFor="let value of dashBoardTableList ;let i=index"
     myStyleDirective
     [itemIndex]="i"
     (click)="navToOrder(value.agId,value.invoiceId,value.tableNo,value.currStageName)"
     [style.background-color]="value.currStageColor"
     class="table1 m-3"
     tooltip={{value.currStageName}}
     placement="top">
</code>```

You could also use [ngStyle] or [ngClass] and use a method in your TypeScript which returns the appropriate style for a given index. There can be performance issues with that, though, as the method gets called for every change detection cycle.

Body:
        {{value.noOfCovers}}

        {{value.tableNo}}

Here I want to get a specific index of div tag unfortunately Tabindex is not working fine.Is there any other way ?

Body:
Applying styles using @ViewChild is generally an Angular anti-pattern.

It sounds like what you really want here is a Directive that takes the index of the element as an argument, something like:

import { AfterViewInit, Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[myStyleDirective]'
})
export class MyStyleDirective implements AfterViewInit {
  @Input() itemIndex!: number;

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngAfterViewInit() {
    const styleValue = this.itemIndex % 2 === 0 ? 'even' : 'odd';
    this.renderer.setStyle(this.el.nativeElement, 'styleToChange', styleValue);
  }
}

You then place the directive on your element:

<div *ngFor="let value of dashBoardTableList ;let i=index"
     myStyleDirective
     [itemIndex]="i"
     (click)="navToOrder(value.agId,value.invoiceId,value.tableNo,value.currStageName)"
     [style.background-color]="value.currStageColor"
     class="table1 m-3"
     tooltip={{value.currStageName}}
     placement="top">

You could also use [ngStyle] or [ngClass] and use a method in your TypeScript which returns the appropriate style for a given index. There can be performance issues with that, though, as the method gets called for every change detection cycle.


问:
Handling keystore file?
As for react native android app, in Visual Studio docs of signing, it says that if my keystore is not within my repo, then I need to upload my key store file contractor-release-key.keystore and set credentials in app center, and that's what I did, however, in the build, I got this error:

```<code>jarsigner: Certificate chain not found for: ***.  *** must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain
</code>```

Also, in build.gradle if I set:

```<code>releaseSigningConfig {
            storeFile rootProject.file("app/contractor-release-key.keystore")
            storePassword System.getenv("APPCENTER_KEYSTORE_PASSWORD")
            keyAlias System.getenv("APPCENTER_KEY_ALIAS")
            keyPassword System.getenv("APPCENTER_KEY_PASSWORD")
        }
</code>```

I get error:

```<code>Execution failed for task ':app:validateSigningRelease'.
> Keystore file '/Users/vsts/agent/2.153.2/work/1/s/android/app/contractor-release-key.keystore' not found for signing config 'releaseSigningConfig'.
</code>```

Any idea?

EDIT

When I add all signing into build.gradle and include keystore file into repository, but I got this error:

```<code>Execution failed for task ':app:processReleaseManifest'.
> Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:9:5-54:19 to override.
</code>```

答: In my case, it suddenly happened and I had to to re-upload the exact same keystore file as well as key password and alias in order to fix it.</p>

Title: Handling keystore file?

Body:
As for react native android app, in Visual Studio docs of signing, it says that if my keystore is not within my repo, then I need to upload my key store file contractor-release-key.keystore and set credentials in app center, and that's what I did, however, in the build, I got this error:

jarsigner: Certificate chain not found for: ***.  *** must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain

Also, in build.gradle if I set:

releaseSigningConfig {
            storeFile rootProject.file("app/contractor-release-key.keystore")
            storePassword System.getenv("APPCENTER_KEYSTORE_PASSWORD")
            keyAlias System.getenv("APPCENTER_KEY_ALIAS")
            keyPassword System.getenv("APPCENTER_KEY_PASSWORD")
        }

I get error:

Execution failed for task ':app:validateSigningRelease'.
> Keystore file '/Users/vsts/agent/2.153.2/work/1/s/android/app/contractor-release-key.keystore' not found for signing config 'releaseSigningConfig'.

Any idea?

EDIT

When I add all signing into build.gradle and include keystore file into repository, but I got this error:

Execution failed for task ':app:processReleaseManifest'.
> Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:9:5-54:19 to override.


问:
Python: How to solve bracket not closed error
following a tutorial I'm getting error "(" is not closed while using the exact same code:

```<code>compiled_sol = compile_standard(
  {
      "language": "Solidity",
      "sources": {"SimpleStorage.sol": {"content" = simple_storage_file}}
  }
)
</code>```

don't know where it's going wrong getting these errors:

```<code>"{" was not closedPylance
Expected parameter namePylance
</code>```

and

```<code>Expected parameter namePylance
</code>```

答:
As @adammaly004 mentioned, you can't have an = in a python dict. Replacing "content" = simple_storage_file with "content": simple_storage_file should solve your issue.

Full example:

compiled_sol = compile_standard(
  {
      "language": "Solidity",
      "sources": {"SimpleStorage.sol": {"content": simple_storage_file}}
  }
)

```

Body:
following a tutorial I'm getting error "(" is not closed while using the exact same code:

compiled_sol = compile_standard(
  {
      "language": "Solidity",
      "sources": {"SimpleStorage.sol": {"content" = simple_storage_file}}
  }
)

don't know where it's going wrong getting these errors:

"{" was not closedPylance
Expected parameter namePylance

and

Expected parameter namePylance


Body:
How to generate a DateTime range by step of 5 minutes? The following is the output:

2022-02-13 00:00:00, 2022-02-13 00:05:00
2022-02-13 00:05:00, 2022-02-13 00:10:00
2022-02-13 00:10:00, 2022-02-13 00:15:00
2022-02-13 00:15:00, 2022-02-13 00:20:00
...
2022-02-13 23:45:00, 2022-02-13 23:50:00
2022-02-13 23:50:00, 2022-02-13 23:55:00
2022-02-13 23:55:00, 2022-02-14 00:00:00

Body:
Use the Interval module.

use Interval;
my $dt = Interval[300].new(time);
say $dt++ for ^5;

2022-02-13T15:29:03Z
2022-02-13T15:34:03Z
2022-02-13T15:39:03Z
2022-02-13T15:44:03Z
2022-02-13T15:49:03Z


问:
How to set a UITableView Editing Mode from a swipe action?
I need to turn on a tableView editing mode by clicking on one of its cells from swipe action "move":

Code for swipe action:

```<code>override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let move = UIContextualAction(style: .normal, title: "Переместить") { (action, view, completionHandler) in
        self.turnEditing()
        completionHandler(true)
    }
    move.backgroundColor = UIColor(named: "CalmBlueColor")

    let configuration = UISwipeActionsConfiguration(actions: [move])
    return configuration
}
</code>```

turnEditing() function:

```<code>   func turnEditing() {
       if tableView.isEditing {
           tableView.isEditing = false
       } else {
           tableView.isEditing = true
       }
    }
</code>```

TableView Delegates:

```<code> override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

}

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}

override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}
</code>```

When I press on the swipe actions it's just closes, without going to editing mode...
Here is the GIF

Is it possible to go into editing mode from a swipe action or only from a barButtonItem + IBAction?

答:
Add some delay

```<code>DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
  self.turnEditing()
}
</code>```

BTW you could replace this

```<code>if tableView.isEditing {
  tableView.isEditing = false
} else {
  tableView.isEditing = true
}
</code>```

With

```<code>tableView.isEditing.toggle()
</code>```

Body:
I need to turn on a tableView editing mode by clicking on one of its cells from swipe action "move":

Code for swipe action:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let move = UIContextualAction(style: .normal, title: "Переместить") { (action, view, completionHandler) in
        self.turnEditing()
        completionHandler(true)
    }
    move.backgroundColor = UIColor(named: "CalmBlueColor")

    let configuration = UISwipeActionsConfiguration(actions: [move])
    return configuration
}

turnEditing() function:

   func turnEditing() {
       if tableView.isEditing {
           tableView.isEditing = false
       } else {
           tableView.isEditing = true
       }
    }

TableView Delegates:

 override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

}

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}

override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

When I press on the swipe actions it's just closes, without going to editing mode...
Here is the GIF

Is it possible to go into editing mode from a swipe action or only from a barButtonItem + IBAction?

Body:
Add some delay

DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
  self.turnEditing()
}

BTW you could replace this

if tableView.isEditing {
  tableView.isEditing = false
} else {
  tableView.isEditing = true
}

With

tableView.isEditing.toggle()


问:
Do you put unit tests in same project or another project?
Do you put unit tests in the same project for convenience or do you put them in a separate assembly?

If you put them in a separate assembly like we do, we end up with a number of extra projects in the solution.  It's great for unit testing while coding but how do you release the application without all of these extra assemblies?

答: Another disadvantage of shipping unit test code to production is that we are shipping the knowledge of how to actually use that code. This can be bad because the attacker will have an easier time understanding the business logic after successful decompilation of the unit tests. This can be really harmful. For example, your code could contain special logic to deal with the particularities of taxes between states and countries. This knowledge would then be easily stolen by the attacker, who will have the possibility to sell this to other players in the same area...just by copying the code in production. In my experience, almost no code in .NET is correctly obfuscated in production. There are many tools that can easily decompile the code in a very intelligible form.

OwnerDisplayName: ak


问:
Remove "TRIM" in a column field?
Referring to the question above, I have a problem when I'm trying to display my database in datagridview. I have a field "Items" but when I call it to the grid, the field will be name "TRIM(Items)". The "TRIM" comes from my sql statement :-

SELECT TRIM(Items) FROM others2

I need the TRIM so that there is no space when I called my data to the grid.
Anyway, how to remove the word but still it will trim my data?

答: Try SELECT TRIM(Items) As Items FROM others2.

Title: Remove "TRIM" in a column field?


问:
Heroku is not allowing me to use the transformers module in Python
I am installing transformers on Heroku. Why am I getting this error?

Failed to build tokenizers
ERROR: Could not build wheels for tokenizers, which is required to install pyproject.toml-based projects
```

PyPi: https://pypi.org/project/transformers/

GitHub: https://github.com/huggingface/transformers/

Docs: https://huggingface.co/docs/transformers/

答:
transformers currently does not support the latest version of Python (3.10) and hence, you will have to switch to an old version that is available on Heroku. The following versions are recommended:

python-3.9.10

python-3.8.12

python-3.7.12

Try editing your runtime.txt file to one of the above versions and you should not get that error.

Body:
I am installing transformers on Heroku. Why am I getting this error?

Failed to build tokenizers
ERROR: Could not build wheels for tokenizers, which is required to install pyproject.toml-based projects

PyPi: https://pypi.org/project/transformers/

GitHub: https://github.com/huggingface/transformers/

Docs: https://huggingface.co/docs/transformers/