答:
You can use streams that you subscribe to in your button. I wrote an article for this exact problem here.

Basically when one button is tapped you broadcast it's id on a stream. At the same time all your buttons (your CustomWidget) listens to the stream. When a new id comes on the stream you check if the current button is the one pressed, if it's not you disable it. If it is you leave it enabled.

Too much code to paste here, but the article (only 2 minutes long) describes everything.

Title: make all the other widget flatbuttons chage their colour when one is pressed on flutter

Body:
i have some buttons that i need to be able to press only one and the rest should change their colour,

in order to make the code smaller i extracted the widget to make it reusable, but when i select a button it get the colour changed but it does not refresh the state of the other buttons.

if i dont extract the button method and make use of duplicate code inside the Row, then it works.

What im missing?

int numOfTime = 60;

class NumOfTime extends StatefulWidget {
  const NumOfTime({
    Key key,
  }) : super(key: key);

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

class _NumOfTimeState extends State<NumOfTime> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
            margin: EdgeInsets.only(left: 15, top: 5),
            child: Text(
              'Δευτερόλεπτα',
              style: TextStyle(color: Colors.white),
            )),
        Container(
          margin: EdgeInsets.only(top: 2, left: 10, right: 10, bottom: 10),
          decoration: myBoxDecoration(),
          child: Row(
            children: <Widget>[
              Container(
                  padding: EdgeInsets.only(left: 10, right: 5),
                  child: Icon(Icons.timer)),
              CustomButton(
                number: 30,
              ),
              CustomButton(
                number: 45,
              ),
              CustomButton(
                number: 60,
              ),
              CustomButton(
                number: 75,
              ),
              CustomButton(
                number: 90,
              ),
              Container(
                padding: EdgeInsets.only(right: 10),
              )
            ],
          ),
        ),
      ],
    );
  }
}

class CustomButton extends StatefulWidget {
  final int number;
  const CustomButton({
    Key key,
    final int number,
  }) : this.number = number;

  @override
  _CustomButtonState createState() => _CustomButtonState(number);
}

class _CustomButtonState extends State<CustomButton> {
  final int number;
  _CustomButtonState(this.number);

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: FlatButton(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
          disabledColor: number == numOfTime ? Colors.black : Colors.white,
          highlightColor: number == numOfTime ? Colors.black : Colors.white,
          color: number == numOfTime ? Colors.black : Colors.white,
          child: Text(
            '$number',
            style: TextStyle(
                color: number == numOfTime ? Colors.white : Colors.black,
                fontSize: 13),
          ),
          onPressed: () {
            numOfTime = number;
            setState(() {});
          }),
    );
  }
}

i expect to see all the other buttons change their color back to white if one is selected.

i also tried to pass null onPressed to make it disabled, but i dont see any change.


来源: stackexchange

问:
How should be the regex for alphanumeric where alphabet only with combinations of"w" or "d" or "h"
I need the regex to validate the user entered string, the string may be of following formats.

ex: 1w 2d 1h or 2w 1h or 1w 2d. Likewise combinations of numbers and w,d and h.

I am looking for the regex to allow the combinations number and w or d or h.

Is it possible to have a regex like that way?

答:
This works for your requirement. Hope this helps! Ordering (w->d->h) guaranteed.

```<code>^(\d+w){0,1}\s*(\d+d){0,1}\s*(\d+h){0,1}$
</code>```

Test cases:

10w 12d 11h

1w 2d

2w 1h

1d 1h

1d 1h

3w 2h

ContentLicense: CC BY-SA 4.0

Body:
This works for your requirement. Hope this helps! Ordering (w->d->h) guaranteed.

^(\d+w){0,1}\s*(\d+d){0,1}\s*(\d+h){0,1}$

Test cases:

10w 12d 11h

1w 2d

2w 1h

1d 1h

1d 1h

3w 2h


问:
Azure Pipeline to build docker images fails using same docker file in Visual Studio
I'm trying to create a deployment pipeline to deploy my image to Kubernetes cluster.  The first step in this process is to create an image based on the docker file.  The docker file I'm using was generated from Visual Studio when I added docker support and successfully creates the image when right clicking on the docker image and selecting to create it.  When I configure the Azure Pipeline, the create docker image fails as soon as it tries to build the actual solution.  The previous step grabs all the sources files but then fails on the docker image creation with

```<code>[error]COPY failed: stat/var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj:
 no such file or directory

[error]/usr/bin/docker failed with return code: 1
</code>```

The following is the docker file generated from Visual studio and is referenced by the azure pipeline stage to create the docker image.

```<code> FROM mcr.microsoft.com/dotnet/core/runtime:2.2-stretch-slim AS base

 WORKDIR /app
 FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS
 build

 WORKDIR /src
 COPY ["DockerTest/DockerTest.csproj", "DockerTest/"]
 RUN dotnet restore "DockerTest/DockerTest.csproj"
 COPY . .
 WORKDIR "/src/DockerTest"
 RUN dotnet build "DockerTest.csproj" -c Release -o /app

 FROM build AS publish
 RUN dotnet publish "DockerTest.csproj" -c Release -o /app

 FROM base AS final
 WORKDIR /app
 COPY --from=publish /app .
 ENTRYPOINT ["dotnet", "DockerTest.dll"]
</code>```

##[section]Starting: Build a container image

  ============================================================================== Task: Docker Description : Build, tag, push, or run Docker images, or
  run a Docker command. Task can be used with Docker or Azure Container
  registry. Version : 0.150.6  Author : Microsoft Corporation Help :
  [More Information]https://go.microsoft.com/fwlink/?linkid=848006)

  ============================================================================== [command]/usr/bin/docker build -f

  /home/vsts/work/1/s/DockerTest/Dockerfile -t
  ihacontainers.azurecr.io/dockertest:6 /home/vsts/work/1/s/DockerTest
  Sending build context to Docker daemon  6.144kB     Step 1/15 : FROM
  mcr.microsoft.com/dotnet/core/runtime:2.2-stretch-slim AS base
  2.2-stretch-slim: Pulling from dotnet/core/runtime 743f2d6c1f65: Pulling fs layer 074da88b8de0: Pulling fs layer ac831735b47a: Pulling
  fs layer 3adcc844418d: Pulling fs layer 3adcc844418d: Waiting
  ac831735b47a: Download complete 743f2d6c1f65: Verifying Checksum
  743f2d6c1f65: Download complete 074da88b8de0: Verifying Checksum
  074da88b8de0: Download complete 3adcc844418d: Verifying Checksum
  zadcc844418d: Download complete 743f2d6c1f65: Pull complete
  074da88b8de0: Pull complete ac831735b47a: Pull complete 3adcc844418d:
  Pull complete Digest:
  sha256:066c31b113b0a20e6155d3bd8a314563c688d2ec31c11d7e551af5bc2595f30c
  Status: Downloaded newer image for
  mcr.microsoft.com/dotnet/core/runtime:2.2-stretch-slim  --->
  c0f9ab44ecc1 Step 2/15 : WORKDIR /app  ---> Running in 6d1a5f5600dd
  Removing intermediate container 6d1a5f5600dd  ---> 527fcebeaf1f Step
  3/15 : FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
  2.2-stretch: Pulling from dotnet/core/sdk c5e155d5a1d1: Pulling fs layer 221d80d00ae9: Pulling fs layer 4250b3117dca: Pulling fs layer
  3b7ca19181b2: Pulling fs layer 3466298fc231: Pulling fs layer
  310737d73ed1: Pulling fs layer dc981de74fae: Pulling fs layer
  3b7ca19181b2: Waiting 3466298fc231: Waiting 310737d73ed1: Waiting
  dc981de74fae: Waiting 4250b3117dca: Verifying Checksum 4250b3117dca:
  Download complete 221d80d00ae9: Verifying Checksum 221d80d00ae9:
  Download complete 3466298fc231: Verifying Checksum 3466298fc231:
  Download complete c5e155d5a1d1: Verifying Checksum c5e155d5a1d1:
  Download complete 3b7ca19181b2: Verifying Checksum 3b7ca19181b2:
  Download complete c5e155d5a1d1: Pull complete 221d80d00ae9: Pull
  complete 310737d73ed1: Verifying Checksum 310737d73ed1: Download
  complete 4250b3117dca: Pull complete dc981de74fae: Verifying Checksum
  dc981de74fae: Download complete 3b7ca19181b2: Pull complete
  3466298fc231: Pull complete 310737d73ed1: Pull complete dc981de74fae:
  Pull complete Digest:
  sha256:222cc0bb0bc93875ee0f6be626b2838beea838f65e53653e07c33eb9d00b0163
  Status: Downloaded newer image for
  mcr.microsoft.com/dotnet/core/sdk:2.2-stretch  ---> e4747ec2aaff Step
  4/15 : WORKDIR /src  ---> Running in a7ebcac87f68 Removing
  intermediate container a7ebcac87f68  ---> d7541674a9da Step 5/15 :
  COPY ["DockerTest/DockerTest.csproj", "DockerTest/"] COPY failed: stat
  /var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj:no
  such file or directory

##[error]COPY failed: stat/var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj:no
  such file or directory

##[error]/usr/bin/docker failed with return code: 1  ##[section]Finishing: Build a container image

答:
[error]COPY failed: stat/var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj: no such file or directory

According to this error message, the error occurred on the line of your dockerfile:              COPY ["DockerTest/DockerTest.csproj", "DockerTest/"].

First, please confirm that you did not use .dockerignore file to exclude this file: DockerTest/DockerTest.csproj, which must exists in the directory where you run your build from.

If it does not ignored by .dockerignore file, then you need to consider about your dockerfile location level.

DockerTest.csproj file should not put at the lower source file path level. You need to change the source of the context, move it at a higher level. So modify your dockerfile manually as :

```<code>COPY ["DockerTest.csproj", "DockerTest/"]
</code>```

Body:
I'm trying to create a deployment pipeline to deploy my image to Kubernetes cluster.  The first step in this process is to create an image based on the docker file.  The docker file I'm using was generated from Visual Studio when I added docker support and successfully creates the image when right clicking on the docker image and selecting to create it.  When I configure the Azure Pipeline, the create docker image fails as soon as it tries to build the actual solution.  The previous step grabs all the sources files but then fails on the docker image creation with

[error]COPY failed: stat/var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj:
 no such file or directory

[error]/usr/bin/docker failed with return code: 1

The following is the docker file generated from Visual studio and is referenced by the azure pipeline stage to create the docker image.

 FROM mcr.microsoft.com/dotnet/core/runtime:2.2-stretch-slim AS base

 WORKDIR /app
 FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS
 build

 WORKDIR /src
 COPY ["DockerTest/DockerTest.csproj", "DockerTest/"]
 RUN dotnet restore "DockerTest/DockerTest.csproj"
 COPY . .
 WORKDIR "/src/DockerTest"
 RUN dotnet build "DockerTest.csproj" -c Release -o /app

 FROM build AS publish
 RUN dotnet publish "DockerTest.csproj" -c Release -o /app

 FROM base AS final
 WORKDIR /app
 COPY --from=publish /app .
 ENTRYPOINT ["dotnet", "DockerTest.dll"]

##[section]Starting: Build a container image

  ============================================================================== Task: Docker Description : Build, tag, push, or run Docker images, or
  run a Docker command. Task can be used with Docker or Azure Container
  registry. Version : 0.150.6  Author : Microsoft Corporation Help :
  [More Information]https://go.microsoft.com/fwlink/?linkid=848006)

  ============================================================================== [command]/usr/bin/docker build -f

  /home/vsts/work/1/s/DockerTest/Dockerfile -t
  ihacontainers.azurecr.io/dockertest:6 /home/vsts/work/1/s/DockerTest
  Sending build context to Docker daemon  6.144kB     Step 1/15 : FROM
  mcr.microsoft.com/dotnet/core/runtime:2.2-stretch-slim AS base
  2.2-stretch-slim: Pulling from dotnet/core/runtime 743f2d6c1f65: Pulling fs layer 074da88b8de0: Pulling fs layer ac831735b47a: Pulling
  fs layer 3adcc844418d: Pulling fs layer 3adcc844418d: Waiting
  ac831735b47a: Download complete 743f2d6c1f65: Verifying Checksum
  743f2d6c1f65: Download complete 074da88b8de0: Verifying Checksum
  074da88b8de0: Download complete 3adcc844418d: Verifying Checksum
  zadcc844418d: Download complete 743f2d6c1f65: Pull complete
  074da88b8de0: Pull complete ac831735b47a: Pull complete 3adcc844418d:
  Pull complete Digest:
  sha256:066c31b113b0a20e6155d3bd8a314563c688d2ec31c11d7e551af5bc2595f30c
  Status: Downloaded newer image for
  mcr.microsoft.com/dotnet/core/runtime:2.2-stretch-slim  --->
  c0f9ab44ecc1 Step 2/15 : WORKDIR /app  ---> Running in 6d1a5f5600dd
  Removing intermediate container 6d1a5f5600dd  ---> 527fcebeaf1f Step
  3/15 : FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
  2.2-stretch: Pulling from dotnet/core/sdk c5e155d5a1d1: Pulling fs layer 221d80d00ae9: Pulling fs layer 4250b3117dca: Pulling fs layer
  3b7ca19181b2: Pulling fs layer 3466298fc231: Pulling fs layer
  310737d73ed1: Pulling fs layer dc981de74fae: Pulling fs layer
  3b7ca19181b2: Waiting 3466298fc231: Waiting 310737d73ed1: Waiting
  dc981de74fae: Waiting 4250b3117dca: Verifying Checksum 4250b3117dca:
  Download complete 221d80d00ae9: Verifying Checksum 221d80d00ae9:
  Download complete 3466298fc231: Verifying Checksum 3466298fc231:
  Download complete c5e155d5a1d1: Verifying Checksum c5e155d5a1d1:
  Download complete 3b7ca19181b2: Verifying Checksum 3b7ca19181b2:
  Download complete c5e155d5a1d1: Pull complete 221d80d00ae9: Pull
  complete 310737d73ed1: Verifying Checksum 310737d73ed1: Download
  complete 4250b3117dca: Pull complete dc981de74fae: Verifying Checksum
  dc981de74fae: Download complete 3b7ca19181b2: Pull complete
  3466298fc231: Pull complete 310737d73ed1: Pull complete dc981de74fae:
  Pull complete Digest:
  sha256:222cc0bb0bc93875ee0f6be626b2838beea838f65e53653e07c33eb9d00b0163
  Status: Downloaded newer image for
  mcr.microsoft.com/dotnet/core/sdk:2.2-stretch  ---> e4747ec2aaff Step
  4/15 : WORKDIR /src  ---> Running in a7ebcac87f68 Removing
  intermediate container a7ebcac87f68  ---> d7541674a9da Step 5/15 :
  COPY ["DockerTest/DockerTest.csproj", "DockerTest/"] COPY failed: stat
  /var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj:no
  such file or directory

##[error]COPY failed: stat/var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj:no
  such file or directory

##[error]/usr/bin/docker failed with return code: 1  ##[section]Finishing: Build a container image

Body:
[error]COPY failed: stat/var/lib/docker/tmp/docker-builder158012929/DockerTest/DockerTest.csproj: no such file or directory

According to this error message, the error occurred on the line of your dockerfile:              COPY ["DockerTest/DockerTest.csproj", "DockerTest/"].

First, please confirm that you did not use .dockerignore file to exclude this file: DockerTest/DockerTest.csproj, which must exists in the directory where you run your build from.

If it does not ignored by .dockerignore file, then you need to consider about your dockerfile location level.

DockerTest.csproj file should not put at the lower source file path level. You need to change the source of the context, move it at a higher level. So modify your dockerfile manually as :

COPY ["DockerTest.csproj", "DockerTest/"]


问:
Submitting a HTML form with AJAX that includes a file input
Can you submit a form via AJAX that has a file type input? I am trying to use jquery to do this but it appears that it cannot serialize the file being submitted. Is this something that is blocked by the browser as a security concern? Is there a way around it?</p>

答:
I downvoted Scott Harwell without giving a proper explanation of why I downvoted. I downvoted because this CAN be done and I do it consistently.  My code is as follows:

html tag:

```<code> <form id="inputForm1" method="POST" enctype="multipart/form-data" ACTION="">
    <div id="file-attachment">
        <div style="float:left;">file:</div>
        <div id="file-sub" style="float:left;">
            <input type="file" id="WebAccessFile" name="WebAccessFile" size="45" value="">
        </div>
    </div>
 </form>
</code>```

the key is the enctype="multipart/form-data"

My jQuery ajax statement is as follows:

```<code>$.ajaxFileUpload({url:'/LonApps/FoxWeb.exe/EWI/ewiprocedures?Proc=addrelease',
    secureuri: false,
    fileElementId:'WebAccessFile',
    dataType: 'text'
});
</code>```

I use Visual FoxPro as my coding language for this function so I will post my VFP code but you can just adapt this code to which ever coding language you are using:

```<code> loAttachment = Request.FormFieldObject("WebAccessFile")
 lcReleaseMessage = loAttachment.FileName
 lcSaveFile = ""
 IF loAttachment.ContentLength > 0
    lcFileName = loAttachment.FileName
    lcFileContent = loAttachment.Value()
    lcSaveFile = "D:\Website\Publish\Depts\EWI\docs\" + lcFileName
    SET SAFETY OFF
    STRTOFILE(lcFileContent, lcSaveFile)
    SET SAFETY ON
    lcHTTPSaveFile = "/Publish/Depts/EWI/docs/" + lcFileName
 ENDIF
</code>```

This is receiving the input value as loAttachment (lo stands for Local Object).  Then, among other things it is finding if the attachment content length is greater than 0, if it is then it is saving the attachment to a local web directory for later access.

ContentLicense: CC BY-SA 3.0

Body:
I downvoted Scott Harwell without giving a proper explanation of why I downvoted. I downvoted because this CAN be done and I do it consistently.  My code is as follows:

html tag:

 <form id="inputForm1" method="POST" enctype="multipart/form-data" ACTION="">
    <div id="file-attachment">
        <div style="float:left;">file:</div>
        <div id="file-sub" style="float:left;">
            <input type="file" id="WebAccessFile" name="WebAccessFile" size="45" value="">
        </div>
    </div>
 </form>

the key is the enctype="multipart/form-data"

My jQuery ajax statement is as follows:

$.ajaxFileUpload({url:'/LonApps/FoxWeb.exe/EWI/ewiprocedures?Proc=addrelease',
    secureuri: false,
    fileElementId:'WebAccessFile',
    dataType: 'text'
});

I use Visual FoxPro as my coding language for this function so I will post my VFP code but you can just adapt this code to which ever coding language you are using:

 loAttachment = Request.FormFieldObject("WebAccessFile")
 lcReleaseMessage = loAttachment.FileName
 lcSaveFile = ""
 IF loAttachment.ContentLength > 0
    lcFileName = loAttachment.FileName
    lcFileContent = loAttachment.Value()
    lcSaveFile = "D:\Website\Publish\Depts\EWI\docs\" + lcFileName
    SET SAFETY OFF
    STRTOFILE(lcFileContent, lcSaveFile)
    SET SAFETY ON
    lcHTTPSaveFile = "/Publish/Depts/EWI/docs/" + lcFileName
 ENDIF

This is receiving the input value as loAttachment (lo stands for Local Object).  Then, among other things it is finding if the attachment content length is greater than 0, if it is then it is saving the attachment to a local web directory for later access.


问:
Tracking multiple clicks on the same element
Looking for a way to track if an element has been clicked multiple times (for example, a user clicks "Submit" button several times to place an order).

We are doing some work redeveloping a website and in our UX research we found that people don't download PDFs from the site because the link behind the button is broken. We noticed that people tend to click the button several times before giving up, yet some still manage to download the PDF.

In order to show our changes to code have improved site performance and user experiences, we want to show that these "multiple clicks" have decreased.

Since the site uses Google Analytics, I have tried to create a variable in GTM that counts clicks on the same click element (which doesn't work):

```<code>function() {
var the_div = {{Click Element}};
var clickCount = 0;
return clickCount;
}
</code>```

I expect the output to be a count of the times I've clicked on the Click Element (1, 2, 3, etc....)

答:
Use javascript variable with global scope

```<code><script>
countClicks = 0;
    function clickCountFunction() {
         countClicks++;
    }
</script>
</code>```

Add onClick attribute in button and call clickCountFunction() in it

Body:
Looking for a way to track if an element has been clicked multiple times (for example, a user clicks "Submit" button several times to place an order).

We are doing some work redeveloping a website and in our UX research we found that people don't download PDFs from the site because the link behind the button is broken. We noticed that people tend to click the button several times before giving up, yet some still manage to download the PDF.

In order to show our changes to code have improved site performance and user experiences, we want to show that these "multiple clicks" have decreased.

Since the site uses Google Analytics, I have tried to create a variable in GTM that counts clicks on the same click element (which doesn't work):

function() {
var the_div = {{Click Element}};
var clickCount = 0;
return clickCount;
}

I expect the output to be a count of the times I've clicked on the Click Element (1, 2, 3, etc....)

Body:
Use javascript variable with global scope

<script>
countClicks = 0;
    function clickCountFunction() {
         countClicks++;
    }
</script>

Add onClick attribute in button and call clickCountFunction() in it


问:
WKWebView not opening URL with devanagari font in URL
I am trying to integrate a payment gateway integration of a bank. But the WKWebView doesn't load the URL.

The URL which I am trying to load in WKWebView is

Here is URL:
http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=समीम&reserveField5=वार्ड%20क्र%2006%20%20जवाहरलाल&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199

When I try to run the same URL on laptop browser then it's working fine.

I have tried these options:

```<code>let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)

let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
</code>```

What am I doing wrong?

答: The solution to this is: all the characters in url which are in different language should be base64 encoded.</p>

Body:
I am trying to integrate a payment gateway integration of a bank. But the WKWebView doesn't load the URL.

The URL which I am trying to load in WKWebView is

Here is URL:
<a href="http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=%E0%A4%B8%E0%A4%AE%E0%A5%80%E0%A4%AE&reserveField5=%E0%A4%B5%E0%A4%BE%E0%A4%B0%E0%A5%8D%E0%A4%A1%20%E0%A4%95%E0%A5%8D%E0%A4%B0%2006%20%20%E0%A4%9C%E0%A4%B5%E0%A4%BE%E0%A4%B9%E0%A4%B0%E0%A4%B2%E0%A4%BE%E0%A4%B2&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199" rel="nofollow noreferrer">http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=समीम&reserveField5=वार्ड%20क्र%2006%20%20जवाहरलाल&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199

When I try to run the same URL on laptop browser then it's working fine.

I have tried these options:

let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)

let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

What am I doing wrong?


问:
Which representation of a 2D matrix is faster
which way is faster and compiler/cache friendlier, use M[a][b] or M[a*b] when working with matrices?

I tried writing both ways on compiler explorer in a function that allocates, initialises and returns a matrix but I don't know assembly and how much time each instruction takes

int **M = malloc(sizeof(int*)*m)
for(i=0; i<m; ++i) {
  *M = malloc(sizeof(int)*n);
  for(int j = 0; j < n; ++j){
    M[j] = j;
  }
```

<p>vs</p>

<pre class="lang-c prettyprint-override"><code>int *M = malloc(m*n*sizeof(int));
for(i = 0; i < m*n; ++i) M[i] = i;
</code>```

I expect the second way to be faster.

答:
If your problem (and the respective solution) require a 2D array, then just use a 2D array: M[a][b].

You must have in mind that the memory is addressed linearly anyway. The concepts of multi-dimensional arrays are just a layer implemented on top of the linear memory.

Nowadays, the compilers are quite highly optimized, so they will do a better job of "linearizeing" a 2D array, than you can. Additionally, if you do it, the code will be a lot more difficult to write and maintain.

Body:
which way is faster and compiler/cache friendlier, use M[a][b] or M[a*b] when working with matrices?

I tried writing both ways on compiler explorer in a function that allocates, initialises and returns a matrix but I don't know assembly and how much time each instruction takes

int **M = malloc(sizeof(int*)*m)
for(i=0; i<m; ++i) {
  *M = malloc(sizeof(int)*n);
  for(int j = 0; j < n; ++j){
    M[j] = j;
  }

vs

int *M = malloc(m*n*sizeof(int));
for(i = 0; i < m*n; ++i) M[i] = i;

I expect the second way to be faster.


问:
How to concise this code? Get an array's property (title) by a second array's shared property (_id)
The following code works but how can I make it more concise?
In two arrays, we have a common property (_id). With this property, I get a property from array 2.
More specific:
Array 'movies' contains items movie with properties '_id' and 'title'.
Array 'favoritemovies' contains only '_id'.
I want to return the user's list of favorite movies as titles. </p>

```<code>var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

var movieTitles = [];

for (var i = 0; i < favoritemovies.length; i++) {
    var favMovies = movies.filter(movie => movie._id == favoritemovies[i])

movieTitles.push(favMovies);

var movieTitlesFlat = movieTitles.flat();
}

for (var i = 0; i < favoritemovies.length; i++) {
  console.log(movieTitlesFlat[i].title);
}
</code>```

答:
Reduce into an object indexed by _id, then call .map on the favoritemovies, for an overall complexity of O(N):

var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];
const moviesById = movies.reduce((a, { _id, title }) => {
  a[_id] = title;
  return a;
}, {});

const titles = favoritemovies.map(id => moviesById[id]);
console.log(titles);```

(this could also be done with a nested loop operation, but without transforming the movies into a map of some sort first, complexity will be O(N^2))

Body:
The following code works but how can I make it more concise?
In two arrays, we have a common property (_id). With this property, I get a property from array 2.
More specific:
Array 'movies' contains items movie with properties '_id' and 'title'.
Array 'favoritemovies' contains only '_id'.
I want to return the user's list of favorite movies as titles.

var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

var movieTitles = [];

for (var i = 0; i < favoritemovies.length; i++) {
    var favMovies = movies.filter(movie => movie._id == favoritemovies[i])

movieTitles.push(favMovies);

var movieTitlesFlat = movieTitles.flat();
}

for (var i = 0; i < favoritemovies.length; i++) {
  console.log(movieTitlesFlat[i].title);
}

Body:
Reduce into an object indexed by _id, then call .map on the favoritemovies, for an overall complexity of O(N):

var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];
const moviesById = movies.reduce((a, { _id, title }) => {
  a[_id] = title;
  return a;
}, {});

const titles = favoritemovies.map(id => moviesById[id]);
console.log(titles);

(this could also be done with a nested loop operation, but without transforming the movies into a map of some sort first, complexity will be O(N^2))


答:
You can use first use filter() on movies to get all the items whose _id is present inside favoritemovies then map() on the that filtered array to get titles.

var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

const res = movies.filter(x => favoritemovies.includes(x._id)).map(x => x.title);
console.log(res)```
</div>
</div>
</p>

<p>The above algorithm will have <code>O(n ^ 2)</code> time complexity. It can be made <code>O(n)</code> by creating and <code>Set</code> from <code>favoritemovies</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var favoritemovies = [1111,3333];
let favmovset = new Set(favoritemovies)
const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

const res = movies.filter(x => favmovset.has(x._id)).map(x => x.title);
console.log(res)</code>```

Title: How to concise this code? Get an array's property (title) by a second array's shared property (_id)

Body:
You can use first use filter() on movies to get all the items whose _id is present inside favoritemovies then map() on the that filtered array to get titles.

var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

const res = movies.filter(x => favoritemovies.includes(x._id)).map(x => x.title);
console.log(res)

The above algorithm will have O(n ^ 2) time complexity. It can be made O(n) by creating and Set from favoritemovies

var favoritemovies = [1111,3333];
let favmovset = new Set(favoritemovies)
const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

const res = movies.filter(x => favmovset.has(x._id)).map(x => x.title);
console.log(res)


问:
How to pass dynamic parameters to rest api in android when using viewmodel
I am fetching news details from News Api site. I am using ViewModel architecture so that the device does not fetch the results when orientation changes.

As per various turorials i am able to fetch the result to a recyclerview using retrofit and viewmodel buy giving static parameters as query to the rest api.

private void loadTopHeadlines() {
        ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines("in", 20, 1,
                "api_key");
        response.enqueue(new Callback<TopHeadlinesResponse>() {
            @Override
            public void onResponse(Call<TopHeadlinesResponse> call, Response<TopHeadlinesResponse> response) {
                topHeadlinesResponse.setValue(response.body().getArticles());
            }

            @Override
            public void onFailure(Call<TopHeadlinesResponse> call, Throwable t) {

            }
        });
    }
```

<p>As you can see in the ViewModel class that is created the method getTopHeadlines() uses static parameters. How do i change it to dynamic parameters.</p>

<p>Static parameter </p>

<pre class="lang-java prettyprint-override"><code>Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines("in", 20, 1,
                "api_key");
</code>```

Dynamic parameter

Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines(dynamic, dynamic, dynamic,
                "api_key");
```

答:
So basically your method should accept those parameters, e.g.:</p>

```<code>private void loadHeadlines(String stringValue, int number, int otherNumer)
//...do some stuff
Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines(stringValue, number, otherNumber, "api_key");
//rest stays the same
}
</code>```

Body:
I am fetching news details from News Api site. I am using ViewModel architecture so that the device does not fetch the results when orientation changes.

As per various turorials i am able to fetch the result to a recyclerview using retrofit and viewmodel buy giving static parameters as query to the rest api.

private void loadTopHeadlines() {
        ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines("in", 20, 1,
                "api_key");
        response.enqueue(new Callback<TopHeadlinesResponse>() {
            @Override
            public void onResponse(Call<TopHeadlinesResponse> call, Response<TopHeadlinesResponse> response) {
                topHeadlinesResponse.setValue(response.body().getArticles());
            }

            @Override
            public void onFailure(Call<TopHeadlinesResponse> call, Throwable t) {

            }
        });
    }

As you can see in the ViewModel class that is created the method getTopHeadlines() uses static parameters. How do i change it to dynamic parameters.

Static parameter

Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines("in", 20, 1,
                "api_key");

Dynamic parameter

Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines(dynamic, dynamic, dynamic,
                "api_key");

Body:
So basically your method should accept those parameters, e.g.:

private void loadHeadlines(String stringValue, int number, int otherNumer)
//...do some stuff
Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines(stringValue, number, otherNumber, "api_key");
//rest stays the same
}


问:
MapStruct ignore automatically unmapped properties
I am using MapStruct with big models (more than 50 fields) shared between different business use cases in my code. Depending on the entry point, some properties will be mapped and some not. When I build my project, I will always get the "WARNING: Unmapped target properties" message.

I have researched and seen that it is possible to tell the mapstruct to ignore the field by using the semantic

```<code>@Mapping(target = "propName", ignore = true)
</code>```

The problem is, given my objects with so many fields, it would take a lot of code to ignore each single property in each mapper class. I also do not want this Warning on my log. Is there any way to tell mapstruct to ignore what is not mapped, avoiding this message?

答:
For ignore automapping
MapStruct 1.3.0.Final Reference Guide:

By means of the @BeanMapping(ignoreByDefault = true) the default
  behavior will be explicit mapping, meaning that all mappings have to
  be specified by means of the @Mapping and no warnings will be issued
  on missing target properties.

```<code>@BeanMapping(ignoreByDefault = true)
OneObj map(TwoObj two);
</code>```

Body:
I am using MapStruct with big models (more than 50 fields) shared between different business use cases in my code. Depending on the entry point, some properties will be mapped and some not. When I build my project, I will always get the "WARNING: Unmapped target properties" message.

I have researched and seen that it is possible to tell the mapstruct to ignore the field by using the semantic

@Mapping(target = "propName", ignore = true)

The problem is, given my objects with so many fields, it would take a lot of code to ignore each single property in each mapper class. I also do not want this Warning on my log. Is there any way to tell mapstruct to ignore what is not mapped, avoiding this message?

Body:
For ignore automapping
MapStruct 1.3.0.Final Reference Guide:

By means of the @BeanMapping(ignoreByDefault = true) the default
  behavior will be explicit mapping, meaning that all mappings have to
  be specified by means of the @Mapping and no warnings will be issued
  on missing target properties.

@BeanMapping(ignoreByDefault = true)
OneObj map(TwoObj two);


问:
How a save in a list the elements of a first list that are not contained in a second list with duplicate values?
I have a problem with a heuristic for Virtual Graph where I have to count the elements of numbers from two integer lists: I have to put in a list the numbers of the first one and the numbers that are not in the second list.

I've tried with two addAll and a removeAll(secondList) and it works but when the lists have duplicates It doesn't work because removes the duplicate element too:

        //Test lists
        List<Integer> ls1 = Arrays.asList(1,1,2,3);
        List<Integer> ls3 = Arrays.asList(1,3);
        List<Integer> s = new ArrayList<>();

        s.addAll(ls1);
        System.out.println("Add " + ls1);
        s.addAll(ls3);
        System.out.println("Add " + ls3);
        System.out.println("New list" + s);
        s.removeAll(ls3);
        System.out.println("Expected value (1,2)");
        System.out.println("Result List " + s);
```

The new list is [1, 1, 2, 3, 1, 3] and the expected output is [1,2] but the actual output is only 2.

答:
Hi @Guillermo Garrido,

It looks like you want to substract list two from list one.

If you are using apache-commons in your project then you can do it simply by following line :

```<code>import import org.apache.commons.collections.ListUtils;
List<Integer> s = ListUtils.subtract(ls1, ls2);
</code>```

Or if you want to do it using simple java then look at @Naman 's answer.

Body:
I have a problem with a heuristic for Virtual Graph where I have to count the elements of numbers from two integer lists: I have to put in a list the numbers of the first one and the numbers that are not in the second list.

I've tried with two addAll and a removeAll(secondList) and it works but when the lists have duplicates It doesn't work because removes the duplicate element too:

        //Test lists
        List<Integer> ls1 = Arrays.asList(1,1,2,3);
        List<Integer> ls3 = Arrays.asList(1,3);
        List<Integer> s = new ArrayList<>();

        s.addAll(ls1);
        System.out.println("Add " + ls1);
        s.addAll(ls3);
        System.out.println("Add " + ls3);
        System.out.println("New list" + s);
        s.removeAll(ls3);
        System.out.println("Expected value (1,2)");
        System.out.println("Result List " + s);

The new list is [1, 1, 2, 3, 1, 3] and the expected output is [1,2] but the actual output is only 2.

Body:
Hi @Guillermo Garrido,

It looks like you want to substract list two from list one.

If you are using apache-commons in your project then you can do it simply by following line :

import import org.apache.commons.collections.ListUtils;
List<Integer> s = ListUtils.subtract(ls1, ls2);

Or if you want to do it using simple java then look at @Naman 's answer.


答:
It seems like both features and weights are 5-vectors.

- When simply multiplying them using * operator you get their element-wise multiplication.

- When transposing one of them (using view()) and then applying element-wise multiplication with * operator, Pytorch broadcast the corresponding singleton dimensions resulting with outer-product of the two vectors: res_ij  = w_i * f_j.

- Finally, you apply matrix multiplication torch.mm to the two vectors, resulting with their inner product.

Title: Pytorch : Results of vector multiplications are different for same input

Body:
I did not understand why these multiplication outputs are different.

print(features*weights)
print('------------')
print(features*weights.view(5,1))
print('------------')
print(torch.mm(features,weights.view(5,1)))

outputs:

tensor([[ 0.1314, -0.2796,  1.1668, -0.1540, -2.8442]])
------------
tensor([[ 0.1314, -0.7035, -0.8472,  0.9971, -1.5130],
        [ 0.0522, -0.2796, -0.3367,  0.3963, -0.6013],
        [-0.1809,  0.9688,  1.1668, -1.3733,  2.0837],
        [-0.0203,  0.1086,  0.1308, -0.1540,  0.2336],
        [ 0.2469, -1.3224, -1.5927,  1.8745, -2.8442]])
------------
tensor([[-1.9796]])


问:
Redis Connection Failure error occurs when getting application.properties from config-server
I have a Redis service running in localhost:6379 and the spring-boot microservice connects to this redis service by reading the hostname and port from the application.properties file.

```<code>@Configuration
public class RedisConfiguration {

    /**
    * redis host.
    */
    @Value("${spring.redis.host}")
    private String redisHost;

    /**
     * redis port.
     */
    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration(redisHost, redisPort);
    return new JedisConnectionFactory(redisConf);
}
</code>```

In the application.properties file, the properties given are -

```<code>spring.redis.host=localhost
spring.redis.port=6379
</code>```

This works Perfectly when i am running the microservice in default profile that is it uses the default application.properties from the /src/main/resources folder.

Now the Challenge I am facing is that, when i run the microservice in test profile, it has to fetch the properties file from the config-server which clones it from a github repo.

In this scenario, the redis service is showing an error like this

[ERROR][2019-05-30 15:48:33,761][pool-1-thread-4|org.springframework.data.redis.listener.RedisMessageListenerContainer:handleSubscriptionException:651] Connection failure occurred. Restarting subscription task after 5000 ms

This error occurs only when i am getting the properties file from the config-service.

The application-test.properties in the github repo is also having the correct redis configurations.

Please help me resolve this issue.

答: Finally, after lot of debugging i found out what was going wrong. It was due to the unwanted space at the end of spring.redis.host=localhost that was causing this issue.

Body:
I have a Redis service running in localhost:6379 and the spring-boot microservice connects to this redis service by reading the hostname and port from the application.properties file.

@Configuration
public class RedisConfiguration {

    /**
    * redis host.
    */
    @Value("${spring.redis.host}")
    private String redisHost;

    /**
     * redis port.
     */
    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration(redisHost, redisPort);
    return new JedisConnectionFactory(redisConf);
}

In the application.properties file, the properties given are -

spring.redis.host=localhost
spring.redis.port=6379

This works Perfectly when i am running the microservice in default profile that is it uses the default application.properties from the /src/main/resources folder.

Now the Challenge I am facing is that, when i run the microservice in test profile, it has to fetch the properties file from the config-server which clones it from a github repo.

In this scenario, the redis service is showing an error like this

[ERROR][2019-05-30 15:48:33,761][pool-1-thread-4|org.springframework.data.redis.listener.RedisMessageListenerContainer:handleSubscriptionException:651] Connection failure occurred. Restarting subscription task after 5000 ms

This error occurs only when i am getting the properties file from the config-service.

The application-test.properties in the github repo is also having the correct redis configurations.

Please help me resolve this issue.


问:
Elixir - Looping through and adding to map
I'm rebuilding something in Elixir from some code I built in C#.

It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild).

Essentially what it did was check some RSS feeds and see if there was any new content. This is the code:

```<code>Map historic (URL as key, post title as value).
List<string> blogfeeds
while true
for each blog in blogfeeds
   List<RssPost> posts = getposts(blog)
   for each post in posts
        if post.url is not in historic
           dothing(post)
           historic.add(post)
</code>```

I am wondering how I can do Enumeration effectively in Elixir. Also, it seems that my very process of adding things to "historic" is anti-functional programming.

Obviously the first step was declaring my list of URLs, but beyond that the enumeration idea is messing with my head. Could someone help me out? Thanks.

答:
I am also new to Elixir but here is a cute and simple solution that uses pattern matching and recursion.

```<code>defmodule YourModule do
   def reduce_list([], reduced) do reduced end

   def reduce_list([first | rest ], reduced) do
      # Do what you need to do here and call the function again
      # with remaining list items and updated map.
      reduce_list(rest, Map.put(reduced, first, "Done"))
   end
end
</code>```

And call the function with just the list you want to map and an empty map

```<code>> YourModule.reduce_list(["one", "two", "three"], %{})
  %{"one" => "Done", "three" => "Done", "two" => "Done"}
</code>```

Body:
I'm rebuilding something in Elixir from some code I built in C#.

It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild).

Essentially what it did was check some RSS feeds and see if there was any new content. This is the code:

Map historic (URL as key, post title as value).
List<string> blogfeeds
while true
for each blog in blogfeeds
   List<RssPost> posts = getposts(blog)
   for each post in posts
        if post.url is not in historic
           dothing(post)
           historic.add(post)

I am wondering how I can do Enumeration effectively in Elixir. Also, it seems that my very process of adding things to "historic" is anti-functional programming.

Obviously the first step was declaring my list of URLs, but beyond that the enumeration idea is messing with my head. Could someone help me out? Thanks.

Body:
I am also new to Elixir but here is a cute and simple solution that uses pattern matching and recursion.

defmodule YourModule do
   def reduce_list([], reduced) do reduced end

   def reduce_list([first | rest ], reduced) do
      # Do what you need to do here and call the function again
      # with remaining list items and updated map.
      reduce_list(rest, Map.put(reduced, first, "Done"))
   end
end

And call the function with just the list you want to map and an empty map

> YourModule.reduce_list(["one", "two", "three"], %{})
  %{"one" => "Done", "three" => "Done", "two" => "Done"}


问:
Chart.js get the nearest point when clicked on canvas
is there a way to get the nearest point when clicked anywhere on canvas? Maybe somehow harvest the core 'nearest' method? Thanks</p>

答:
I believe you are looking for
.getElementAtEvent and .getElementsAtEvent (https://www.chartjs.org/docs/latest/developers/api.html#getelementsatevente)

What you can do - is set up a clickHandler function that will grab the event from onClick and use it to return the chart element under it.

Here is an example from the official docs:

```<code>function clickHandler(evt) {
    var firstPoint = myChart.getElementAtEvent(evt)[0];

    if (firstPoint) {
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
    }
}
</code>```

After, just add it to your chart canvas (again, from the official docs):

```<code>canvas.onclick = clickHandler;
</code>```

Body:
I believe you are looking for
.getElementAtEvent and .getElementsAtEvent (https://www.chartjs.org/docs/latest/developers/api.html#getelementsatevente)

What you can do - is set up a clickHandler function that will grab the event from onClick and use it to return the chart element under it.

Here is an example from the official docs:

function clickHandler(evt) {
    var firstPoint = myChart.getElementAtEvent(evt)[0];

    if (firstPoint) {
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
    }
}

After, just add it to your chart canvas (again, from the official docs):

canvas.onclick = clickHandler;


问:
Is it possible to handle the Environmental Variables within the Batch Script?
I created a very simple batch file as a launcher for a python script, however it does not work fine depending on the "PATH" setup for the user (Python 2 x Python 3).
Since changing the PATH can bring issues with other Python 2 based applications , could I make any update in the .bat to make a temporary change in the PATH while the Py script is running?

The idea is to use the batch to have the minimum interference from the user in the system setup (preferable a double click only).
In case of yes, what could I do?

```<code>@echo off
title ###Beta Script Launcher###
python myscript.py
pause
</code>```

答:
Yes you can edit the environment variables in batch script by using the following command

```<code>setx path "%PATH%;C:\New Folder"
</code>```

based on wherever your python that you want to use is installed.
But this will change the path permanently

Body:
I created a very simple batch file as a launcher for a python script, however it does not work fine depending on the "PATH" setup for the user (Python 2 x Python 3).
Since changing the PATH can bring issues with other Python 2 based applications , could I make any update in the .bat to make a temporary change in the PATH while the Py script is running?

The idea is to use the batch to have the minimum interference from the user in the system setup (preferable a double click only).
In case of yes, what could I do?

@echo off
title ###Beta Script Launcher###
python myscript.py
pause

Body:
Yes you can edit the environment variables in batch script by using the following command

setx path "%PATH%;C:\New Folder"

based on wherever your python that you want to use is installed.
But this will change the path permanently


问:
I have a long string which contains dates in multiple formats (dd-mm-yyyy, mm-dd-yyyy etc.) . How do I convert them all into the same format?
I am working on Python. I have many long texts of data. Each text can be treated as a string. Within each string, I need to separate the string into elements of a list where ever a date is present.

```<code>eg. long string1 (date format: mm.dd.yyyy):

05.12.2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.13.2016 15:58:31  sdfasjdcakscsdv
01.14.2016fsdkjgfdhkvjxdbvxd

eg. long string2 (date format: dd/mm/yyyy):

05/12/2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.1.2016 15:58:31  sdfasjdcakscsdv
21/11/2016fsdkjgfdhkvjxdbvxd
</code>```

Step1: I need to write a generalized code such that I can pass both strings in the same code.

Step2: Objective of the code is to convert string into list with elements
  separated by date.

eg. long string 1 to list 1
[05.12.2016 15:58:31 jsfkgskdlfsgfdslkcbj, 05.13.2016 15:58:31  sdfasjdcakscsdv, 01.14.2016fsdkjgfdhkvjxdbvxd]

Step 3: and then take the element with the earliest date

output from above example: 01.14.2016fsdkjgfdhkvjxdbvxd

I got help for doing Step 2 and 3 and I can do it when all strings have the same date format. But my challenge is first reading a string and figuring out which date format it is using and then parsing and sorting it on the basis of date

I have code if one date format is given.

```<code>text = '05/12/2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.1.2016 15:58:31  sdfasjdcakscsdv 21/11/2016fsdkjgfdhkvjxdbvxd'

list1 = list()
for d, t in zip(*[iter(re.split(r'(\d+[\/.]\d+[\/.]\d+ \d+:\d+:\d+)', text)[1:])]*2):
    list1.append(d + t)

from datetime import datetime
list_sorted=sorted(list1,key=lambda s: datetime.strptime(s[0:19], "%d.%m.%Y %H:%M:%S") if '.' in s[0:19] else datetime.strptime(s[0:19], "%d/%m/%Y %H:%M:%S"))

complaint = list_sorted[0]
print(complaint)
</code>```

The above code works well for a single string for a single date format. How do I generalize it to first detect the date format in the string and then parse it accordingly

答:
You can use dateutil.parser present in the dateutil module which can parse the date-time string for you irrespective of the format

```<code>In [17]: from dateutil import parser

In [18]: parser.parse('05/12/2016 15:58:31', fuzzy=True)
Out[18]: datetime.datetime(2016, 5, 12, 15, 58, 31)

In [19]: parser.parse('05.1.2016 15:58:31', fuzzy=True)
Out[19]: datetime.datetime(2016, 5, 1, 15, 58, 31)

In [20]: parser.parse('21/11/2016', fuzzy=True)
Out[20]: datetime.datetime(2016, 11, 21, 0, 0)
</code>```

Or another example which collects the datetime objects and sort the original list according to it

```<code>from dateutil import parser

#List of textdate srings
textdate = ['5.13.2001 21:23:54 fgdsgd', '05.12.2001 09:43:32 arfehfks']

#Collect datetime objects
dates = []
for item in textdate:
    dates.append(parser.parse(item, fuzzy=True))

#Sort datetime objects and obtained original list on sorting
res = [textdate[i[0]] for i in sorted(enumerate(dates), key=lambda x:x[1])]
print(res)
</code>```

The output will be

```<code>['05.12.2001 09:43:32 arfehfks', '5.13.2001 21:23:54 fgdsgd']
</code>```

Body:
I am working on Python. I have many long texts of data. Each text can be treated as a string. Within each string, I need to separate the string into elements of a list where ever a date is present.

eg. long string1 (date format: mm.dd.yyyy):

05.12.2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.13.2016 15:58:31  sdfasjdcakscsdv
01.14.2016fsdkjgfdhkvjxdbvxd

eg. long string2 (date format: dd/mm/yyyy):

05/12/2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.1.2016 15:58:31  sdfasjdcakscsdv
21/11/2016fsdkjgfdhkvjxdbvxd

Step1: I need to write a generalized code such that I can pass both strings in the same code.

Step2: Objective of the code is to convert string into list with elements
  separated by date.

eg. long string 1 to list 1
[05.12.2016 15:58:31 jsfkgskdlfsgfdslkcbj, 05.13.2016 15:58:31  sdfasjdcakscsdv, 01.14.2016fsdkjgfdhkvjxdbvxd]

Step 3: and then take the element with the earliest date

output from above example: 01.14.2016fsdkjgfdhkvjxdbvxd

I got help for doing Step 2 and 3 and I can do it when all strings have the same date format. But my challenge is first reading a string and figuring out which date format it is using and then parsing and sorting it on the basis of date

I have code if one date format is given.

text = '05/12/2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.1.2016 15:58:31  sdfasjdcakscsdv 21/11/2016fsdkjgfdhkvjxdbvxd'

list1 = list()
for d, t in zip(*[iter(re.split(r'(\d+[\/.]\d+[\/.]\d+ \d+:\d+:\d+)', text)[1:])]*2):
    list1.append(d + t)

from datetime import datetime
list_sorted=sorted(list1,key=lambda s: datetime.strptime(s[0:19], "%d.%m.%Y %H:%M:%S") if '.' in s[0:19] else datetime.strptime(s[0:19], "%d/%m/%Y %H:%M:%S"))

complaint = list_sorted[0]
print(complaint)

The above code works well for a single string for a single date format. How do I generalize it to first detect the date format in the string and then parse it accordingly

Body:
You can use dateutil.parser present in the dateutil module which can parse the date-time string for you irrespective of the format

In [17]: from dateutil import parser

In [18]: parser.parse('05/12/2016 15:58:31', fuzzy=True)
Out[18]: datetime.datetime(2016, 5, 12, 15, 58, 31)

In [19]: parser.parse('05.1.2016 15:58:31', fuzzy=True)
Out[19]: datetime.datetime(2016, 5, 1, 15, 58, 31)

In [20]: parser.parse('21/11/2016', fuzzy=True)
Out[20]: datetime.datetime(2016, 11, 21, 0, 0)

Or another example which collects the datetime objects and sort the original list according to it

from dateutil import parser

#List of textdate srings
textdate = ['5.13.2001 21:23:54 fgdsgd', '05.12.2001 09:43:32 arfehfks']

#Collect datetime objects
dates = []
for item in textdate:
    dates.append(parser.parse(item, fuzzy=True))

#Sort datetime objects and obtained original list on sorting
res = [textdate[i[0]] for i in sorted(enumerate(dates), key=lambda x:x[1])]
print(res)

The output will be

['05.12.2001 09:43:32 arfehfks', '5.13.2001 21:23:54 fgdsgd']


问:
How can I create an alias for a function that executes another command?
The command looks like this

```<code>vim -o `fzf`
</code>```

I need to create an alias for this command. But when I source ~/.zshrc, fzf command gets executed. The alias opens what I already opened using the fzf prompt.

答:
Okay I found this out. The solution is to create a zsh function and place it inside the ~/.zshrc file.

```<code>function vo() {
  vim -o `fzf`
}
</code>```

Body:
The command looks like this

vim -o `fzf`

I need to create an alias for this command. But when I source ~/.zshrc, fzf command gets executed. The alias opens what I already opened using the fzf prompt.

Body:
Okay I found this out. The solution is to create a zsh function and place it inside the ~/.zshrc file.

function vo() {
  vim -o `fzf`
}


问:
How to format numbers (or text) with jQuery?
I would like to modify (or to format) the display of numbers with jQuery: each group of three digits separated by a space.

Now when I send data with Php, the formatting is retained. It's boring to end up with an IP address formatted, for instance!

How to fix it?

```<code>$(document).ready(function()
//$(function()
{
        $('h1, h2, h3, h4, h5, h6, p, li, dt, dd, caption, tr').each(function()
        {
            var $h = $(this);
            var html = $h.html();
            html = html.replace(/(\d{3-2})[\s\.]{0,1}(\d{3})/g, "$1 $2");
            html = html.replace(/(\d{1})[\s\.]{0,1}(\d{3})/g, "$1$2");
            // html
            $h.html(html);
    })
</code>```

;
});

Thanks for your help.

Regards,

Vincent

答:
If I understood you question properly, you can achieve what you want by changing:

```<code> html = html.replace(/(\d{3-2})[\s\.]{0,1}(\d{3})/g, "$1 $2");
 html = html.replace(/(\d{1})[\s\.]{0,1}(\d{3})/g, "$1$2");
</code>```

into:

```<code> html = html.replace(/(\d{1-3})[\s\.]{0,1}(\d{3})/g, "$1 $2");
</code>```

From your text and the code I don't understand well why you do html.replace twice if your aim is to split the numbers in groups of 3 digits separated by a space

Body:
I would like to modify (or to format) the display of numbers with jQuery: each group of three digits separated by a space.

Now when I send data with Php, the formatting is retained. It's boring to end up with an IP address formatted, for instance!

How to fix it?

$(document).ready(function()
//$(function()
{
        $('h1, h2, h3, h4, h5, h6, p, li, dt, dd, caption, tr').each(function()
        {
            var $h = $(this);
            var html = $h.html();
            html = html.replace(/(\d{3-2})[\s\.]{0,1}(\d{3})/g, "$1 $2");
            html = html.replace(/(\d{1})[\s\.]{0,1}(\d{3})/g, "$1$2");
            // html
            $h.html(html);
    })

;
});

Thanks for your help.

Regards,

Vincent

Body:
If I understood you question properly, you can achieve what you want by changing:

 html = html.replace(/(\d{3-2})[\s\.]{0,1}(\d{3})/g, "$1&#160;$2");
 html = html.replace(/(\d{1})[\s\.]{0,1}(\d{3})/g, "$1$2");

into:

 html = html.replace(/(\d{1-3})[\s\.]{0,1}(\d{3})/g, "$1&#160;$2");

From your text and the code I don't understand well why you do html.replace twice if your aim is to split the numbers in groups of 3 digits separated by a space


问:
Im trying to send a command list through serial port but only the first line is taken by the device others are ignored
I am trying to send a message including carriage returns (represented without pressing enter) over a serial connection. It works if i press enter with an open serial connection, but I have not found a way to represent the carriage return character successfully within the message body. Need to reprsent the "CR" in txt file.

how could I close the file descriptor (fd) of the serial port before sending next command line?

Note:  the modem documentation says: In order to successfully communicate with modem device, the “$WP” prefix is required when issuing command and the "CR" is required for terminating the command line.

I tried minicom/picocom over /dev/ttyACM0, but same issues only first line of command is performed

答:
You can use printf:

```<code>$ printf 'whatever\r' > /dev/ttyACM0
</code>```

to send the CR

Body:
You can use printf:

$ printf 'whatever\r' > /dev/ttyACM0

to send the CR


问:
Check modifierFlags of NSEvent if a certain modifier was pressed but no other
I just experimented with the addLocalMonitorForEventsMatchingMask:handler: method in NSEvent and came across the following question: How do I find out if only certain modifiers were pressed?

A short example to set this question into context: I wanted to listen for the shortcut "⌘+W". Therefore I wrote the following code:

```<code>[NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *theEvent) {
    if ([theEvent modifierFlags] & NSCommandKeyMask && [theEvent keyCode] == 13) {
        [self.window performClose:self];
    }
    return theEvent;
}];
</code>```

This works well, however the shortcut will be triggered, even if more modifier keys are pressed, e.g. "⌃+⌘+W" or "⇧+⌃+⌥+⌘+W". Is there a way to circumvent this?

A simple solution would be to check for all other modifier keys and ensure they are not pressed. This seems tedious and error prone - besides it's ugly enough as it is now with the unary "&". In addition you may get into trouble if (for some reason) another modifier key is added to keyboard layouts.

As always I'm thankful for any recommendations.

答:
Swift 5 version

```<code>if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command {
    // Got it!
}
</code>```

Body:
I just experimented with the addLocalMonitorForEventsMatchingMask:handler: method in NSEvent and came across the following question: How do I find out if only certain modifiers were pressed?

A short example to set this question into context: I wanted to listen for the shortcut "⌘+W". Therefore I wrote the following code:

[NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *theEvent) {
    if ([theEvent modifierFlags] & NSCommandKeyMask && [theEvent keyCode] == 13) {
        [self.window performClose:self];
    }
    return theEvent;
}];

This works well, however the shortcut will be triggered, even if more modifier keys are pressed, e.g. "⌃+⌘+W" or "⇧+⌃+⌥+⌘+W". Is there a way to circumvent this?

A simple solution would be to check for all other modifier keys and ensure they are not pressed. This seems tedious and error prone - besides it's ugly enough as it is now with the unary "&". In addition you may get into trouble if (for some reason) another modifier key is added to keyboard layouts.

As always I'm thankful for any recommendations.

Body:
Swift 5 version

if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command {
    // Got it!
}


问:
How to stop caching of particular div using wp rocket cache plugin?
How to stop caching of particular div using wp rocket cache plugin?

答:
As per my knowledge it is not possible to STOP cache for specific DIV or SPAN etc.

In order to disable page caching, you can just install and activate this helper plugin: using this plugin.
Ref. https://docs.wp-rocket.me/article/61-disable-page-caching

OR use this method --> Excluding a Page From Cache via DONOTCACHEPAGE
 - Exclude files and Page from cache

Also you can clear cache for any specific PAGE OR POST by following way.

Clear cache on specific post/page
There are two ways of clearing cache on specific posts/pages.

Visit the Pages or Posts section in WordPress, and roll over a page or post table row to see a Clear this cache action  link

Another way to do this is in on the post or page Edit screen. In the Editor panel, the Clear cache button can be found in the Publish meta box.


问:
How to convert chrome.storage.sync.get to browser.storage.sync.get? (or, how to use Promises)
I am trying to port an extension but my JS is very rusty.  https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities says The equivalent WebExtensions APIs use promises instead:

Original:

```<code>    var read = function(name, deflt) {
            return new Promise(function(resolve){
                    chrome.storage.sync.get([name], function(result){
                            if (chrome.runtime.lastError)
                                    throw new Error(chrome.runtime.lastError);
                            resolve(result[name] || deflt);
                    });
            });
    };
</code>```

I feel there should be a very simple and nice solution to this because the code should return a promise and browser.storage.sync.get also happens to return a promise already... I just don't know how.

答:
Since browser.storage.sync.get returns a Promise (and assuming the signature is the same as the chrome version), something like this should be equivalent. This returns a Promise immediately, which you can call then() and catch() on to handle success and error cases respectively

```<code>var read = function(name, deflt) {
  return browser.storage.sync.get([name])
    .then(result => {
      if (browser.runtime.lastError) { // assuming this exists
        throw new Error(browser.runtime.lastError);
      }

      return result[name] || deflt
    })
};

read('foo', 'barDefault')
  .then(doStuffWithResult)
  .catch(console.error)
</code>```

Body:
I am trying to port an extension but my JS is very rusty.  https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities says The equivalent WebExtensions APIs use promises instead:

Original:

    var read = function(name, deflt) {
            return new Promise(function(resolve){
                    chrome.storage.sync.get([name], function(result){
                            if (chrome.runtime.lastError)
                                    throw new Error(chrome.runtime.lastError);
                            resolve(result[name] || deflt);
                    });
            });
    };

I feel there should be a very simple and nice solution to this because the code should return a promise and browser.storage.sync.get also happens to return a promise already... I just don't know how.

Body:
Since browser.storage.sync.get returns a Promise (and assuming the signature is the same as the chrome version), something like this should be equivalent. This returns a Promise immediately, which you can call then() and catch() on to handle success and error cases respectively

var read = function(name, deflt) {
  return browser.storage.sync.get([name])
    .then(result => {
      if (browser.runtime.lastError) { // assuming this exists
        throw new Error(browser.runtime.lastError);
      }

      return result[name] || deflt
    })
};

read('foo', 'barDefault')
  .then(doStuffWithResult)
  .catch(console.error)


问:
MAXIFS multiple criteria ignoring NA() data
I am trying to get the maximum value of a column within a certain range and ignore the NA() values that are in the column. All of the data in the column that is not NA() is greater than zero. I have tried ignoring the NA(), >=0 and the AGGREGATE function does not have the MAXIFS only the MAX function.

```<code>=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,"<>NA()")
=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,">=0")
</code>```

It displays the #VALUE!

答:
Well, tried this and it seems to work fine:

```<code>=MAXIFS(A1:A11,A1:A11,">"&0)
</code>```

Body:
I am trying to get the maximum value of a column within a certain range and ignore the NA() values that are in the column. All of the data in the column that is not NA() is greater than zero. I have tried ignoring the NA(), >=0 and the AGGREGATE function does not have the MAXIFS only the MAX function.

=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,"<>NA()")
=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,">=0")

It displays the #VALUE!

Body:
Well, tried this and it seems to work fine:

=MAXIFS(A1:A11,A1:A11,">"&0)


问:
How can I save the id of a child record in the parent without calling .save again?
I have a problem where legacy code was calling .save inside an after_save callback until Rails 5.1, but because of how saved_change_to_attribute replaces attribute_changed? in after_ callbacks, it is a problem to call .save twice (.save affects .changes).

I now need to replicate the same behaviour without calling .save twice.

In my Rails 5.1.7 app (preparing for 5.2 upgrade):

```<code>class OtherModel < ApplicationRecord
  belongs_to :my_model, inverse_of: :other_model_history
end

class MyModel < ApplicationRecord
  has_many :other_model_history, class_name: 'OtherModel', inverse_of: :my_model
  belongs_to :latest_other_model, class_name: 'OtherModel'
  before_create :initialize_first_other_model

  def initialize_first_other_model
    initial_other = OtherModel.new(name: 'initial')
    other_model_history << initial_other
    latest_other_model = initial_other
    # When it finally reaches save (this is before_create) I want ActiveRecord to know
    # to save the ID of initial_other in latest_other_model_id ... but it doesn't
  end
end
</code>```

When MyModel.new.save is called, initialize_other_model creates the initial OtherModel instance with the correct other_model.my_model_id based on my_model.id.

BUT, the my_model.latest_other_model_id is nil. This is despite
latest_other_model correctly referencing the initial_other object.

How can I tell ActiveRecord that it must set my_model.latest_other_model_id = initial_other.id?

EDIT: with ActiveRecord::Base.logger = Logger.new(STDOUT)

```<code>DEBUG -- :   SQL (0.3ms)  INSERT INTO "my_models" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2019-05-31 06:12:27.006455"], ["updated_at", "2019-05-31 06:12:27.006455"]]
DEBUG -- :   SQL (0.1ms)  INSERT INTO "other_models" ("my_model_id", "name", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["my_model_id", 3], ["name", "initial"], ["created_at", "2019-05-31 06:12:27.015472"], ["updated_at", "2019-05-31 06:12:27.015472"]]
DEBUG -- :    (1.5ms)  commit transaction
</code>```

You can see that MyModel is inserted first, without the other_model, then OtherModel is inserted with the id from MyModel. I want Rails to also know to then insert my_models.latest_other_model_id, without calling .save

答:
I was able to use update_column in after_save. This saves the reference from my_model to other_model without affecting saved_changes. My callbacks are now

before_create:

```<code>  initial_other = OtherModel.new(name: 'initial')
  other_model_history << initial_other
</code>```

after_save:

```<code>update_column('latest_other_model_id', other_model_history.last.id)
</code>```

Note: I wouldn't recommend this style of initialising inside callbacks to anyone who doesn't have it forced upon them by legacy code. This feels very fragile.

Body:
I have a problem where legacy code was calling .save inside an after_save callback until Rails 5.1, but because of how saved_change_to_attribute replaces attribute_changed? in after_ callbacks, it is a problem to call .save twice (.save affects .changes).

I now need to replicate the same behaviour without calling .save twice.

In my Rails 5.1.7 app (preparing for 5.2 upgrade):

class OtherModel < ApplicationRecord
  belongs_to :my_model, inverse_of: :other_model_history
end

class MyModel < ApplicationRecord
  has_many :other_model_history, class_name: 'OtherModel', inverse_of: :my_model
  belongs_to :latest_other_model, class_name: 'OtherModel'
  before_create :initialize_first_other_model

  def initialize_first_other_model
    initial_other = OtherModel.new(name: 'initial')
    other_model_history << initial_other
    latest_other_model = initial_other
    # When it finally reaches save (this is before_create) I want ActiveRecord to know
    # to save the ID of initial_other in latest_other_model_id ... but it doesn't
  end
end

When MyModel.new.save is called, initialize_other_model creates the initial OtherModel instance with the correct other_model.my_model_id based on my_model.id.

BUT, the my_model.latest_other_model_id is nil. This is despite
latest_other_model correctly referencing the initial_other object.

How can I tell ActiveRecord that it must set my_model.latest_other_model_id = initial_other.id?

EDIT: with ActiveRecord::Base.logger = Logger.new(STDOUT)

DEBUG -- :   SQL (0.3ms)  INSERT INTO "my_models" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2019-05-31 06:12:27.006455"], ["updated_at", "2019-05-31 06:12:27.006455"]]
DEBUG -- :   SQL (0.1ms)  INSERT INTO "other_models" ("my_model_id", "name", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["my_model_id", 3], ["name", "initial"], ["created_at", "2019-05-31 06:12:27.015472"], ["updated_at", "2019-05-31 06:12:27.015472"]]
DEBUG -- :    (1.5ms)  commit transaction

You can see that MyModel is inserted first, without the other_model, then OtherModel is inserted with the id from MyModel. I want Rails to also know to then insert my_models.latest_other_model_id, without calling .save

Body:
I was able to use update_column in after_save. This saves the reference from my_model to other_model without affecting saved_changes. My callbacks are now

before_create:

  initial_other = OtherModel.new(name: 'initial')
  other_model_history << initial_other

after_save:

update_column('latest_other_model_id', other_model_history.last.id)

Note: I wouldn't recommend this style of initialising inside callbacks to anyone who doesn't have it forced upon them by legacy code. This feels very fragile.


问:
What to do with XML node names (hard coded values)?
I've been working with xml lately.  And have noticed a bit of a phenomenon (maybe not that big of a deal to the rest of the world, but to me it was).  Perhaps, it is me being a newb.  But shouldn't most hard coded or magic numbers be broken out to a configuration file?  For example,

```<code>    string url = "http://www.domain.com/aDocument.xml";
    XmlDocument feed = new XmlDocument();
    feed.Load(url);

    XmlNode errorsNode = feed.SelectSingleNode("Errors");

    if (errorsNode != null)
    {
        XmlNode error = errorsNode.FirstChild;
        lblError.Text = "Error: " + error.SelectSingleNode("Code").InnerText;
    }
</code>```

Here is the xml document:

```<code>  <Errors>
    <Error>
        <Code>AWS.MissingParameters</Code>
        <Message>You are missing an parameter</Message>
    </Error>
 </Errors>
</code>```

How would you parse this without hardcoding "code" or "message"?

答:
Same as I would for numbers.  I'd declare constants of type string which have the name of the element to get, and then pass that to the methods on my XML tools.

However, you might want to consider creating an object representation from the XML document (or schema if you have it) which would handle all of this for you.  This way, you can just load up the XML document into the code, and it will do the parsing for you into an object representation.

Then, if the XML changes, you would modify the generated code to use your new element names.

You want to use the XSD.EXE tool for this.

ContentLicense: CC BY-SA 2.5

Body:
I've been working with xml lately.  And have noticed a bit of a phenomenon (maybe not that big of a deal to the rest of the world, but to me it was).  Perhaps, it is me being a newb.  But shouldn't most hard coded or magic numbers be broken out to a configuration file?  For example,

    string url = "http://www.domain.com/aDocument.xml";
    XmlDocument feed = new XmlDocument();
    feed.Load(url);

    XmlNode errorsNode = feed.SelectSingleNode("Errors");

    if (errorsNode != null)
    {
        XmlNode error = errorsNode.FirstChild;
        lblError.Text = "Error: " + error.SelectSingleNode("Code").InnerText;
    }

Here is the xml document:

  <Errors>
    <Error>
        AWS.MissingParameters
        <Message>You are missing an parameter</Message>
    </Error>
 </Errors>

How would you parse this without hardcoding "code" or "message"?

OwnerDisplayName: casperOne


问:
CSS - List tree background issue
I have a list with multiple sections. I try to make it look like a kind of tree. It started quite well but I can't fix the last bits.

The code can be found at:

http://jsfiddle.net/Kwfpm/

Here is how it should work

The first "Datorer", "Mjukvara" and
"Microsoft" should be connected to
the tree with a horisontal line.

"Mjukvara" at the bottom left should
be connected to "Kategorier".

There are some repeated problems but these should be solved if the two above is solved.

Here is a link what it should look like (without the collapsing things):

Open and close to see the tree:
http://jquery.bassistance.de/treeview/demo/prerendered.html

Info

I don't know how many levels there are.

The HTML can't be changed because its generated by Wordpress

Use backgrounds or borders to show what you got.

If JSfiddle don't work you can use this:

CSS

```<code>    * {
    margin: 0;
    padding: 0;
}
.sidebar > ul > li {
    background: none;
}
li {
    padding-left: 20px;
    list-style: none;
    background: url('http://www.jenst.se/images/normal.png') repeat-y 10px 0;
    color: #333;
    font-family: Arial;
    font-size: 13px;
    line-height: 22px;
}
li a {
    color: #555;
}
li:last-child {
    background: url('http://www.jenst.se/images/lastchild.png') no-repeat 10px 0px;
}
</code>```

HTML

```<code><div class="sidebar default">
<ul>
    <li id="categories-10" class="widget widget_categories">
        <h4 class="title">Kategorier</h4>
        <ul>
            <li class="cat-item cat-item-7"><a href="http://localhost/concepts/addmod/category/sjukt-lang-kategori-som-tar-for-mycket-plats/" title="Se alla inlägg sparade under Datorer">Datorer</a>
            </li>
            <li class="cat-item cat-item-3"><a href="http://localhost/concepts/addmod/category/testkategori/" title="Se alla inlägg sparade under Mjukvara">Mjukvara</a>
                <ul class='children'>
                    <li class="cat-item cat-item-4"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/" title="Se alla inlägg sparade under Hårdvara">Hårdvara</a>
                        <ul class='children'>
                            <li class="cat-item cat-item-6"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/underkategori-2/" title="Se alla inlägg sparade under Microsoft">Microsoft</a>
                            </li>
                            <li class="cat-item cat-item-9"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/bla/" title="Se alla inlägg sparade under Office-paket">Office-paket</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li class="cat-item cat-item-3"><a href="http://localhost/concepts/addmod/category/testkategori/" title="Se alla inlägg sparade under Mjukvara">Mjukvara</a>
                <ul class='children'>
                    <li class="cat-item cat-item-4"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/" title="Se alla inlägg sparade under Hårdvara">Hårdvara</a>
                        <ul class='children'>
                            <li class="cat-item cat-item-6"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/underkategori-2/" title="Se alla inlägg sparade under Microsoft">Microsoft</a>
                            </li>
                            <li class="cat-item cat-item-9"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/bla/" title="Se alla inlägg sparade under Office-paket">Office-paket</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
    <li id="categories-10" class="widget widget_categories">
        <ul>
            <li class="cat-item cat-item-7"><a href="http://localhost/concepts/addmod/category/sjukt-lang-kategori-som-tar-for-mycket-plats/" title="Se alla inlägg sparade under Datorer">Datorer</a>
            </li>
            <li class="cat-item cat-item-3"><a href="http://localhost/concepts/addmod/category/testkategori/" title="Se alla inlägg sparade under Mjukvara">Mjukvara</a>
                <ul class='children'>
                    <li class="cat-item cat-item-4"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/" title="Se alla inlägg sparade under Hårdvara">Hårdvara</a>
                        <ul class='children'>
                            <li class="cat-item cat-item-6"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/underkategori-2/" title="Se alla inlägg sparade under Microsoft">Microsoft</a>
                            </li>
                            <li class="cat-item cat-item-9"><a href="http://localhost/concepts/addmod/category/testkategori/underkategori/bla/" title="Se alla inlägg sparade under Office-paket">Office-paket</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>
</div>
</code>```

答:
Have a look at this javascript treeview: http://krijnhoetmer.nl/stuff/javascript/list-treeview-menu/

It does have a same structure as you prefer with li's and ul's. Maybe you could take a look at it with firebug.

Title: CSS - List tree background issue

Body:
I have a list with multiple sections. I try to make it look like a kind of tree. It started quite well but I can't fix the last bits.

The code can be found at:

http://jsfiddle.net/Kwfpm/

Here is how it should work

The first "Datorer", "Mjukvara" and
"Microsoft" should be connected to
the tree with a horisontal line.

"Mjukvara" at the bottom left should
be connected to "Kategorier".

There are some repeated problems but these should be solved if the two above is solved.

Here is a link what it should look like (without the collapsing things):

Open and close to see the tree:
http://jquery.bassistance.de/treeview/demo/prerendered.html

Info

I don't know how many levels there are.

The HTML can't be changed because its generated by Wordpress

Use backgrounds or borders to show what you got.

If JSfiddle don't work you can use this:

CSS

    * {
    margin: 0;
    padding: 0;
}
.sidebar > ul > li {
    background: none;
}
li {
    padding-left: 20px;
    list-style: none;
    background: url('http://www.jenst.se/images/normal.png') repeat-y 10px 0;
    color: #333;
    font-family: Arial;
    font-size: 13px;
    line-height: 22px;
}
li a {
    color: #555;
}
li:last-child {
    background: url('http://www.jenst.se/images/lastchild.png') no-repeat 10px 0px;
}

HTML

Kategorier

Datorer

Mjukvara

Hårdvara

Microsoft

Office-paket

Mjukvara

Hårdvara

Microsoft

Office-paket

Datorer

Mjukvara

Hårdvara

Microsoft

Office-paket