问:
Save MNIST dataset with added noise
I want to save the new MNIST dataset tensors after adding noise.

```<code>mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())

def add_noise(dataset):
  for data in dataset:
      img, _ = data[0], data[1]
      noisy_data = torch.tensor(random_noise(img, mode='gaussian', mean=0, var=0.05, clip=True))
      return noisy_data

train_gauss = add_noise(mnist_trainset)
</code>```

The code above only saves one image of the MNIST dataset, how can I save all tensors at once?

答:
Your return is inside the for loop, so at the end of the first iteration it already returns the noisy_data.

You should take it out of the for loop and then you could use a list to return the whole dataset at once, like so:

```<code>mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())

def add_noise(dataset):
  noisy_data = []
  for data in dataset:
      img, _ = data[0], data[1]
      noisy_data += torch.tensor(random_noise(img, mode='gaussian', mean=0, var=0.05, clip=True))
  return noisy_data

train_gauss = add_noise(mnist_trainset)
</code>```

Title: Save MNIST dataset with added noise

Body:
I want to save the new MNIST dataset tensors after adding noise.

mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())

def add_noise(dataset):
  for data in dataset:
      img, _ = data[0], data[1]
      noisy_data = torch.tensor(random_noise(img, mode='gaussian', mean=0, var=0.05, clip=True))
      return noisy_data

train_gauss = add_noise(mnist_trainset)

The code above only saves one image of the MNIST dataset, how can I save all tensors at once?

Body:
Your return is inside the for loop, so at the end of the first iteration it already returns the noisy_data.

You should take it out of the for loop and then you could use a list to return the whole dataset at once, like so:

mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())

def add_noise(dataset):
  noisy_data = []
  for data in dataset:
      img, _ = data[0], data[1]
      noisy_data += torch.tensor(random_noise(img, mode='gaussian', mean=0, var=0.05, clip=True))
  return noisy_data

train_gauss = add_noise(mnist_trainset)


来源: stackexchange

问:
Dockerfile "COPY" command confusion
I have 3 .NET6 projects in my local 'src' folder as below:

src/A

src/B

src/C

A: web api project, has many nuget dependencies

B: class lib, dependent of A

C: class lib, dependent of A

(Note: of course, project related files including .csproj are present in the local project folders)

My Dockerfile is in project folder A.
I am running the "docker build" command from 'src' folder (i.e. this is the build context) as below:

```<code>docker build -f A/Dockerfile -t myapiimage:v1 .
</code>```

below section of code is from my Dockerfile, where i try to restore nuget dependencies:

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ./A/*.csproj A/
RUN dotnet restore A/A.csproj
</code>```

this works fine and i understand that .csproj in the image is stored inside /src/A/A.csproj
Am i right?

I want to know whether COPY preserves the source folder structure in the image being built or not?

because after the below 3 lines:

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY *.csproj ./
</code>```

None of the line works:

```<code>RUN dotnet restore A/A.csproj
</code>```

OR,

```<code>RUN dotnet restore A.csproj
</code>```

OR,

```<code>RUN dotnet restore *A.csproj
</code>```

OR,

```<code>RUN dotnet restore src/A/A.csproj
</code>```

So, where this .csproj files (of all 3 projects) are getting stored in the image?

答:
Your line COPY *.csproj ./ doesn't copy anything, because there are no .csproj files in your src directory on the host machine.

The way I usually do it is a bit clunky. First I do

```<code>COPY */*.csproj ./
</code>```

which copies all the .csproj files into the workdir in the image. Then I do

```<code>RUN for file in $(ls *.csproj); do mkdir -p ${file%.*}/ && mv $file ${file%.*}/; done
</code>```

which looks at all the .csproj files and creates a directory for them and moves them into that directory.

With that approach, your Dockerfile would look like this

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY */*.csproj ./
RUN for file in $(ls *.csproj); do mkdir -p ${file%.*}/ && mv $file ${file%.*}/; done
RUN dotnet restore A/A.csproj
</code>```

ContentLicense: CC BY-SA 4.0

Title: Dockerfile "COPY" command confusion

Body:
I have 3 .NET6 projects in my local 'src' folder as below:

src/A

src/B

src/C

A: web api project, has many nuget dependencies

B: class lib, dependent of A

C: class lib, dependent of A

(Note: of course, project related files including .csproj are present in the local project folders)

My Dockerfile is in project folder A.
I am running the "docker build" command from 'src' folder (i.e. this is the build context) as below:

docker build -f A/Dockerfile -t myapiimage:v1 .

below section of code is from my Dockerfile, where i try to restore nuget dependencies:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ./A/*.csproj A/
RUN dotnet restore A/A.csproj

this works fine and i understand that .csproj in the image is stored inside /src/A/A.csproj
Am i right?

I want to know whether COPY preserves the source folder structure in the image being built or not?

because after the below 3 lines:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY *.csproj ./

None of the line works:

RUN dotnet restore A/A.csproj

OR,

RUN dotnet restore A.csproj

OR,

RUN dotnet restore *A.csproj

OR,

RUN dotnet restore src/A/A.csproj

So, where this .csproj files (of all 3 projects) are getting stored in the image?

Body:
Your line COPY *.csproj ./ doesn't copy anything, because there are no .csproj files in your src directory on the host machine.

The way I usually do it is a bit clunky. First I do

COPY */*.csproj ./

which copies all the .csproj files into the workdir in the image. Then I do

RUN for file in $(ls *.csproj); do mkdir -p ${file%.*}/ && mv $file ${file%.*}/; done

which looks at all the .csproj files and creates a directory for them and moves them into that directory.

With that approach, your Dockerfile would look like this

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY */*.csproj ./
RUN for file in $(ls *.csproj); do mkdir -p ${file%.*}/ && mv $file ${file%.*}/; done
RUN dotnet restore A/A.csproj


问:
Why does this .c file #include itself?
Why does this .c file #include itself?

https://github.com/powturbo/TurboPFor-Integer-Compression

vsimple.c

```<code>#define USIZE 8
#include "vsimple.c"
#undef USIZE

#define USIZE 16
#include "vsimple.c"
#undef USIZE

#define USIZE 32
#include "vsimple.c"
#undef USIZE

#define USIZE 64
#include "vsimple.c"
#undef USIZE
</code>```

答:
The file includes itself so the same source code can be used to generate 4 different sets of functions for specific values of the macro USIZE.

The #include directives are actually enclosed in an #ifndef, which limits the recursion to a single level:

```<code>#ifndef USIZE

// common definitions
...
//

#define VSENC vsenc
#define VSDEC vsdec

#define USIZE 8
#include "vsimple.c"
#undef USIZE

#define USIZE 16
#include "vsimple.c"
#undef USIZE

#define USIZE 32
#include "vsimple.c"
#undef USIZE

#define USIZE 64
#include "vsimple.c"
#undef USIZE

#else // defined(USIZE)

// macro expanded size specific functions using token pasting

...

#define uint_t TEMPLATE3(uint, USIZE, _t)

unsigned char *TEMPLATE2(VSENC, USIZE)(uint_t *__restrict in, size_t n, unsigned char *__restrict out) {
   ...
}

unsigned char *TEMPLATE2(VSDEC, USIZE)(unsigned char *__restrict ip, size_t n, uint_t *__restrict op) {
   ...
}

#endif
</code>```

The functions defined in this module are

```<code>// vsencNN: compress array with n unsigned (NN bits in[n]) values to the buffer out. Return value = end of compressed output buffer out
unsigned char *vsenc8( unsigned char  *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsenc16(unsigned short *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsenc32(unsigned       *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsenc64(uint64_t       *__restrict in, size_t n, unsigned char  *__restrict out);

// vsdecNN: decompress buffer into an array of n unsigned values. Return value = end of compressed input buffer in
unsigned char *vsdec8( unsigned char  *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsdec16(unsigned char  *__restrict in, size_t n, unsigned short *__restrict out);
unsigned char *vsdec32(unsigned char  *__restrict in, size_t n, unsigned       *__restrict out);
unsigned char *vsdec64(unsigned char  *__restrict in, size_t n, uint64_t       *__restrict out);
</code>```

They are all expanded from the two function definitions in vsimple.c:

```<code>unsigned char *TEMPLATE2(VSENC, USIZE)(uint_t *__restrict in, size_t n, unsigned char *__restrict out) {
   ...
}

unsigned char *TEMPLATE2(VSDEC, USIZE)(unsigned char *__restrict ip, size_t n, uint_t *__restrict op) {
   ...
}
</code>```

The TEMPLATE2 and TEMPLATE3 macros are defined in conf.h as

```<code>#define TEMPLATE2_(_x_, _y_) _x_##_y_
#define TEMPLATE2(_x_, _y_) TEMPLATE2_(_x_,_y_)

#define TEMPLATE3_(_x_,_y_,_z_) _x_##_y_##_z_
#define TEMPLATE3(_x_,_y_,_z_) TEMPLATE3_(_x_, _y_, _z_)
</code>```

These macros are classic preprocessor constructions to create identifiers via token pasting. TEMPLATE2 and TEMPLATE2_ are more commonly called GLUE and XGLUE.

The function template starts as:

```<code>unsigned char *TEMPLATE2(VSENC, USIZE)(uint_t *__restrict in, size_t n, unsigned char *__restrict out) ...
</code>```

It is expanded in the first recursive inclusion with USIZE defined as 8 into:

```<code>unsigned char *vsenc8(uint8_t *__restrict in, size_t n, unsigned char *__restrict out) ...
</code>```

The second recursive inclusion, with USIZE defined as 16, expands the template as:

```<code>unsigned char *vsenc16(uint16_t *__restrict in, size_t n, unsigned char *__restrict out) ...
</code>```

and 2 more inclusions define vsenc32 and vsenc64.

This usage of preprocessed source code is more common with separate files: one for the instantiating part that has all the common definitions, especially the macros, and a separate file for the code and data templates, which is included multiple times with different macro definitions.

A good example is the generation of enums, string and structures arrays from atom and opcode definitions in QuickJS.

Title: Why does this .c file #include itself?

Body:
Why does this .c file #include itself?

https://github.com/powturbo/TurboPFor-Integer-Compression

vsimple.c

#define USIZE 8
#include "vsimple.c"
#undef USIZE

#define USIZE 16
#include "vsimple.c"
#undef USIZE

#define USIZE 32
#include "vsimple.c"
#undef USIZE

#define USIZE 64
#include "vsimple.c"
#undef USIZE

Body:
The file includes itself so the same source code can be used to generate 4 different sets of functions for specific values of the macro USIZE.

The #include directives are actually enclosed in an #ifndef, which limits the recursion to a single level:

#ifndef USIZE

// common definitions
...
//

#define VSENC vsenc
#define VSDEC vsdec

#define USIZE 8
#include "vsimple.c"
#undef USIZE

#define USIZE 16
#include "vsimple.c"
#undef USIZE

#define USIZE 32
#include "vsimple.c"
#undef USIZE

#define USIZE 64
#include "vsimple.c"
#undef USIZE

#else // defined(USIZE)

// macro expanded size specific functions using token pasting

...

#define uint_t TEMPLATE3(uint, USIZE, _t)

unsigned char *TEMPLATE2(VSENC, USIZE)(uint_t *__restrict in, size_t n, unsigned char *__restrict out) {
   ...
}

unsigned char *TEMPLATE2(VSDEC, USIZE)(unsigned char *__restrict ip, size_t n, uint_t *__restrict op) {
   ...
}

#endif

The functions defined in this module are

// vsencNN: compress array with n unsigned (NN bits in[n]) values to the buffer out. Return value = end of compressed output buffer out
unsigned char *vsenc8( unsigned char  *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsenc16(unsigned short *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsenc32(unsigned       *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsenc64(uint64_t       *__restrict in, size_t n, unsigned char  *__restrict out);

// vsdecNN: decompress buffer into an array of n unsigned values. Return value = end of compressed input buffer in
unsigned char *vsdec8( unsigned char  *__restrict in, size_t n, unsigned char  *__restrict out);
unsigned char *vsdec16(unsigned char  *__restrict in, size_t n, unsigned short *__restrict out);
unsigned char *vsdec32(unsigned char  *__restrict in, size_t n, unsigned       *__restrict out);
unsigned char *vsdec64(unsigned char  *__restrict in, size_t n, uint64_t       *__restrict out);

They are all expanded from the two function definitions in vsimple.c:

unsigned char *TEMPLATE2(VSENC, USIZE)(uint_t *__restrict in, size_t n, unsigned char *__restrict out) {
   ...
}

unsigned char *TEMPLATE2(VSDEC, USIZE)(unsigned char *__restrict ip, size_t n, uint_t *__restrict op) {
   ...
}

The TEMPLATE2 and TEMPLATE3 macros are defined in conf.h as

#define TEMPLATE2_(_x_, _y_) _x_##_y_
#define TEMPLATE2(_x_, _y_) TEMPLATE2_(_x_,_y_)

#define TEMPLATE3_(_x_,_y_,_z_) _x_##_y_##_z_
#define TEMPLATE3(_x_,_y_,_z_) TEMPLATE3_(_x_, _y_, _z_)

These macros are classic preprocessor constructions to create identifiers via token pasting. TEMPLATE2 and TEMPLATE2_ are more commonly called GLUE and XGLUE.

The function template starts as:

unsigned char *TEMPLATE2(VSENC, USIZE)(uint_t *__restrict in, size_t n, unsigned char *__restrict out) ...

It is expanded in the first recursive inclusion with USIZE defined as 8 into:

unsigned char *vsenc8(uint8_t *__restrict in, size_t n, unsigned char *__restrict out) ...

The second recursive inclusion, with USIZE defined as 16, expands the template as:

unsigned char *vsenc16(uint16_t *__restrict in, size_t n, unsigned char *__restrict out) ...

and 2 more inclusions define vsenc32 and vsenc64.

This usage of preprocessed source code is more common with separate files: one for the instantiating part that has all the common definitions, especially the macros, and a separate file for the code and data templates, which is included multiple times with different macro definitions.

A good example is the generation of enums, string and structures arrays from atom and opcode definitions in QuickJS.


问:
How to make bar count start at 1 for a given timeframe?
Is there any way to make the barcount start at 1 for the first bar in the given time frame? as the picture show it now start from the first bar on chart...</p>
```<code>study(title="candle count" ,overlay=true)

i_startTime = input(defval = timestamp("01 Jan 2022 08:30 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Feb 2022 15:30 +0000"), title = "End Time", type = input.time)

inDateRange = time >= i_startTime and time <= i_endTime

Count = inDateRange ? bar_index : na

//Count = bar_index + 1

label.new(time >= i_startTime and time <= i_endTime ? bar_index : na,high,tostring(Count),textcolor=color.blue,style=label.style_none)```

[![`enter image description here`][1]][1]

  [1]: https://i.stack.imgur.com/BhCXH.png
</code>```

答:
Just use your own variable declared with the var keyword so that is isn't reset every bar.</p>
```<code>var int Count = 0

if inDateRange
    Count += 1
</code>```

Body:
Is there any way to make the barcount start at 1 for the first bar in the given time frame? as the picture show it now start from the first bar on chart...

study(title="candle count" ,overlay=true)

i_startTime = input(defval = timestamp("01 Jan 2022 08:30 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Feb 2022 15:30 +0000"), title = "End Time", type = input.time)

inDateRange = time >= i_startTime and time <= i_endTime

Count = inDateRange ? bar_index : na

//Count = bar_index + 1

label.new(time >= i_startTime and time <= i_endTime ? bar_index : na,high,tostring(Count),textcolor=color.blue,style=label.style_none)```

[![`enter image description here`][1]][1]

  [1]: https://i.stack.imgur.com/BhCXH.png

Body:
Just use your own variable declared with the var keyword so that is isn't reset every bar.

var int Count = 0

if inDateRange
    Count += 1


问:
flex mobile project: Establish http connection to a specific url
how to establish http connection to a specific url and get data from that url in flex mobile project.

Thanks

答:
Did you try doing any research?

http://help.adobe.com/en_US/flex/mobileapps/index.html

http://help.adobe.com/en_US/flex/mobileapps/developing_mobile_apps_flex.pdf

http://help.adobe.com/en_US/flex/accessingdata/WS2db454920e96a9e51e63e3d11c0bf69084-7ff2.html

ContentLicense: CC BY-SA 3.0


问:
How to load this dynamic website with Selenium
Trying to load this dynamic website but failed. Anyone can help?</p>
```<code>driver = webdriver.Chrome()
driver.get('https://apply.95559.com.cn/personbank/portals/ptQuotaQryCoins.do')
</code>```

答:
Not that super clear about the issue you are facing while loading the dynamic website. However I was able to load the website using the following code block:

Code Block:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('https://apply.95559.com.cn/personbank/portals/ptQuotaQryCoins.do')
</code>```

Browser Snapshot:

Body:
Trying to load this dynamic website but failed. Anyone can help?

driver = webdriver.Chrome()
driver.get('https://apply.95559.com.cn/personbank/portals/ptQuotaQryCoins.do')

Body:
Not that super clear about the issue you are facing while loading the dynamic website. However I was able to load the website using the following code block:

Code Block:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('https://apply.95559.com.cn/personbank/portals/ptQuotaQryCoins.do')

Browser Snapshot:


问:
Fatal Error DISPLAY variable set incorrectly: :0
I want to install oracle weblogic server. I already downloaded it and it's fmw_12.1.3.0.0_wls.jar. In order to install it I'm instructed to run java -jar fmw_12.1.3.0.0_wls.jar. But when I run it I get

```<code>(...)X-Server access is denied on host
[Fatal Error] DISPLAY variable set incorrectly: :0
[Resolution] Verify that your DISPLAY environment variable is set correctly,
and that there is an X11 server on the system. If you are
running the Oracle Installer as a different user or on a different host,
you may need to use the xhost command to ensure that host/user
has permission to write to your display.

Logs are located here: /tmp/OraInstall2019-03-16_10-36-23PM.
</code>```

My system is: CentOS Linux release 7.6.1810 (Core) My java is: Java(TM) SE Runtime Environment (build 1.7.0_80-b15)

I'm trying to perform this installation locally. I'm confused because every solution I came across assumed that I was logging via ssh or vnc server while I'm definitely not. What I tried:

set $JAVA_HOME to point to my jdk directory.

unset $ORACLE_HOME that was created for the database I have installed.

trying to set DISPLAY    values to some other number than 0 (I know
its stupid but whatever).

reinstall java

I'm thinking if it might be the problem related with graphic drivers. Might it be that the defaults that were installed with X11 are somehow wrong? Or maybe centOS is not compatibile with this software? Should I maybe try oracle linux?

答:
I solved my problem by using jdk 1.8 x64. This issue seemed to be caused by jdk 1.8 x86.
And yes, the problem was similar to yours. Give it a shot.</p>

Body:
I want to install oracle weblogic server. I already downloaded it and it's fmw_12.1.3.0.0_wls.jar. In order to install it I'm instructed to run java -jar fmw_12.1.3.0.0_wls.jar. But when I run it I get

(...)X-Server access is denied on host
[Fatal Error] DISPLAY variable set incorrectly: :0
[Resolution] Verify that your DISPLAY environment variable is set correctly,
and that there is an X11 server on the system. If you are
running the Oracle Installer as a different user or on a different host,
you may need to use the xhost command to ensure that host/user
has permission to write to your display.

Logs are located here: /tmp/OraInstall2019-03-16_10-36-23PM.

My system is: CentOS Linux release 7.6.1810 (Core) My java is: Java(TM) SE Runtime Environment (build 1.7.0_80-b15)

I'm trying to perform this installation locally. I'm confused because every solution I came across assumed that I was logging via ssh or vnc server while I'm definitely not. What I tried:

set $JAVA_HOME to point to my jdk directory.

unset $ORACLE_HOME that was created for the database I have installed.

trying to set DISPLAY    values to some other number than 0 (I know
its stupid but whatever).

reinstall java

I'm thinking if it might be the problem related with graphic drivers. Might it be that the defaults that were installed with X11 are somehow wrong? Or maybe centOS is not compatibile with this software? Should I maybe try oracle linux?


问:
zooming with in the canvas?
Hi i have 4 chart controls in a canvas. when i click a chart control it should zoom relative to the control position. its zoomin perfectly but it is going out side of the canvas.

code

```<code> <Canvas x:Name="SampleCanvas" Background="#F5F7F9" Height="530"    Width="1010">
                    <chartingToolkit:Chart  x:Name="mcChart" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="5" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                    <chartingToolkit:Chart  x:Name="mcChart2" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="410" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform2"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience2"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                    <chartingToolkit:Chart  x:Name="mcChart3" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="0" Canvas.Top="270" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform3"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience3"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                    <chartingToolkit:Chart  x:Name="mcChart4" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="410" Canvas.Top="270" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform4"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience4"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                </Canvas>
</code>```

in code behind i am dynamically passing the element and doing the zoom as below.

```<code>            Storyboard storyBoard = new Storyboard();

            ///////// X Transform
            DoubleAnimation ds = new DoubleAnimation();
            storyBoard.Children.Add(ds);
            ds.From  = 1;
            ds.To = 1.5;
            ds.Duration = new Duration(TimeSpan.FromSeconds(2));
            Storyboard.SetTargetName(ds, "scaleTransform");
            Storyboard.SetTargetProperty(ds, new PropertyPath("(ScaleX)"));

            ////Y Transform

            DoubleAnimation dsy = new DoubleAnimation();
            storyBoard.Children.Add(dsy);
            dsy.From = 1;
            dsy.To = 1.5;
            dsy.Duration = new Duration(TimeSpan.FromSeconds(2));
            Storyboard.SetTargetName(dsy, "scaleTransform");
            Storyboard.SetTargetProperty(dsy, new PropertyPath("(ScaleY)"));
            LayoutRoot.Resources.Remove("unique_id");
            LayoutRoot.Resources.Add("unique_id",storyBoard);

            storyBoard.Begin();
</code>```

i am getting the zoom outside of the canvas for chart2,cahrt3,chart4.

is there anyway to get the zoom center of canvas or  the relative position of the chart ?

Thanks

答:
Add RenderTransformOrigin="0.5,0.5" to the element you are scaling.

e.g.

```<code><Canvas x:Name="SampleCanvas" RenderTransformOrigin="0.5,0.5"...
</code>```

The co-ordindates in a render transform origin are a fraction of the size so 0.5, 0.5 is the middle.

Title: zooming with in the canvas?

Body:
Hi i have 4 chart controls in a canvas. when i click a chart control it should zoom relative to the control position. its zoomin perfectly but it is going out side of the canvas.

code

 <Canvas x:Name="SampleCanvas" Background="#F5F7F9" Height="530"    Width="1010">
                    <chartingToolkit:Chart  x:Name="mcChart" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="5" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                    <chartingToolkit:Chart  x:Name="mcChart2" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="410" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform2"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience2"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                    <chartingToolkit:Chart  x:Name="mcChart3" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="0" Canvas.Top="270" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform3"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience3"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                    <chartingToolkit:Chart  x:Name="mcChart4" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="410" Canvas.Top="270" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform4"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience4"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
                </Canvas>

in code behind i am dynamically passing the element and doing the zoom as below.

            Storyboard storyBoard = new Storyboard();

            ///////// X Transform
            DoubleAnimation ds = new DoubleAnimation();
            storyBoard.Children.Add(ds);
            ds.From  = 1;
            ds.To = 1.5;
            ds.Duration = new Duration(TimeSpan.FromSeconds(2));
            Storyboard.SetTargetName(ds, "scaleTransform");
            Storyboard.SetTargetProperty(ds, new PropertyPath("(ScaleX)"));

            ////Y Transform

            DoubleAnimation dsy = new DoubleAnimation();
            storyBoard.Children.Add(dsy);
            dsy.From = 1;
            dsy.To = 1.5;
            dsy.Duration = new Duration(TimeSpan.FromSeconds(2));
            Storyboard.SetTargetName(dsy, "scaleTransform");
            Storyboard.SetTargetProperty(dsy, new PropertyPath("(ScaleY)"));
            LayoutRoot.Resources.Remove("unique_id");
            LayoutRoot.Resources.Add("unique_id",storyBoard);

            storyBoard.Begin();

i am getting the zoom outside of the canvas for chart2,cahrt3,chart4.

is there anyway to get the zoom center of canvas or  the relative position of the chart ?

Thanks

Body:
Add RenderTransformOrigin="0.5,0.5" to the element you are scaling.

e.g.

<Canvas x:Name="SampleCanvas" RenderTransformOrigin="0.5,0.5"...

The co-ordindates in a render transform origin are a fraction of the size so 0.5, 0.5 is the middle.


问:
Validating form input with preg_match() returns 0 every time
I am validating the form input for a form field labeled 'tags', where users input tags that describe the uploaded image. After this validation, I preg_replace() any spaces with commas such that this input is csv input.

No matter the input, preg_match() returns 0. What am I doing wrong?

I want my tags to include:

Begin with any letters (regardless of case) and/or numbers or space

Contain any letters, numbers, spaces, commas, and hyphens

End with any letters, numbers, spaces, or commas

Here is my regex string:

```<code>$regex = '/^[ ,][a-zA-Z0-9]+(?:[ ,-]+[a-zA-Z0-9])[ ,]$/';
</code>```

This is my preg_match statement contained in an if statement where else exits the program (when preg_match returns 0).

```<code>preg_match($regex, $_POST['tags']) == 1;
</code>```

Here are some example inputs and whether or not they should be valid.

green-outline, triangle, 2d*% => invalid

green-outline, triangle, 2d => valid

green-outline triangle 2d => valid

I have tried the live regex tool at Regex101 but I can't figure out what's wrong.

答:
In that case I think something like this should work:

```<code>/^[\w, \-]+$/g
</code>```

NOTE: I removed the \d I had added previously since it's already included in \w.

https://regex101.com/r/sfulPW/2

Edit

Here's how that regular expression works:

^ indicates the start of the line, that's where we should start matching.

[\w, \-]+ tells to match one or more + of the following:

\w any word character or number (case insensitive)

, any comma

  any space

\- any dash

$ indicates the end of the line, that's where we should stop matching.

The g flag allows us to make multiple matches.

Body:
I am validating the form input for a form field labeled 'tags', where users input tags that describe the uploaded image. After this validation, I preg_replace() any spaces with commas such that this input is csv input.

No matter the input, preg_match() returns 0. What am I doing wrong?

I want my tags to include:

Begin with any letters (regardless of case) and/or numbers or space

Contain any letters, numbers, spaces, commas, and hyphens

End with any letters, numbers, spaces, or commas

Here is my regex string:

$regex = '/^[ ,][a-zA-Z0-9]+(?:[ ,-]+[a-zA-Z0-9])[ ,]$/';

This is my preg_match statement contained in an if statement where else exits the program (when preg_match returns 0).

preg_match($regex, $_POST['tags']) == 1;

Here are some example inputs and whether or not they should be valid.

green-outline, triangle, 2d*% => invalid

green-outline, triangle, 2d => valid

green-outline triangle 2d => valid

I have tried the live regex tool at Regex101 but I can't figure out what's wrong.

Body:
In that case I think something like this should work:

/^[\w, \-]+$/g

NOTE: I removed the \d I had added previously since it's already included in \w.

https://regex101.com/r/sfulPW/2

Edit

Here's how that regular expression works:

^ indicates the start of the line, that's where we should start matching.

[\w, \-]+ tells to match one or more + of the following:

\w any word character or number (case insensitive)

, any comma

  any space

\- any dash

$ indicates the end of the line, that's where we should stop matching.

The g flag allows us to make multiple matches.


问:
Replace multiple "less than values" in different columns in pandas dataframe
I am working with python and pandas. I have a dataset of lab analysis where I am dealing with multiple parameters and detection limits(dl). Many of the samples are reported as below the dl (e.g.<dl,<4)

For example:

import pandas as pd

df=pd.DataFrame([['<4','88.72','<0.09'],['<1','5','<0.09'],['2','17.6','<0.09']], columns=['var_1','var_2','var_3'])
df
```
<p>My goal is to replace all <dl with dl/2 as a float value.</p>
<p>I can do this for one column pretty easily.</p>
```
df['var_3'] = df.var_3.str.replace('<' ,'').astype(float)
df['var_3'] = df['var_3'].apply(lambda x: x/2 if x == 0.09 else x)
df
```
<p>but this requires me looking at the dl and inputting it.</p>
<p>I would like to streamline it to apply it across all variables with one or more detection limits per variable as I have many variables and the detection limit will not always be constant from data frame to data frame this is applied to.</p>
<p>I found something similar in R but not sure how to apply it in python. Any solutions would be appreciated.</p>
<p><strong>Update</strong></p>
<p>So the</p>
```df=df.replace(r'<(.*)', r'\1/2', regex=True).apply(pd.eval)
```
<p>works well with dataframe with just columns with numbers. I assume that is a limitation of the eval function. For some reason I can get the code  to work on smaller dataframes but after I concatenate them the code will not work on the larger dataframe and I get this error message:</p>
```---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/9_/w2qcdj_x2x5852py8xl6b0sh0000gn/T/ipykernel_9403/3946462310.py in <module>
----> 1 MS=MS.replace(r'<(.*)', r'\1/2', regex=True).apply(pd.eval)

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/frame.py in apply(self, func, axis, raw, result_type, args, **kwargs)
   8738             kwargs=kwargs,
   8739         )
-> 8740         return op.apply()
   8741
   8742     def applymap(

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply(self)
    686             return self.apply_raw()
    687
--> 688         return self.apply_standard()
    689
    690     def agg(self):

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply_standard(self)
    810
    811     def apply_standard(self):
--> 812         results, res_index = self.apply_series_generator()
    813
    814         # wrap results

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply_series_generator(self)
    826             for i, v in enumerate(series_gen):
    827                 # ignore SettingWithCopy here in case the user mutates
--> 828                 results[i] = self.f(v)
    829                 if isinstance(results[i], ABCSeries):
    830                     # If we have a view on v, we need to make a copy because

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/computation/eval.py in eval(expr, parser, engine, truediv, local_dict, global_dict, resolvers, level, target, inplace)
    351         eng = ENGINES[engine]
    352         eng_inst = eng(parsed_expr)
--> 353         ret = eng_inst.evaluate()
    354
    355         if parsed_expr.assigner is None:

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/computation/engines.py in evaluate(self)
     78
     79         # make sure no names in resolvers and locals/globals clash
---> 80         res = self._evaluate()
     81         return reconstruct_object(
     82             self.result_type, res, self.aligned_axes, self.expr.terms.return_type

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/computation/engines.py in _evaluate(self)
    119         scope = env.full_scope
    120         _check_ne_builtin_clash(self.expr)
--> 121         return ne.evaluate(s, local_dict=scope)
    122
    123

~/opt/anaconda3/lib/python3.9/site-packages/numexpr/necompiler.py in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
    821
    822     # Create a signature
--> 823     signature = [(name, getType(arg)) for (name, arg) in
    824                  zip(names, arguments)]
    825

~/opt/anaconda3/lib/python3.9/site-packages/numexpr/necompiler.py in <listcomp>(.0)
    821
    822     # Create a signature
--> 823     signature = [(name, getType(arg)) for (name, arg) in
    824                  zip(names, arguments)]
    825

~/opt/anaconda3/lib/python3.9/site-packages/numexpr/necompiler.py in getType(a)
    703     if kind == 'U':
    704         raise ValueError('NumExpr 2 does not support Unicode as a dtype.')
--> 705     raise ValueError("unknown type %s" % a.dtype.name)
    706
    707

ValueError: unknown type object
```

答:
Use replace instead str.replace than eval all expressions:

```<code>>>> df.replace(r'<(.*)', r'\1/2', regex=True).apply(pd.eval)
   var_1  var_2  var_3
0    2.0  88.72  0.045
1    0.5   5.00  0.045
2    2.0  17.60  0.045
</code>```

\1 will be replace by the first capture group .*

Update

Alternative:

```<code>out = df.melt(ignore_index=False)
m = out['value'].str.startswith('<')
out.loc[m, 'value'] = out.loc[m, 'value'].str.strip('<').astype(float) / 2
out = out.reset_index().pivot('index', 'variable', 'value') \
         .rename_axis(index=None, columns=None)
</code>```

Output:

```<code>>>> out
  var_1  var_2  var_3
0   2.0  88.72  0.045
1   0.5      5  0.045
2     2   17.6  0.045
</code>```

Update

Alternative using melt to flatten your dataframe and pivot to reshape to your original dataframe:

```<code>df1 = df.melt(ignore_index=False)
m = df1['value'].str.startswith('<')
df1['value'] = df1['value'].mask(~m).str[1:].astype(float).div(2) \
                           .fillna(df1['value']).astype(float)
df1 = df1.reset_index().pivot_table('value', 'index', 'variable') \
         .rename_axis(index=None, columns=None)
</code>```

Output:

```<code>>>> df1
   var_1  var_2  var_3
0    2.0  88.72  0.045
1    0.5   5.00  0.045
2    2.0  17.60  0.045
</code>```

Body:
I am working with python and pandas. I have a dataset of lab analysis where I am dealing with multiple parameters and detection limits(dl). Many of the samples are reported as below the dl (e.g.<dl,<4)

For example:

import pandas as pd

df=pd.DataFrame([['<4','88.72','<0.09'],['<1','5','<0.09'],['2','17.6','<0.09']], columns=['var_1','var_2','var_3'])
df

My goal is to replace all <dl with dl/2 as a float value.

I can do this for one column pretty easily.

df['var_3'] = df.var_3.str.replace('<' ,'').astype(float)
df['var_3'] = df['var_3'].apply(lambda x: x/2 if x == 0.09 else x)
df

but this requires me looking at the dl and inputting it.

I would like to streamline it to apply it across all variables with one or more detection limits per variable as I have many variables and the detection limit will not always be constant from data frame to data frame this is applied to.

I found something similar in R but not sure how to apply it in python. Any solutions would be appreciated.

Update

So the

df=df.replace(r'<(.*)', r'\1/2', regex=True).apply(pd.eval)

works well with dataframe with just columns with numbers. I assume that is a limitation of the eval function. For some reason I can get the code  to work on smaller dataframes but after I concatenate them the code will not work on the larger dataframe and I get this error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/9_/w2qcdj_x2x5852py8xl6b0sh0000gn/T/ipykernel_9403/3946462310.py in <module>
----> 1 MS=MS.replace(r'<(.*)', r'\1/2', regex=True).apply(pd.eval)

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/frame.py in apply(self, func, axis, raw, result_type, args, **kwargs)
   8738             kwargs=kwargs,
   8739         )
-> 8740         return op.apply()
   8741
   8742     def applymap(

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply(self)
    686             return self.apply_raw()
    687
--> 688         return self.apply_standard()
    689
    690     def agg(self):

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply_standard(self)
    810
    811     def apply_standard(self):
--> 812         results, res_index = self.apply_series_generator()
    813
    814         # wrap results

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply_series_generator(self)
    826             for i, v in enumerate(series_gen):
    827                 # ignore SettingWithCopy here in case the user mutates
--> 828                 results[i] = self.f(v)
    829                 if isinstance(results[i], ABCSeries):
    830                     # If we have a view on v, we need to make a copy because

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/computation/eval.py in eval(expr, parser, engine, truediv, local_dict, global_dict, resolvers, level, target, inplace)
    351         eng = ENGINES[engine]
    352         eng_inst = eng(parsed_expr)
--> 353         ret = eng_inst.evaluate()
    354
    355         if parsed_expr.assigner is None:

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/computation/engines.py in evaluate(self)
     78
     79         # make sure no names in resolvers and locals/globals clash
---> 80         res = self._evaluate()
     81         return reconstruct_object(
     82             self.result_type, res, self.aligned_axes, self.expr.terms.return_type

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/computation/engines.py in _evaluate(self)
    119         scope = env.full_scope
    120         _check_ne_builtin_clash(self.expr)
--> 121         return ne.evaluate(s, local_dict=scope)
    122
    123

~/opt/anaconda3/lib/python3.9/site-packages/numexpr/necompiler.py in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
    821
    822     # Create a signature
--> 823     signature = [(name, getType(arg)) for (name, arg) in
    824                  zip(names, arguments)]
    825

~/opt/anaconda3/lib/python3.9/site-packages/numexpr/necompiler.py in <listcomp>(.0)
    821
    822     # Create a signature
--> 823     signature = [(name, getType(arg)) for (name, arg) in
    824                  zip(names, arguments)]
    825

~/opt/anaconda3/lib/python3.9/site-packages/numexpr/necompiler.py in getType(a)
    703     if kind == 'U':
    704         raise ValueError('NumExpr 2 does not support Unicode as a dtype.')
--> 705     raise ValueError("unknown type %s" % a.dtype.name)
    706
    707

ValueError: unknown type object

Body:
Use replace instead str.replace than eval all expressions:

>>> df.replace(r'<(.*)', r'\1/2', regex=True).apply(pd.eval)
   var_1  var_2  var_3
0    2.0  88.72  0.045
1    0.5   5.00  0.045
2    2.0  17.60  0.045

\1 will be replace by the first capture group .*

Update

Alternative:

out = df.melt(ignore_index=False)
m = out['value'].str.startswith('<')
out.loc[m, 'value'] = out.loc[m, 'value'].str.strip('<').astype(float) / 2
out = out.reset_index().pivot('index', 'variable', 'value') \
         .rename_axis(index=None, columns=None)

Output:

>>> out
  var_1  var_2  var_3
0   2.0  88.72  0.045
1   0.5      5  0.045
2     2   17.6  0.045

Update

Alternative using melt to flatten your dataframe and pivot to reshape to your original dataframe:

df1 = df.melt(ignore_index=False)
m = df1['value'].str.startswith('<')
df1['value'] = df1['value'].mask(~m).str[1:].astype(float).div(2) \
                           .fillna(df1['value']).astype(float)
df1 = df1.reset_index().pivot_table('value', 'index', 'variable') \
         .rename_axis(index=None, columns=None)

Output:

>>> df1
   var_1  var_2  var_3
0    2.0  88.72  0.045
1    0.5   5.00  0.045
2    2.0  17.60  0.045


问:
Pause or slow down considerably Flink (Kafka) source until dependencies are ready
I'm designing a Flink job that basically it's going to:

Read messages from Kafka

Process the incoming messages' data by requesting some more information from external services — for instance, make some HTTP/gRPC calls, retrieve some data, do some aggregation and store some partial results in a database

Propagate results into Elasticsearch

What I don't have clear is how to slow down, or completely pause the Flink job from reading Kafka messages whenever one of the (RESTful / gRPC) services is down, or simply decreasing their performance.

Is there a way to achieve this by using some configuration settings or some Flink built-in component?

答: Flink will automatically slow down the rate at which data is read from Kafka due to backpressure. When the function that's making REST/gRPC calls can't keep up with the data coming from Kafka, its input network buffers will fill up, and data "pushes" from the Kafka source to that operator will be delayed until space opens up.</p>


问:
Toggling A Click Handler Function On an Input Event Listener — Javascript
I'm setting up a form that submits to a MySQL database via PHP and there are server-side validations that take place for security reasons. I would like the frontend validation messages to be handled with JavasScript because there are many similar forms on the site, and would like these linked to the input event listener.

In the following code the submit button has a preventDefault() method on it until the title is more than 10 characters long. I've read that the best way to add and remove preventDefault is via a click handler function, which I'm using.

By default the button has a .prevent-default class on it and this is removed when the input passes the validation.

The Issue I'm Experiencing

The preventDefault and the error message work if the form is submitted when less than 10 characters are typed, and of course if more than 10 characters are typed the form will just submit as expected.

However, when more than 10 characters are initially typed, and the user then deletes some characters to bring the count back below 10, the form still submits on the front end? I would like it to fail again, with the same error message showing after the submit button is clicked.

I think the solution is to toggle the checkValidations() function. I can't seem to be able to do this though.

NOTE: Some of the elements use the forEach loop because on the full site there will be multiple instances of the form.

CodePen Link: https://codepen.io/thechewy/pen/GROEmoN

var dmForm = document.querySelector("form"),

// class name on the submit button
preventSubmit = document.querySelectorAll(".prevent-submit"),
dmTitle = document.querySelector("#dm-title"),

// empty element for error message
dmTitleError = document.querySelector(".js-dm-title-error")

// function that prevents default click action on button and adds warning message
var clickHandler = function(evt) {
    evt.preventDefault()
    if(dmTitle.value.length < 10) {
        dmTitleError.classList.add('warning')
        dmTitleError.textContent = "Title must be more than 10 characters"
    }
}

// checks for 'prevent-submit' class and if present invokes the clickHander function above
if (preventSubmit) {
  preventSubmit.forEach(item => {
    item.addEventListener('click', clickHandler, false)
})

  // removes warning when the user types more than 10 characters
  if (dmForm) {
    dmTitle.addEventListener('input', () => {
      if( dmTitle.value.length > 10) {
        dmTitleError.classList.remove('warning')
        dmTitleError.textContent = ""

        // call the function that removes the preventDefault method
        checkValidations()
      }
    })
  }

function checkValidations(){
  if (dmTitle.value.length > 10) {
    preventSubmit.forEach(item => {
      item.removeEventListener('click', clickHandler, false)
      item.classList.remove('prevent-submit')
    })
  }
}

} // end of 'if (preventSubmit)' statement```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

input,
button {
  padding: 0.5rem;
}

.js-error-message.warning {
    background: #cc1f1f;
    transition: background .5s;
    padding: 0.2rem 0.5rem;
    margin-top: 0.5rem;
    display: inline-block;
    position: absolute;
    bottom: -5rem;
}</code>```

<form method="post">

    <input id="dm-title" name="dm-title">

  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>```

答:
Looks like you do need to remove validation everytime when all is OK, just execute preventDefault if an error is detected:

var dmForm = document.querySelector("form"),

// class name on the submit button
preventSubmit = document.querySelectorAll(".prevent-submit"),
dmTitle = document.querySelector("#dm-title"),

// empty element for error message
dmTitleError = document.querySelector(".js-dm-title-error")

// function that prevents default click action on button and adds warning message
var clickHandler = function(evt) {

    if(dmTitle.value.length < 10) {
        dmTitleError.classList.add('warning')
        dmTitleError.textContent = "Title must be more than 10 characters"
evt.preventDefault(); // <-- prevent from sending and show warning
    }
}

// checks for 'prevent-submit' class and if present invokes the clickHander function above
if (preventSubmit) {
  preventSubmit.forEach(item => {
    item.addEventListener('click', clickHandler, false)
})

  // removes warning when the user types more than 10 characters
  if (dmForm) {
    dmTitle.addEventListener('input', () => {
      if( dmTitle.value.length > 10) {
        dmTitleError.classList.remove('warning')
        dmTitleError.textContent = ""
      }

    })
  }

} // end of 'if (preventSubmit)' statement```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

input,
button {
  padding: 0.5rem;
}

.js-error-message.warning {
    background: #cc1f1f;
    transition: background .5s;
    padding: 0.2rem 0.5rem;
    margin-top: 0.5rem;
    display: inline-block;
    position: absolute;
    bottom: -5rem;
}</code>```

<form method="post">

    <input id="dm-title" name="dm-title">

  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>```

Body:
I'm setting up a form that submits to a MySQL database via PHP and there are server-side validations that take place for security reasons. I would like the frontend validation messages to be handled with JavasScript because there are many similar forms on the site, and would like these linked to the input event listener.

In the following code the submit button has a preventDefault() method on it until the title is more than 10 characters long. I've read that the best way to add and remove preventDefault is via a click handler function, which I'm using.

By default the button has a .prevent-default class on it and this is removed when the input passes the validation.

The Issue I'm Experiencing

The preventDefault and the error message work if the form is submitted when less than 10 characters are typed, and of course if more than 10 characters are typed the form will just submit as expected.

However, when more than 10 characters are initially typed, and the user then deletes some characters to bring the count back below 10, the form still submits on the front end? I would like it to fail again, with the same error message showing after the submit button is clicked.

I think the solution is to toggle the checkValidations() function. I can't seem to be able to do this though.

NOTE: Some of the elements use the forEach loop because on the full site there will be multiple instances of the form.

CodePen Link: https://codepen.io/thechewy/pen/GROEmoN

var dmForm = document.querySelector("form"),

// class name on the submit button
preventSubmit = document.querySelectorAll(".prevent-submit"),
dmTitle = document.querySelector("#dm-title"),

// empty element for error message
dmTitleError = document.querySelector(".js-dm-title-error")

// function that prevents default click action on button and adds warning message
var clickHandler = function(evt) {
    evt.preventDefault()
    if(dmTitle.value.length < 10) {
        dmTitleError.classList.add('warning')
        dmTitleError.textContent = "Title must be more than 10 characters"
    }
}

// checks for 'prevent-submit' class and if present invokes the clickHander function above
if (preventSubmit) {
  preventSubmit.forEach(item => {
    item.addEventListener('click', clickHandler, false)
})

  // removes warning when the user types more than 10 characters
  if (dmForm) {
    dmTitle.addEventListener('input', () => {
      if( dmTitle.value.length > 10) {
        dmTitleError.classList.remove('warning')
        dmTitleError.textContent = ""

        // call the function that removes the preventDefault method
        checkValidations()
      }
    })
  }

function checkValidations(){
  if (dmTitle.value.length > 10) {
    preventSubmit.forEach(item => {
      item.removeEventListener('click', clickHandler, false)
      item.classList.remove('prevent-submit')
    })
  }
}

} // end of 'if (preventSubmit)' statement

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

input,
button {
  padding: 0.5rem;
}

.js-error-message.warning {
    background: #cc1f1f;
    transition: background .5s;
    padding: 0.2rem 0.5rem;
    margin-top: 0.5rem;
    display: inline-block;
    position: absolute;
    bottom: -5rem;
}

<form method="post">

    <input id="dm-title" name="dm-title">

  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>

Body:
Looks like you do need to remove validation everytime when all is OK, just execute preventDefault if an error is detected:

var dmForm = document.querySelector("form"),

// class name on the submit button
preventSubmit = document.querySelectorAll(".prevent-submit"),
dmTitle = document.querySelector("#dm-title"),

// empty element for error message
dmTitleError = document.querySelector(".js-dm-title-error")

// function that prevents default click action on button and adds warning message
var clickHandler = function(evt) {

    if(dmTitle.value.length < 10) {
        dmTitleError.classList.add('warning')
        dmTitleError.textContent = "Title must be more than 10 characters"
evt.preventDefault(); // <-- prevent from sending and show warning
    }
}

// checks for 'prevent-submit' class and if present invokes the clickHander function above
if (preventSubmit) {
  preventSubmit.forEach(item => {
    item.addEventListener('click', clickHandler, false)
})

  // removes warning when the user types more than 10 characters
  if (dmForm) {
    dmTitle.addEventListener('input', () => {
      if( dmTitle.value.length > 10) {
        dmTitleError.classList.remove('warning')
        dmTitleError.textContent = ""
      }

    })
  }

} // end of 'if (preventSubmit)' statement

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

input,
button {
  padding: 0.5rem;
}

.js-error-message.warning {
    background: #cc1f1f;
    transition: background .5s;
    padding: 0.2rem 0.5rem;
    margin-top: 0.5rem;
    display: inline-block;
    position: absolute;
    bottom: -5rem;
}

<form method="post">
  <div class="input-wrapper">
    <input id="dm-title" name="dm-title">
    <p class="js-error-message js-dm-title-error"></p>
  </div>
  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>


问:
Why does loc / iloc selection return NaN rows?
I have a problem that is very frustrating to solve for.  I'm trying to use .loc to extract a subset of a dataframe since it is large and I want to reduce my memory demand.  The difficulty I am encountering is that non-selected rows are returning with NaN values.

It's particularly difficult to diagnose since its occurring in an async routine in Django, so it hasn't been throwing error messages.

As more detail, if new_df has 20,000 records, I am selecting the first 10,000 records on the first loop, and the second 10,000 on the second loop.  It runs "fine" for the first iteration, but on the second iteration, temp_df has len == 10,000 right after assignment, but somehow by the predict_proba line, temp_df.shape() shows 20,000 records, the first 10,000 of which contain NaN's.

Here is my code:

```<code>   iter_size = int(0.5*len(new_df))

    i = 0
    max_i = len(new_df)
    new_ests = np.zeros(max_i)
    while i < max_i:
        inds = list(range(i, min((i+iter_size), max_i)))
        if len(inds) == 0:
            break
        temp_df = new_df.loc[inds, :]
        temp_df = get_elixr_away(temp_df)
        temp_df = get_segment(temp_df)
        temp_df = get_segment_away(temp_df)
        temp_df['home_pb_lseason'] = 5700
        temp_df['net_pb_bseason'] = 0
        temp_df['net_exp_level'] = 0
        temp_df['net_level_gap'] = 0
        _, temp_df = add_trophs(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_home(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_away(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_home(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_away(temp_df, analysis_sel_cols)
        _, temp_df = code_features(temp_df, analysis_sel_cols)
        _, temp_df = code_away_features(temp_df, analysis_sel_cols)
        _, temp_df = code_home_features(temp_df, analysis_sel_cols)
        temp_df = temp_df.loc[:, analysis_sel_cols]

        ests = (LR_MODEL.predict_proba(temp_df.loc[:, analysis_sel_cols])[:, pred_index])
        del temp_df
</code>```

Unfortunately the NaN values are silently crashing my predict_proba calculation.

Since it's large, I've been deleting temp_df at the end of the loop, but this is not stopping the behaviour.  What am I missing?

答:
I resorted to use of slices to create the subset.  Still not clear why iloc or loc could not be used for this purpose.  Seems contrary to intentions.</p>
```<code>    iter_size = int(0.5*len(new_df))

    i = 0
    max_i = len(new_df)
    new_ests = np.zeros(max_i)
    while i < max_i:
        inds = min((i+iter_size), max_i)
        if inds == 0:
            break
        temp_df = new_df[i:inds].reset_index()
        temp_df = get_elixr_away(temp_df)
        temp_df = get_segment(temp_df)
        temp_df = get_segment_away(temp_df)
        temp_df['home_pb_lseason'] = 5700
        temp_df['net_pb_bseason'] = 0
        temp_df['net_exp_level'] = 0
        temp_df['net_level_gap'] = 0
        _, temp_df = add_trophs(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_home(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_away(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_home(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_away(temp_df, analysis_sel_cols)
        _, temp_df = code_features(temp_df, analysis_sel_cols)
        _, temp_df = code_away_features(temp_df, analysis_sel_cols)
        _, temp_df = code_home_features(temp_df, analysis_sel_cols)
        temp_df = temp_df.loc[:, analysis_sel_cols]

        ests = (LR_MODEL.predict_proba(temp_df.loc[:, analysis_sel_cols])[:, pred_index])
        new_ests[range(i, inds)] = ests

        del temp_df
</code>```

Body:
I have a problem that is very frustrating to solve for.  I'm trying to use .loc to extract a subset of a dataframe since it is large and I want to reduce my memory demand.  The difficulty I am encountering is that non-selected rows are returning with NaN values.

It's particularly difficult to diagnose since its occurring in an async routine in Django, so it hasn't been throwing error messages.

As more detail, if new_df has 20,000 records, I am selecting the first 10,000 records on the first loop, and the second 10,000 on the second loop.  It runs "fine" for the first iteration, but on the second iteration, temp_df has len == 10,000 right after assignment, but somehow by the predict_proba line, temp_df.shape() shows 20,000 records, the first 10,000 of which contain NaN's.

Here is my code:

   iter_size = int(0.5*len(new_df))

    i = 0
    max_i = len(new_df)
    new_ests = np.zeros(max_i)
    while i < max_i:
        inds = list(range(i, min((i+iter_size), max_i)))
        if len(inds) == 0:
            break
        temp_df = new_df.loc[inds, :]
        temp_df = get_elixr_away(temp_df)
        temp_df = get_segment(temp_df)
        temp_df = get_segment_away(temp_df)
        temp_df['home_pb_lseason'] = 5700
        temp_df['net_pb_bseason'] = 0
        temp_df['net_exp_level'] = 0
        temp_df['net_level_gap'] = 0
        _, temp_df = add_trophs(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_home(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_away(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_home(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_away(temp_df, analysis_sel_cols)
        _, temp_df = code_features(temp_df, analysis_sel_cols)
        _, temp_df = code_away_features(temp_df, analysis_sel_cols)
        _, temp_df = code_home_features(temp_df, analysis_sel_cols)
        temp_df = temp_df.loc[:, analysis_sel_cols]

        ests = (LR_MODEL.predict_proba(temp_df.loc[:, analysis_sel_cols])[:, pred_index])
        del temp_df

Unfortunately the NaN values are silently crashing my predict_proba calculation.

Since it's large, I've been deleting temp_df at the end of the loop, but this is not stopping the behaviour.  What am I missing?

Body:
I resorted to use of slices to create the subset.  Still not clear why iloc or loc could not be used for this purpose.  Seems contrary to intentions.

    iter_size = int(0.5*len(new_df))

    i = 0
    max_i = len(new_df)
    new_ests = np.zeros(max_i)
    while i < max_i:
        inds = min((i+iter_size), max_i)
        if inds == 0:
            break
        temp_df = new_df[i:inds].reset_index()
        temp_df = get_elixr_away(temp_df)
        temp_df = get_segment(temp_df)
        temp_df = get_segment_away(temp_df)
        temp_df['home_pb_lseason'] = 5700
        temp_df['net_pb_bseason'] = 0
        temp_df['net_exp_level'] = 0
        temp_df['net_level_gap'] = 0
        _, temp_df = add_trophs(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_home(temp_df, analysis_sel_cols)
        _, temp_df = add_segments_away(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_home(temp_df, analysis_sel_cols)
        _, temp_df = add_elixir_away(temp_df, analysis_sel_cols)
        _, temp_df = code_features(temp_df, analysis_sel_cols)
        _, temp_df = code_away_features(temp_df, analysis_sel_cols)
        _, temp_df = code_home_features(temp_df, analysis_sel_cols)
        temp_df = temp_df.loc[:, analysis_sel_cols]

        ests = (LR_MODEL.predict_proba(temp_df.loc[:, analysis_sel_cols])[:, pred_index])
        new_ests[range(i, inds)] = ests

        del temp_df


问:
React JS: Getting [object object] When Concatenating Object Element With String
Im defining row content in React Table, when type the element variable alone it will print correctly, but when I try to concatenate it with other variable I get [Object Object] instead

the Object:

```<code>// Icons object
const typeIcons = {
  DINEIN:  <FlatwareIcon color="secondary" />  ,
  DELIVERY: <DeliveryDiningIcon color="secondary" />,
  TAKEAWAY: <RoomServiceIcon  color="success"/>
}
</code>```

When using object element with type 'DINEIN' for example, it works perfectly :

```<code>row2: typeIcons[item.order_type],
</code>```

and gives the required icon, But when concatenating with other variable, i.e.

```<code>row2: typeIcons[item.order_type] + item.order_type,
</code>```

the outcome will be:  [Object Object]DINEIN
Any explanation ?
Thanks in advance for your kind help.

答:
typeIcons[item.order_type] is object(React component) while item.order_type is a string. You cannot concatenate string with object.
I assume value under row2 must contain a React component, then you can try something like this:

```<code>row2: <>{typeIcons[item.order_type]} {item.order_type}</>,
</code>```

Body:
Im defining row content in React Table, when type the element variable alone it will print correctly, but when I try to concatenate it with other variable I get [Object Object] instead

the Object:

// Icons object
const typeIcons = {
  DINEIN:  <FlatwareIcon color="secondary" />  ,
  DELIVERY: <DeliveryDiningIcon color="secondary" />,
  TAKEAWAY: <RoomServiceIcon  color="success"/>
}

When using object element with type 'DINEIN' for example, it works perfectly :

row2: typeIcons[item.order_type],

and gives the required icon, But when concatenating with other variable, i.e.

row2: typeIcons[item.order_type] + item.order_type,

the outcome will be:  [Object Object]DINEIN
Any explanation ?
Thanks in advance for your kind help.

Body:
typeIcons[item.order_type] is object(React component) while item.order_type is a string. You cannot concatenate string with object.
I assume value under row2 must contain a React component, then you can try something like this:

row2: <>{typeIcons[item.order_type]} {item.order_type}</>,


问:
In ASP .NET Core 3.1, WebAPIs, what is the most logical place to do JSON request validation?
I'm writing a few .NET core 3.1 WebAPIs, and although model validation (through ValidationAttributes) takes care of most of my request validation, the request validation doesn't respect the DataTypeAttribute.

So for example, if I have a property that is a decimal on my end-point and someone provides a string, it fails at request validation and my controller end-point doesn't get hit.

I know there are a few alternatives, and I'm just wondering where it would make the most sense to put request validation logic in?

Examples: ValidationAttribute (doesn't fire for request validation), ActionFilters (OnActionExecuting, which does fire), JsonInputFormatters (also fires), etc...

========== EDIT: ==========

Thank you for the answers. I now am creating a subclass CustomActionFilterAttribute from ActionFilterAttribute. Then I decorate my controller and its actions with this filter attribute, but the OnActionExecuting isn't firing.

I have tried to do (in Startup.ConfigureServices()):

```<code>services.AddScoped\<CustomActionFilterAttribute>();

services.AddControllers(
                config =>
                {
                    config.Filters.Add\<CustomActionFilterAttribute>();
                });
</code>```

And then I decorate my controller like so:

```<code>[ValidateSubUsersModelFilter]
public class MyController : Controller {}
</code>```

None of the actions in MyController trigger the OnActionExecuting function of CustomActionFilterAttribute. Am I missing something here?

答: I would use fluent validation and set up automatic request validation during mvc   setup. That way every json request will be validated if body model will have validator implemented before it hits the controller.</p>

Body:
I'm writing a few .NET core 3.1 WebAPIs, and although model validation (through ValidationAttributes) takes care of most of my request validation, the request validation doesn't respect the DataTypeAttribute.

So for example, if I have a property that is a decimal on my end-point and someone provides a string, it fails at request validation and my controller end-point doesn't get hit.

I know there are a few alternatives, and I'm just wondering where it would make the most sense to put request validation logic in?

Examples: ValidationAttribute (doesn't fire for request validation), ActionFilters (OnActionExecuting, which does fire), JsonInputFormatters (also fires), etc...

========== EDIT: ==========

Thank you for the answers. I now am creating a subclass CustomActionFilterAttribute from ActionFilterAttribute. Then I decorate my controller and its actions with this filter attribute, but the OnActionExecuting isn't firing.

I have tried to do (in Startup.ConfigureServices()):

services.AddScoped\<CustomActionFilterAttribute>();

services.AddControllers(
                config =>
                {
                    config.Filters.Add\<CustomActionFilterAttribute>();
                });

And then I decorate my controller like so:

[ValidateSubUsersModelFilter]
public class MyController : Controller {}

None of the actions in MyController trigger the OnActionExecuting function of CustomActionFilterAttribute. Am I missing something here?


问:
How do I create a dummy variable within a range of values in R?
I need to create a dummy variable where if 20≤dummy≤40, it reads '1', and '0' otherwise. I think I am having a brainfart, but I cannot seem to do it.

I currently have:

```<code>dummy_x <- ifelse(x<=40, 1, 0)
</code>```

which works, however:

```<code>dummy_x <-ifelse(20<=x<=40, 1, 0)
</code>```

does not. If anyone can help, it would be greatly appreciated.

答: You have to split the second ifelse into two conditions like ifelse(x>=20 & x <=40, 1, 0)

Body:
I need to create a dummy variable where if 20≤dummy≤40, it reads '1', and '0' otherwise. I think I am having a brainfart, but I cannot seem to do it.

I currently have:

dummy_x <- ifelse(x<=40, 1, 0)

which works, however:

dummy_x <-ifelse(20<=x<=40, 1, 0)

does not. If anyone can help, it would be greatly appreciated.


问:
Postgresql select from table inside docker container bash
I can access my postgresql db inside docker container and the see the postgresql bash with this command :

```<code>docker exec -it  <container-name> psql -U <dataBaseUserName> <dataBaseName>
</code>```

But I need to see the data I inserted to the table with the api. Is there a way to perform select statement here?

答:
Whenever you access your container using the

```<code>docker exec -it <container-name> psql -U <username> <database>
</code>```

you can run any PSQL-Query you like. To list all the tables within your database you can use

```<code>\dt
</code>```

After you identified the table you want to query you can call any select, update or delete statement you like, e.g.:

```<code>SELECT * FROM <tablename>;
</code>```

See the official PostgresQL documentation for more details.

However, I highly recommend using tools such as DBeaver or Database-Tools integrated within your IDE to manage your databases. Connecting your databases running in a container is as easy as running the docker exec command. But the user interface and integrated shortcuts of those tools to e.g. generate SQL-Queries makes it much more easy to access and manage your databases.

Body:
I can access my postgresql db inside docker container and the see the postgresql bash with this command :

docker exec -it  <container-name> psql -U <dataBaseUserName> <dataBaseName>

But I need to see the data I inserted to the table with the api. Is there a way to perform select statement here?

Body:
Whenever you access your container using the

docker exec -it <container-name> psql -U <username> <database>

you can run any PSQL-Query you like. To list all the tables within your database you can use

\dt

After you identified the table you want to query you can call any select, update or delete statement you like, e.g.:

SELECT * FROM <tablename>;

See the official PostgresQL documentation for more details.

However, I highly recommend using tools such as DBeaver or Database-Tools integrated within your IDE to manage your databases. Connecting your databases running in a container is as easy as running the docker exec command. But the user interface and integrated shortcuts of those tools to e.g. generate SQL-Queries makes it much more easy to access and manage your databases.


问:
Why am I getting an error in C# when mixing explicit implementation and polymorphism?
I am getting this error:

type  Bar does not implement interface IFoo

From this code:

```<code>public interface IFoo
{
   void DoA();

   void DoB();
}

public class Foo:IFoo
{

    void IFoo.DoA()
    {

    }

    void IFoo.DoB()
    {

   }
}

public class Bar:Foo
{

     void IFoo.DoA()
      {
          base.doA();

      }

      void IFoo.DoB()
      {
          base.doB();

      }
  }
</code>```

I am using C# 2.0.

What am I doing wrong?

答:
See n8wrl's answer as to how you should be doing this.  See below for the reason why.

You can't explicity implement interface members (void IFoo.DoA()) when implicitly implementing the interface.  In other words, because Bar only implements IFoo by virtue of extending Foo, you cannot use explicit implementation.

This will work:

```<code>public class Bar : Foo
{
    public void DoA()
    {
        ...
    }

    public void DoB()
    {
        ...
    }
</code>```

Or this:

```<code>public class Bar : Foo, IFoo
{
    void IFoo.DoA()
    {
        ...
    }

    void IFoo.DoB()
    {
        ...
    }
</code>```

A bigger problem that you'll probably face is that since Foo is not abstract, it must implement DoA and DoB.  If you also implement these methods in bar, you will not be doing it polymorphically.  You'll be hiding the Foo implementations if the code has a handle to the Bar type.

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

ContentLicense: CC BY-SA 2.5

Body:
I am getting this error:

type  Bar does not implement interface IFoo

From this code:

public interface IFoo
{
   void DoA();

   void DoB();
}

public class Foo:IFoo
{

    void IFoo.DoA()
    {

    }

    void IFoo.DoB()
    {

   }
}

public class Bar:Foo
{

     void IFoo.DoA()
      {
          base.doA();

      }

      void IFoo.DoB()
      {
          base.doB();

      }
  }

I am using C# 2.0.

What am I doing wrong?

Body:
See n8wrl's answer as to how you should be doing this.  See below for the reason why.

You can't explicity implement interface members (void IFoo.DoA()) when implicitly implementing the interface.  In other words, because Bar only implements IFoo by virtue of extending Foo, you cannot use explicit implementation.

This will work:

public class Bar : Foo
{
    public void DoA()
    {
        ...
    }

    public void DoB()
    {
        ...
    }

Or this:

public class Bar : Foo, IFoo
{
    void IFoo.DoA()
    {
        ...
    }

    void IFoo.DoB()
    {
        ...
    }

A bigger problem that you'll probably face is that since Foo is not abstract, it must implement DoA and DoB.  If you also implement these methods in bar, you will not be doing it polymorphically.  You'll be hiding the Foo implementations if the code has a handle to the Bar type.

OwnerDisplayName: Michael Meadows

LastEditorDisplayName: Michael Meadows


问:
Unhashable type 'np.ndarray' in matplotlib 3d stem example from documentation
The matplotlib documentation contains the following code sample

```<code>import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi)
x = np.cos(theta - np.pi/2)
y = np.sin(theta - np.pi/2)
z = theta

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ax.stem(x, y, z)

plt.show()
</code>```

However, when I copy and paste this into a juypter notebook, I get an error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-b5d3d05087f2> in <module>
      8
      9 fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
---> 10 ax.stem(x, y, z)
     11
     12 plt.show()

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1445     def inner(ax, *args, data=None, **kwargs):
   1446         if data is None:
-> 1447             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448
   1449         bound = new_sig.bind(ax, *args, **kwargs)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in stem(self, linefmt, markerfmt, basefmt, bottom, label, use_line_collection, *args)
   2812             else:
   2813                 linestyle, linemarker, linecolor = \
-> 2814                     _process_plot_format(linefmt)
   2815         else:
   2816             linestyle, linemarker, linecolor = _process_plot_format(linefmt)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _process_plot_format(fmt)
    130     while i < len(fmt):
    131         c = fmt[i]
--> 132         if fmt[i:i+2] in mlines.lineStyles:  # First, the two-char styles.
    133             if linestyle is not None:
    134                 raise ValueError(

TypeError: unhashable type: 'numpy.ndarray'
</code>```

I suspect there's something wrong with my python kernel, rather than the matplotlib documentation, but I can't figure it out. Any help would be appreciated.

Numpy version: 1.19.5

Matplotlib version: 3.3.4

答:
After changing to the following module versions, the code sample from matplotlib's documentation works as intended.

Numpy version: 1.21.5

Matplotlib version: 3.5.0

Body:
The matplotlib documentation contains the following code sample

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi)
x = np.cos(theta - np.pi/2)
y = np.sin(theta - np.pi/2)
z = theta

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ax.stem(x, y, z)

plt.show()

However, when I copy and paste this into a juypter notebook, I get an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-b5d3d05087f2> in <module>
      8
      9 fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
---> 10 ax.stem(x, y, z)
     11
     12 plt.show()

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1445     def inner(ax, *args, data=None, **kwargs):
   1446         if data is None:
-> 1447             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448
   1449         bound = new_sig.bind(ax, *args, **kwargs)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in stem(self, linefmt, markerfmt, basefmt, bottom, label, use_line_collection, *args)
   2812             else:
   2813                 linestyle, linemarker, linecolor = \
-> 2814                     _process_plot_format(linefmt)
   2815         else:
   2816             linestyle, linemarker, linecolor = _process_plot_format(linefmt)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _process_plot_format(fmt)
    130     while i < len(fmt):
    131         c = fmt[i]
--> 132         if fmt[i:i+2] in mlines.lineStyles:  # First, the two-char styles.
    133             if linestyle is not None:
    134                 raise ValueError(

TypeError: unhashable type: 'numpy.ndarray'

I suspect there's something wrong with my python kernel, rather than the matplotlib documentation, but I can't figure it out. Any help would be appreciated.

Numpy version: 1.19.5

Matplotlib version: 3.3.4


问:
ConnectionError: HTTPSConnectionPool(host = 'api.github.com', port=443): Max retries exceeded using GeckoDriverManager and WebdriverManager for Python
I made a web-scraping script using Selenium, Pandas, bf4 and GeckoDriver

```<code>import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from webdriver_manager.firefox import GeckoDriverManager

url = "https://example/url/target"

option = Option()
option.headlers = True
driver = webdriver.Firefox(executable_path=r'C:\Users\Public\geckodriver.exe')
driver.get(url)
</code>```

With this code the script works 100% but as I need it to be a portable application (transfer to other computers) I don't want the user to have to manually specify the Geckodriver path, let alone have to download it.

Geckodriver has an auto-installer but in all the ways that I try to make i get an error, searching here in the forum I found this alternative (and the error)

```<code>url = "https://example/url/target"

driver = webdriver.Firefox(executable_path=rGeckoDriverManager().install())

driver.get("https:www.python.org")
driver.get(url)
</code>```

Result:

```<code>ConnectionError: HTTPSConnectionPool(host = 'api.github.com', port=443): Max retries exceeded with url: /repos/mozilla/geckodriver/releases/latest (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000025186487F98>: Failed to stabilize a new connection: [Errno 11001 getaddriinfo failed',))
</code>```

I also tried following the: https://pypi.org/project/geckodriver-autoinstaller/#description :

```<code>import geckodriver_autoinstaller
geckodriver_autoinstaller.install()

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
</code>```

Result:

```<code><urlopen error [Errno 11001] getaddrinfo failed>
</code>```

All these options I tested also with socket.getddrinfo('localhost', 8080) and also using Git hub personal Token in os.environ['GH_TOKEN'] = 'exampletoken'

Does anyone know why I'm not able to automate the driver installation?

W10 64 bit,
Firefox Latest Version,
Libs and anaconda latest version,
Python = 3.6,
Internet with VPN (from work)

答:
Possibly a typo, however instead of rGeckoDriverManager() you should have used GeckoDriverManager() within the line:

```<code>driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
</code>```

Effectively your code block will be:

```<code>from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get("https://www.google.com")
</code>```

Console Output:

```<code>====== WebDriver manager ======
Current firefox version is 97.0
Get LATEST geckodriver version for 97.0 firefox
Driver [C:\Users\debanjan.bhattacharj\.wdm\drivers\geckodriver\win64\v0.30.0\geckodriver.exe] found in cache
C:\Users\debanjan.bhattacharj\Desktop\Python Programs\Selenium3-GeckoDriverManager.py:8: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

</code>```

PS: Using selenium4 executable_path has been deprecated and you have pass in a Service object.

Body:
I made a web-scraping script using Selenium, Pandas, bf4 and GeckoDriver

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from webdriver_manager.firefox import GeckoDriverManager

url = "https://example/url/target"

option = Option()
option.headlers = True
driver = webdriver.Firefox(executable_path=r'C:\Users\Public\geckodriver.exe')
driver.get(url)

With this code the script works 100% but as I need it to be a portable application (transfer to other computers) I don't want the user to have to manually specify the Geckodriver path, let alone have to download it.

Geckodriver has an auto-installer but in all the ways that I try to make i get an error, searching here in the forum I found this alternative (and the error)

url = "https://example/url/target"

driver = webdriver.Firefox(executable_path=rGeckoDriverManager().install())

driver.get("https:www.python.org")
driver.get(url)

Result:

ConnectionError: HTTPSConnectionPool(host = 'api.github.com', port=443): Max retries exceeded with url: /repos/mozilla/geckodriver/releases/latest (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000025186487F98>: Failed to stabilize a new connection: [Errno 11001 getaddriinfo failed',))

I also tried following the: https://pypi.org/project/geckodriver-autoinstaller/#description :

import geckodriver_autoinstaller
geckodriver_autoinstaller.install()

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title

Result:

<urlopen error [Errno 11001] getaddrinfo failed>

All these options I tested also with socket.getddrinfo('localhost', 8080) and also using Git hub personal Token in os.environ['GH_TOKEN'] = 'exampletoken'

Does anyone know why I'm not able to automate the driver installation?

W10 64 bit,
Firefox Latest Version,
Libs and anaconda latest version,
Python = 3.6,
Internet with VPN (from work)

Body:
Possibly a typo, however instead of rGeckoDriverManager() you should have used GeckoDriverManager() within the line:

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

Effectively your code block will be:

from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get("https://www.google.com")

Console Output:

====== WebDriver manager ======
Current firefox version is 97.0
Get LATEST geckodriver version for 97.0 firefox
Driver [C:\Users\debanjan.bhattacharj\.wdm\drivers\geckodriver\win64\v0.30.0\geckodriver.exe] found in cache
C:\Users\debanjan.bhattacharj\Desktop\Python Programs\Selenium3-GeckoDriverManager.py:8: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

PS: Using selenium4 executable_path has been deprecated and you have pass in a Service object.


问:
Pass parent attribute in metaclass
The metaclass is defined as below:

```<code>class MyMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        # uses attribute a,b,c,d
        a = namespace["a"]
        b = namespace["b"]
        c = namespace["c"]
        d = namespace["d"]
        ...
        return super().__new__(metacls, name, bases, namespace, **kwargs)
</code>```

This metaclass uses attributes a, b, c, d.
Now classes can be created with this metaclass as:

```<code>class A(metaclass=MyMeta):
    a = "etc/dev"
    b = 2
    c = "c"
    d = "d"

class B(metaclass=MyMeta):
    a = "etc/dev/null"
    b = 2
    c = "c"
    d = "d"
</code>```

The attribute a is variable for each class.
I want to extract the constant attributes in a base class to avoid duplication:

```<code>class BaseClass:
    b = 2
    c = "c"
    d = "d"
</code>```

and create classes using the metaclass as:

```<code>class A(BaseClass, metaclass=MyMeta):
    a = "/etc/dev"

class B(BaseClass, metaclass=MyMeta):
    a = "/etc/dev/null"
</code>```

The metaclass complains that it can not find attribute b from parent class.

```<code>test_mode = namespace["b"]
KeyError: 'b'
</code>```

Is there a way to pass attributes from parent to a child metaclass ?

Constraint: Can not update the MyMeta metaclass as it's been borrowed/imported it from an existing library.

答:
You can do it by making the metaclass __new__() method also check the namespaces of all the base classes of the class being defined. Here's one way of doing it. Note that it filters out attributes in the namespaces that have dunder identifiers.

Since you can't change the meta class you "borrowed" a custom one is derived from it. This revised version of my earlier answer also uses the collection.ChainMap class to make all the namespaces be considered without actually combining them all.

```<code>from collections import ChainMap
import re

class BorrowedMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        # uses attribute a,b,c,d
        a = namespace["a"]
        b = namespace["b"]
        c = namespace["c"]
        d = namespace["d"]
        ...
        return super().__new__(metacls, name, bases, namespace, **kwargs)

def is_dunder(name):
    """Determine if name is a Python dunder identifier."""
    return re.match(r'^__[^\d\W]\w*\Z__$', name, re.UNICODE)

class MyMeta(BorrowedMeta):
    def __new__(metacls, name, bases, namespace, **kwargs):
        chainmap = ChainMap(*[namespace] +
                             [{k: v for (k, v) in vars(base).items() if not(is_dunder(k))}
                                                    for base in bases])

        return super().__new__(metacls, name, bases, {**chainmap}, **kwargs)

class BaseClass:
    b = 2
    c = "c"
    d = "d"

class A(BaseClass, metaclass=MyMeta):
    a = "/etc/dev"

class B(BaseClass, metaclass=MyMeta):
    a = "/etc/dev/null"

from pprint import pprint
pprint(vars(A))
print()
pprint(vars(B))
</code>```

Output:

```<code>mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a': '/etc/dev',
              'b': 2,
              'c': 'c',
              'd': 'd'})

mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a': '/etc/dev/null',
              'b': 2,
              'c': 'c',
              'd': 'd'})
</code>```

Title: Pass parent attribute in metaclass

Body:
The metaclass is defined as below:

class MyMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        # uses attribute a,b,c,d
        a = namespace["a"]
        b = namespace["b"]
        c = namespace["c"]
        d = namespace["d"]
        ...
        return super().__new__(metacls, name, bases, namespace, **kwargs)

This metaclass uses attributes a, b, c, d.
Now classes can be created with this metaclass as:

class A(metaclass=MyMeta):
    a = "etc/dev"
    b = 2
    c = "c"
    d = "d"

class B(metaclass=MyMeta):
    a = "etc/dev/null"
    b = 2
    c = "c"
    d = "d"

The attribute a is variable for each class.
I want to extract the constant attributes in a base class to avoid duplication:

class BaseClass:
    b = 2
    c = "c"
    d = "d"

and create classes using the metaclass as:

class A(BaseClass, metaclass=MyMeta):
    a = "/etc/dev"

class B(BaseClass, metaclass=MyMeta):
    a = "/etc/dev/null"

The metaclass complains that it can not find attribute b from parent class.

test_mode = namespace["b"]
KeyError: 'b'

Is there a way to pass attributes from parent to a child metaclass ?

Constraint: Can not update the MyMeta metaclass as it's been borrowed/imported it from an existing library.

Body:
You can do it by making the metaclass __new__() method also check the namespaces of all the base classes of the class being defined. Here's one way of doing it. Note that it filters out attributes in the namespaces that have dunder identifiers.

Since you can't change the meta class you "borrowed" a custom one is derived from it. This revised version of my earlier answer also uses the collection.ChainMap class to make all the namespaces be considered without actually combining them all.

from collections import ChainMap
import re

class BorrowedMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        # uses attribute a,b,c,d
        a = namespace["a"]
        b = namespace["b"]
        c = namespace["c"]
        d = namespace["d"]
        ...
        return super().__new__(metacls, name, bases, namespace, **kwargs)

def is_dunder(name):
    """Determine if name is a Python dunder identifier."""
    return re.match(r'^__[^\d\W]\w*\Z__$', name, re.UNICODE)

class MyMeta(BorrowedMeta):
    def __new__(metacls, name, bases, namespace, **kwargs):
        chainmap = ChainMap(*[namespace] +
                             [{k: v for (k, v) in vars(base).items() if not(is_dunder(k))}
                                                    for base in bases])

        return super().__new__(metacls, name, bases, {**chainmap}, **kwargs)

class BaseClass:
    b = 2
    c = "c"
    d = "d"

class A(BaseClass, metaclass=MyMeta):
    a = "/etc/dev"

class B(BaseClass, metaclass=MyMeta):
    a = "/etc/dev/null"

from pprint import pprint
pprint(vars(A))
print()
pprint(vars(B))

Output:

mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a': '/etc/dev',
              'b': 2,
              'c': 'c',
              'd': 'd'})

mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a': '/etc/dev/null',
              'b': 2,
              'c': 'c',
              'd': 'd'})


问:
How to substitute different number of digits behind special character with regex
I have the following kind of string:"§ 9,12,14,15 und 16" or "§ 9,12 und 16".

I want to change the string to:"§ 9, § 12, § 14, § 15 und §16" or "§ 9, § 12 und § 16", respectively.

The number of digits varies and I want a code snipped that is applicable for all length:

```<code>text = "§§ 9,12,14,15 und 16"
text = re.sub(r'§* (\d+),(\d+),(\d+),(\d+) und (\d+)', r'§ \1, § \2, § \3, § \4 und § \5', text)
</code>```

I only manage to match the string if I know the number of digits.

答:
You can do that by using re.sub with a regular expression and a lambda for replacements.

```<code>str = "aaa § 9,12,14,15 und 16 bbb"
rgx = r'(?:,|(?<!§) )(?=\d)'
</code>```

```<code>re.sub(rgx, lambda m: ', § ' if m.group() == ',' else ' §', str)
  #=> "aaa § 9, § 12, § 14, § 15 und §16 bbb"
</code>```

Regex demo¯\(ツ)/¯Python demo

The regular expression can be broken down as follows.

```<code>(?:       # begin a non-capture group
  ,       # match a comma
  |       # or
  (?<!§)  # next character cannot be preceded by '§'
  [ ]     # match a space
)         # end non-capture group
(?=\d)    # next character must be a digit
</code>```

(?<!§) is a negative lookbehind; (?=\d) is a positive lookahead. I've placed the space in a character class ([ ]) merely to make it visible.

Body:
I have the following kind of string:"§ 9,12,14,15 und 16" or "§ 9,12 und 16".

I want to change the string to:"§ 9, § 12, § 14, § 15 und §16" or "§ 9, § 12 und § 16", respectively.

The number of digits varies and I want a code snipped that is applicable for all length:

text = "§§ 9,12,14,15 und 16"
text = re.sub(r'§* (\d+),(\d+),(\d+),(\d+) und (\d+)', r'§ \1, § \2, § \3, § \4 und § \5', text)

I only manage to match the string if I know the number of digits.

Body:
You can do that by using re.sub with a regular expression and a lambda for replacements.

str = "aaa § 9,12,14,15 und 16 bbb"
rgx = r'(?:,|(?<!§) )(?=\d)'

re.sub(rgx, lambda m: ', § ' if m.group() == ',' else ' §', str)
  #=> "aaa § 9, § 12, § 14, § 15 und §16 bbb"

Regex demo¯\(ツ)/¯Python demo

The regular expression can be broken down as follows.

(?:       # begin a non-capture group
  ,       # match a comma
  |       # or
  (?<!§)  # next character cannot be preceded by '§'
  [ ]     # match a space
)         # end non-capture group
(?=\d)    # next character must be a digit

(?<!§) is a negative lookbehind; (?=\d) is a positive lookahead. I've placed the space in a character class ([ ]) merely to make it visible.