问:
Dockerfile execution permission denied
I have this dockerfile

```<code>FROM alpine:3.8
ENV LANG C.UTF-8
RUN set -x && \
    apk add --no-cache \
              openrc \
              bash \
              libreswan \
              xl2tpd \
              ppp \
    && mkdir -p /var/run/pluto \
    && mkdir -p /var/run/xl2tpd \
    && touch /var/run/xl2tpd/l2tp-control
COPY ipsec.conf /etc/ipsec.conf
COPY ipsec.secrets /etc/ipsec.secrets
COPY xl2tpd.conf /etc/xl2tpd/xl2tpd.conf
COPY options.l2tpd.client /etc/ppp/options.l2tpd.client
COPY startup.sh /
RUN ["chmod", "+x", "/startup.sh"]

CMD ["./startup.sh"]
</code>```

When I run that in local everything works ok. but I'm trying to execute the image generated in a gcp vm (ubuntu) and I get the following error

```<code>/bin/sh: can't open './startup.sh': Permission denied
</code>```

Can someone help me with this error?

note: I also tried to modify permissions with:

```<code>RUN ["chmod", "777", "/startup.sh"]
RUN chmod +x /startup.sh
RUN chmod 777 /startup.sh
</code>```

And execute the script with:

```<code>ENTRYPOINT ["./startup.sh"]
RUN ["./startup.sh"]
RUN ./startup.sh
</code>```

答:
you are missing here to add user to change permission
More Info </p>

```<code>RUN useradd -ms /bin/bash  myuser
</code>```

Title: Dockerfile execution permission denied

Body:
I have this dockerfile

FROM alpine:3.8
ENV LANG C.UTF-8
RUN set -x && \
    apk add --no-cache \
              openrc \
              bash \
              libreswan \
              xl2tpd \
              ppp \
    && mkdir -p /var/run/pluto \
    && mkdir -p /var/run/xl2tpd \
    && touch /var/run/xl2tpd/l2tp-control
COPY ipsec.conf /etc/ipsec.conf
COPY ipsec.secrets /etc/ipsec.secrets
COPY xl2tpd.conf /etc/xl2tpd/xl2tpd.conf
COPY options.l2tpd.client /etc/ppp/options.l2tpd.client
COPY startup.sh /
RUN ["chmod", "+x", "/startup.sh"]

CMD ["./startup.sh"]

When I run that in local everything works ok. but I'm trying to execute the image generated in a gcp vm (ubuntu) and I get the following error

/bin/sh: can't open './startup.sh': Permission denied

Can someone help me with this error?

note: I also tried to modify permissions with:

RUN ["chmod", "777", "/startup.sh"]
RUN chmod +x /startup.sh
RUN chmod 777 /startup.sh

And execute the script with:

ENTRYPOINT ["./startup.sh"]
RUN ["./startup.sh"]
RUN ./startup.sh

Body:
you are missing here to add user to change permission
More Info

RUN useradd -ms /bin/bash  myuser


来源: stackexchange

问:
How to get record details of a DNS record via aws cli?
I want to get the details of a DNS record in AWS route53.

What is the aws cli command to get DNS record details given that we have the domain name or the record ID?

答:
You're looking for the list-resource-record-set command.

You can filter to a specific record using --query, as seen in example below.

```<code>aws route53 list-resource-record-sets --hosted-zone-id Z2LD58HEXAMPLE --query "ResourceRecordSets[?Name == 'example.domain.']"
</code>```

Alternatively if you just need resolution information take a look at running DIG.

ContentLicense: CC BY-SA 4.0

Body:
You're looking for the list-resource-record-set command.

You can filter to a specific record using --query, as seen in example below.

aws route53 list-resource-record-sets --hosted-zone-id Z2LD58HEXAMPLE --query "ResourceRecordSets[?Name == 'example.domain.']"

Alternatively if you just need resolution information take a look at running DIG.


问:
Phaser update sprite texture
I have a problem updating a sprite.

I created a function to change clothes. This should work like:

```<code>// Something like this.
pet = pet_with_hat
</code>```

There is code at https://github.com/futer/pandachii in in js/main.js, line 387.

When I write this:

```<code>this.pet = this.game.add.sprite(90,90, 'pet_black_hat')
</code>```

There is an error:

```
 Uncaught TypeError: Cannot read property 'health' of undefined
 GameState.update @ main.js:194
 Phaser.StateManager.update @ phaser.js:16628
 Phaser.Game.update @ phaser.js:23092
 Phaser.RequestAnimationFrame.updateRAF @ phaser.js:41421
 _onLoop @ phaser.js:41407
```

How do I change the sprite image for this pet to another?

I will be grateful.

答:
If you've added the new image using scene.add.image(...) then you can use,
carSprite.setTexture('tank')

If you want to select a different sprite in the same texture atlas that you loaded with scene.load.atlas(...), then you can call carSprite.setFrame('tank')

If you want to select a sprite in a completely different texture atlas, then you can call, carSprite.setTexture('newTextureAtlasKey', 'tank')

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: Phaser update sprite texture

Body:
I have a problem updating a sprite.

I created a function to change clothes. This should work like:

// Something like this.
pet = pet_with_hat

There is code at https://github.com/futer/pandachii in in js/main.js, line 387.

When I write this:

this.pet = this.game.add.sprite(90,90, 'pet_black_hat')

There is an error:

 Uncaught TypeError: Cannot read property 'health' of undefined
 GameState.update @ main.js:194
 Phaser.StateManager.update @ phaser.js:16628
 Phaser.Game.update @ phaser.js:23092
 Phaser.RequestAnimationFrame.updateRAF @ phaser.js:41421
 _onLoop @ phaser.js:41407

How do I change the sprite image for this pet to another?

I will be grateful.


问:
Change stroke Color to Clear Color CGContext
I want user to draw on Custom UIView with clearcolor as stroke color. The code is working fine for other colors but not clear color.

```<code> override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }
    context.addRect(rect)
    draw(inContext: context)
}

func draw(inContext context: CGContext) {

    context.setLineWidth(5)
    context.setStrokeColor(UIColor.clear.cgColor)
    context.setLineCap(.round)

    for line in lineArray {
        guard let firstPoint = line.first else { continue }
        context.beginPath()
        context.move(to: firstPoint)
        for point in line.dropFirst() {
            context.addLine(to: point)
        }
        context.strokePath()
    }
}
</code>```

答:
So, it sounds like you've a situation like this. You have an image being displayed in an image view:

And you want the image to be hidden until the user draws on top of it, at which point the user's drawing should reveal that part of the image, like this:

If so, what you want is not to draw with clear color; you want a mask. What's actually happening in that second screen shot is that we track the user's drawing and draw black into an otherwise clear mask on the image view.

Body:
I want user to draw on Custom UIView with clearcolor as stroke color. The code is working fine for other colors but not clear color.

 override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }
    context.addRect(rect)
    draw(inContext: context)
}

func draw(inContext context: CGContext) {

    context.setLineWidth(5)
    context.setStrokeColor(UIColor.clear.cgColor)
    context.setLineCap(.round)

    for line in lineArray {
        guard let firstPoint = line.first else { continue }
        context.beginPath()
        context.move(to: firstPoint)
        for point in line.dropFirst() {
            context.addLine(to: point)
        }
        context.strokePath()
    }
}


问:
In Cypress to test getting total number of elements from listbox and then according to the data run in loop and as per each data perform an if
In Cyress Test writing an test of react application when I click on a Listbox in the drop down it get list of data.

eg : 123a, 1233, 111c etc suppose have count 50
then select each 1 by 1 however need to compare each that if its certain account perform certain checks

in details:
have searched and clicked the listbox but the issue i am facing how can i find the total number of elements in that listbox and need to traverse each item/value 1 by 1 and when select verify certain asserts.

so 3 challenges where i am stuck
1) How to get total number of elements have tried initial count=cy.get('@alias').length seems not working.

2) after we get how can I iterate through the loop 1 at a time as after selecting 1 item as have to certain assertions.

Thanks
Varun Awasthi

答:
I am new to this, but to get the count of elements returned I would use something like this:

```<code>cy.get('.item').its('length')
</code>```

Then, if you want to work with specific elements from that array:

```<code>.then(size => {
  for(i= 0; i < size: i++) {
    cy.get('.item').eq(size).should('have.value', 'list item')
  }
})
</code>```

Body:
I am new to this, but to get the count of elements returned I would use something like this:

cy.get('.item').its('length')

Then, if you want to work with specific elements from that array:

.then(size => {
  for(i= 0; i < size: i++) {
    cy.get('.item').eq(size).should('have.value', 'list item')
  }
})


问:
Append an the entire array as one element to another array that has arrays of different sizes inside with Python
Let's say I have array 'a' like this

```<code>>>> a = np.array([[1,2], [3,4,5]])

>>> a.shape

(2,)
>>>
</code>```

Now I'd like to append the entire of an array like [6,7,8,9] to it as just one element and not four:

```<code>>>> b = np.append(a,[6,7,8,9])

>>> b.shape

(6,)
>>>
</code>```

But this is not what I want. What I do want is to have b having 3 elements and not 6 by stacking every element of the new array to a. I found a workaround  this as below but what is the proper way to get this done?

```<code>>>> b = np.append(a,[0])

>>> b[2] = [6,7,8,9]

>>> b.shape

(3,)
>>>
</code>```

答:
Define 2 arrays:

```<code>In [19]: a = np.array([[1,2], [3,4,5]])
In [20]: b = np.array([6,7,8,9])
In [21]: a
Out[21]: array([list([1, 2]), list([3, 4, 5])], dtype=object)
</code>```

Since a is an array of lists, lets backtrack and define b as a list as well:

```<code>In [22]: b = [6,7,8,9]
</code>```

An object array has few, if any advantages compared to a list.  On big disadvantage is that it doesn't have an append method:

```<code>In [23]: a.tolist()
Out[23]: [[1, 2], [3, 4, 5]]
In [24]: alist = a.tolist()
In [25]: alist.append(b)
In [26]: np.array(alist)
Out[26]: array([list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9])], dtype=object)
</code>```

While we can work out a way of making new array with 3 elements, I doubt if it will be any better than this list append.

When we try to concatenate, the b list is first turned into an array:

```<code>In [30]: np.concatenate([a,b])
Out[30]: array([list([1, 2]), list([3, 4, 5]), 6, 7, 8, 9], dtype=object)
In [31]: np.array(b)
Out[31]: array([6, 7, 8, 9])
</code>```

So this joins the (2,) a with the (4,) b producing a (6,).

To do the concatenate that you want, we have to first wrap b in an similar object dtype array:

```<code>In [32]: c = np.array([None])
In [33]: c
Out[33]: array([None], dtype=object)
In [34]: c[0]=b
In [35]: c
Out[35]: array([list([6, 7, 8, 9])], dtype=object)
</code>```

c is a (1,) object dtype, which pairs with the (2,) a as desired:

```<code>In [36]: np.concatenate((a,c))
Out[36]: array([list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9])], dtype=object)
</code>```

This is effectively the same as your appending [0]:

```<code>In [40]: d = np.concatenate([a, [None]])
In [41]: d
Out[41]: array([list([1, 2]), list([3, 4, 5]), None], dtype=object)
In [42]: d[-1] = b
In [43]: d
Out[43]: array([list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9])], dtype=object)
</code>```

One way or other you have to convert b into a single element array, not the 4 element Out[31].  concatenate joins arrays.

Body:
Let's say I have array 'a' like this

>>> a = np.array([[1,2], [3,4,5]])

>>> a.shape

(2,)
>>>

Now I'd like to append the entire of an array like [6,7,8,9] to it as just one element and not four:

>>> b = np.append(a,[6,7,8,9])

>>> b.shape

(6,)
>>>

But this is not what I want. What I do want is to have b having 3 elements and not 6 by stacking every element of the new array to a. I found a workaround  this as below but what is the proper way to get this done?

>>> b = np.append(a,[0])

>>> b[2] = [6,7,8,9]

>>> b.shape

(3,)
>>>

Body:
Define 2 arrays:

In [19]: a = np.array([[1,2], [3,4,5]])
In [20]: b = np.array([6,7,8,9])
In [21]: a
Out[21]: array([list([1, 2]), list([3, 4, 5])], dtype=object)

Since a is an array of lists, lets backtrack and define b as a list as well:

In [22]: b = [6,7,8,9]

An object array has few, if any advantages compared to a list.  On big disadvantage is that it doesn't have an append method:

In [23]: a.tolist()
Out[23]: [[1, 2], [3, 4, 5]]
In [24]: alist = a.tolist()
In [25]: alist.append(b)
In [26]: np.array(alist)
Out[26]: array([list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9])], dtype=object)

While we can work out a way of making new array with 3 elements, I doubt if it will be any better than this list append.

When we try to concatenate, the b list is first turned into an array:

In [30]: np.concatenate([a,b])
Out[30]: array([list([1, 2]), list([3, 4, 5]), 6, 7, 8, 9], dtype=object)
In [31]: np.array(b)
Out[31]: array([6, 7, 8, 9])

So this joins the (2,) a with the (4,) b producing a (6,).

To do the concatenate that you want, we have to first wrap b in an similar object dtype array:

In [32]: c = np.array([None])
In [33]: c
Out[33]: array([None], dtype=object)
In [34]: c[0]=b
In [35]: c
Out[35]: array([list([6, 7, 8, 9])], dtype=object)

c is a (1,) object dtype, which pairs with the (2,) a as desired:

In [36]: np.concatenate((a,c))
Out[36]: array([list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9])], dtype=object)

This is effectively the same as your appending [0]:

In [40]: d = np.concatenate([a, [None]])
In [41]: d
Out[41]: array([list([1, 2]), list([3, 4, 5]), None], dtype=object)
In [42]: d[-1] = b
In [43]: d
Out[43]: array([list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9])], dtype=object)

One way or other you have to convert b into a single element array, not the 4 element Out[31].  concatenate joins arrays.


问:
Conditionally Ignore Authorize .NET Core 3.1
I am migrating a web API from .net Framework to .net Core. The old version was able to ignore the Authorize Attribute on the controller if the app was running on a private server. Here is the code for that. I know .net core 3.1 does not offer Custom AuthorizeAttributes. That is not my question.

```<code>// A custom AuthroizeAttribute
public class ConditionalAuthorizeAttribute : AuthorizeAttribute
{

    protected override bool IsAuthorized(HttpActionContext httpContext)
    {
        if (environment_private())
            return true;
        else
            return base.IsAuthorized(httpContext);
    }

    private bool environment_private()
    {
        // code that will tell you if you are in your dev environment or not
        return Properties.Settings.Default.PrivateServer;
    }
}

// How it was called from the controller
[ConditionalAuthorize(Roles = "MyRole")]
[Route(...)]
// More code for controller
</code>```

I just need a simple way to authorized all requests when running the project on our private server (which is determined by a variable in appSettings.json). I have tried policies, but I face the following difficulties:

1) I couldn't pass the variable in the configuration from the controller to a parameterized authorize attribute.

2) I couldn't inject the configuration into a parameterized authorize attribute.

This effectively eliminated my ability to follow this guide in any way: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-2.2

This leads to my question: How can I use a value from appSettings.json to override whether the request checks a role or not?

答:
After a lot of research, I found a way to do it using TypeFilterAttribute. Essentially, it's the same way of doing it (using a custom attribute to filter all requests and check the condition within the custom attribute) except I used .net Core-supported methods.

In case you are trying to solve this same issue, here are the exact steps to my solution.

Add two files, "YourAttributeNameAttribute.cs" and "YourFilterNameFilter.cs".

In the "YourAttributeNameAttribute.cs" file, the code is as follows:

```<code>public class YourAttributeNameAttribute : TypeFilterAttribute
{
    public YourAttributeNameAttribute(string role) : base(typeof(YourFilterNameFilter))
    {
        Arguments = new object[] { role };
    }
}
</code>```

The code in "YourFilterNameFilter.cs":

```<code>public class YourFilterNameFilter : IAuthorizationFilter
{
    private readonly string Role;
    public YourFilterNameFilter(string role)
    {
        Role = role;
    }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();

        // If private server, ignore roles
        if (private_server_logic_here)
            return;

        var user = context.HttpContext.User;

        // Check role if on public server
        if (!user.IsInRole(Role))
        {
            context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Unauthorized);
            return;
        }
    }
}
</code>```

The code for the controller:

```<code>[YourAttributeName("role_name")]
[Route("api/my_route")]
[HttpGet]
</code>```

Body:
I am migrating a web API from .net Framework to .net Core. The old version was able to ignore the Authorize Attribute on the controller if the app was running on a private server. Here is the code for that. I know .net core 3.1 does not offer Custom AuthorizeAttributes. That is not my question.

// A custom AuthroizeAttribute
public class ConditionalAuthorizeAttribute : AuthorizeAttribute
{

    protected override bool IsAuthorized(HttpActionContext httpContext)
    {
        if (environment_private())
            return true;
        else
            return base.IsAuthorized(httpContext);
    }

    private bool environment_private()
    {
        // code that will tell you if you are in your dev environment or not
        return Properties.Settings.Default.PrivateServer;
    }
}

// How it was called from the controller
[ConditionalAuthorize(Roles = "MyRole")]
[Route(...)]
// More code for controller

I just need a simple way to authorized all requests when running the project on our private server (which is determined by a variable in appSettings.json). I have tried policies, but I face the following difficulties:

1) I couldn't pass the variable in the configuration from the controller to a parameterized authorize attribute.

2) I couldn't inject the configuration into a parameterized authorize attribute.

This effectively eliminated my ability to follow this guide in any way: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-2.2

This leads to my question: How can I use a value from appSettings.json to override whether the request checks a role or not?

Body:
After a lot of research, I found a way to do it using TypeFilterAttribute. Essentially, it's the same way of doing it (using a custom attribute to filter all requests and check the condition within the custom attribute) except I used .net Core-supported methods.

In case you are trying to solve this same issue, here are the exact steps to my solution.

Add two files, "YourAttributeNameAttribute.cs" and "YourFilterNameFilter.cs".

In the "YourAttributeNameAttribute.cs" file, the code is as follows:

public class YourAttributeNameAttribute : TypeFilterAttribute
{
    public YourAttributeNameAttribute(string role) : base(typeof(YourFilterNameFilter))
    {
        Arguments = new object[] { role };
    }
}

The code in "YourFilterNameFilter.cs":

public class YourFilterNameFilter : IAuthorizationFilter
{
    private readonly string Role;
    public YourFilterNameFilter(string role)
    {
        Role = role;
    }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();

        // If private server, ignore roles
        if (private_server_logic_here)
            return;

        var user = context.HttpContext.User;

        // Check role if on public server
        if (!user.IsInRole(Role))
        {
            context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Unauthorized);
            return;
        }
    }
}

The code for the controller:

[YourAttributeName("role_name")]
[Route("api/my_route")]
[HttpGet]


问:
Using multiproccessing for displaying realtime output from Subproccess while writing the output to file
I have a code that takes the host address, asks for filename (to save on user's desktop) and asks if user's want to clear the file or append to it.

when it runs, it prints the output to screen first and then writes the file.
how can I use multiproccessing to make them work simultaneously?
 i've tried with target= and they run but still one after another and not together.

......................................................................................................................................

(Don't mind the host, filename, clear input validation, they're here for testing multiproccessing)

Code: (I used the first condition to test the multiproccess)

```<code>import multiprocessing as mp
import subprocess as sub
import sys
import os

class pingURL():

    def __init__(self):
        self.t2d = mp.Queue()
        self.tf = mp.Queue()
        host = input("Enter Host: ")
        filename = input("Enter filename: ")
        clear = input("Clear File? [Y/n] ")

        print(clear, filename)  # For Debugging Input Validation

        if clear.lower() == 'y' and filename == '':
            self.pHclrFileYesFnNo(host)
            # self.clrFileYesFnNoWritefile(host)
            # self.clrFileYesFnNoPrintoutput(host)
        elif clear.lower() == 'n' and filename == '':
            self.clrFileNoFnNoPrintoutput(host)
            self.clrFileNoFnNoWritefile(host)
        elif clear.lower() == 'y' and filename != '':
            self.clrFileYesFnYesPrintoutput(host)
            self.clrFileYesFnYesWritefile(host, filename)
        elif clear.lower() == 'n' and filename != '':
            self.clrFileNoFnYesPrintoutput(host)
            self.clrFileNoFnYesWritefile(host, filename)

    def pHclrFileYesFnNo(self, host):

        procs = []

        proc = mp.Process(name="Clear + No Filename + Print Output", target=self.clrFileYesFnNoPrintoutput(host))
        proc2 = mp.Process(name="Clear + No Filename + Write to file", target=self.clrFileYesFnNoWritefile(host))

        procs.append(proc)
        procs.append(proc2)

        for proc in procs:
            proc.start()
            proc.join()

    def clrFileYesFnNoPrintoutput(self, host):

        print(f'Number of procceccess: {mp.cpu_count()}')
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileYesFnNoWritefile(self, host):

        print(f'Number of procceccess: {mp.cpu_count()}')
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')

        file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
        with open(file, 'a') as output:
            output.truncate(0)
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

    def clrFileNoFnNoPrintoutput(self, host):

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileNoFnNoWritefile(self, host):

        file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
        with open(file, 'a') as output:
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

    def clrFileYesFnYesPrintoutput(self, host):

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileYesFnYesWritefile(self, host, filename):

        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'
        with open(file, 'a') as output:
            output.truncate(0)
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

    def clrFileNoFnYesPrintoutput(self, host):

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileNoFnYesWritefile(self, host, filename):

        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'
        with open(file, 'a') as output:
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

if __name__ == "__main__":

    pingURL()
</code>```

I get the same Proccess name and ID when running the script:

答:
well the solution was defining a handler for every condition.
that worked for me.</p>

```<code>def pHclrFileNoFnNo(self, host):

    procs = []
    proc = mp.Process(target=self.clrFileNoFnNoWritefile, args=(host,))
    proc.daemon = False
    proc2 = mp.Process(target=self.clrFileNoFnNoPrintoutput, args=(host,))
    proc2.daemon = True

    procs.append(proc)
    procs.append(proc2)

    for proc in procs:
        proc.start()
</code>```

Body:
I have a code that takes the host address, asks for filename (to save on user's desktop) and asks if user's want to clear the file or append to it.

when it runs, it prints the output to screen first and then writes the file.
how can I use multiproccessing to make them work simultaneously?
 i've tried with target= and they run but still one after another and not together.

......................................................................................................................................

(Don't mind the host, filename, clear input validation, they're here for testing multiproccessing)

Code: (I used the first condition to test the multiproccess)

import multiprocessing as mp
import subprocess as sub
import sys
import os

class pingURL():

    def __init__(self):
        self.t2d = mp.Queue()
        self.tf = mp.Queue()
        host = input("Enter Host: ")
        filename = input("Enter filename: ")
        clear = input("Clear File? [Y/n] ")

        print(clear, filename)  # For Debugging Input Validation

        if clear.lower() == 'y' and filename == '':
            self.pHclrFileYesFnNo(host)
            # self.clrFileYesFnNoWritefile(host)
            # self.clrFileYesFnNoPrintoutput(host)
        elif clear.lower() == 'n' and filename == '':
            self.clrFileNoFnNoPrintoutput(host)
            self.clrFileNoFnNoWritefile(host)
        elif clear.lower() == 'y' and filename != '':
            self.clrFileYesFnYesPrintoutput(host)
            self.clrFileYesFnYesWritefile(host, filename)
        elif clear.lower() == 'n' and filename != '':
            self.clrFileNoFnYesPrintoutput(host)
            self.clrFileNoFnYesWritefile(host, filename)

    def pHclrFileYesFnNo(self, host):

        procs = []

        proc = mp.Process(name="Clear + No Filename + Print Output", target=self.clrFileYesFnNoPrintoutput(host))
        proc2 = mp.Process(name="Clear + No Filename + Write to file", target=self.clrFileYesFnNoWritefile(host))

        procs.append(proc)
        procs.append(proc2)

        for proc in procs:
            proc.start()
            proc.join()

    def clrFileYesFnNoPrintoutput(self, host):

        print(f'Number of procceccess: {mp.cpu_count()}')
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileYesFnNoWritefile(self, host):

        print(f'Number of procceccess: {mp.cpu_count()}')
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')

        file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
        with open(file, 'a') as output:
            output.truncate(0)
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

    def clrFileNoFnNoPrintoutput(self, host):

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileNoFnNoWritefile(self, host):

        file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
        with open(file, 'a') as output:
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

    def clrFileYesFnYesPrintoutput(self, host):

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileYesFnYesWritefile(self, host, filename):

        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'
        with open(file, 'a') as output:
            output.truncate(0)
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

    def clrFileNoFnYesPrintoutput(self, host):

        with sub.Popen(['ping', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    def clrFileNoFnYesWritefile(self, host, filename):

        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'
        with open(file, 'a') as output:
            sub.call(['ping', f'{host}'], stdout=output)

        output.close()

if __name__ == "__main__":

    pingURL()

I get the same Proccess name and ID when running the script:

Body:
well the solution was defining a handler for every condition.
that worked for me.

def pHclrFileNoFnNo(self, host):

    procs = []
    proc = mp.Process(target=self.clrFileNoFnNoWritefile, args=(host,))
    proc.daemon = False
    proc2 = mp.Process(target=self.clrFileNoFnNoPrintoutput, args=(host,))
    proc2.daemon = True

    procs.append(proc)
    procs.append(proc2)

    for proc in procs:
        proc.start()


问:
Why do PHP and MySQL unix timestamps diverge on 1983-10-29?
I've been using PHP's strtotime and MySQL's UNIX_TIMESTAMP functions in my app, to convert dates into timestamps.  PHP and MySQL are running on my local machine, and these functions generally return the same result, as I expect them to:

```<code>$ php
<?php echo strtotime("2011-06-02"); ?>
1307001600

mysql> SELECT UNIX_TIMESTAMP("2011-06-02") ts;
+------------+
| ts         |
+------------+
| 1307001600 |
+------------+
</code>```

But, sorta by chance, I happened to notice that when I entered 1983-01-01 as the date, the results were no longer equal:

```<code>$ php
<?php echo strtotime("1983-01-01"); ?>
410263200

mysql> SELECT UNIX_TIMESTAMP("1983-01-01") ts;
+-----------+
| ts        |
+-----------+
| 410256000 |
+-----------+
</code>```

As you can see, PHP returned 410263200, while MySQL returned 410256000 - a difference of 7200 seconds.

This got me curious, and I wanted to know on what date the timestamps were no longer equivalent, so I wrote a little program that starts with today's date (in Y-m-d format), uses PHP's strtotime and MySQL's UNIX_TIMESTAMP and compares the results. It then subtracts 1 day from each value and loops until they're no longer equal.

The result:

1983-10-29

On October 29, 1983, for some reason, strtotime and UNIX_TIMESTAMP return values that differ by 7200 seconds.

Any ideas?

Thanks for reading.

答:
You say you're on Alaskan time. From http://www.statoids.com/tus.html:

1983-10-30 02:00: All parts of Alaska except the Aleutians and Saint Lawrence Island switched to AT. Prior to the change, Alaska east of 138°W (Juneau) had been on PT; between 138°W and 141°W (Yakutat) had been on Yukon Time, which was UTC-9 with DST; west of 162°W (Nome) had been on Bering Time, which was UTC-11 with DST. Name of Alaska-Hawaii zone changed to Hawaii-Aleutian.

So, I'd guess that this is because your timezone changed by two hours (7200 seconds = 2 hours) on 30th October 1983.

I'd guess that MySQL's UNIX_TIMESTAMP is using a different timezone from your Alaskan setting in PHP, which may be either the server default, or dependent on your connection settings, so these diverge when you hit that date.

You may be able to glean more information by asking MySQL what its timezone setting is on that connection with SELECT @@global.time_zone, @@session.time_zone;; see this answer for more info on the output and how to interpret it.

Body:
I've been using PHP's strtotime and MySQL's UNIX_TIMESTAMP functions in my app, to convert dates into timestamps.  PHP and MySQL are running on my local machine, and these functions generally return the same result, as I expect them to:

$ php
<?php echo strtotime("2011-06-02"); ?>
1307001600

mysql> SELECT UNIX_TIMESTAMP("2011-06-02") ts;
+------------+
| ts         |
+------------+
| 1307001600 |
+------------+

But, sorta by chance, I happened to notice that when I entered 1983-01-01 as the date, the results were no longer equal:

$ php
<?php echo strtotime("1983-01-01"); ?>
410263200

mysql> SELECT UNIX_TIMESTAMP("1983-01-01") ts;
+-----------+
| ts        |
+-----------+
| 410256000 |
+-----------+

As you can see, PHP returned 410263200, while MySQL returned 410256000 - a difference of 7200 seconds.

This got me curious, and I wanted to know on what date the timestamps were no longer equivalent, so I wrote a little program that starts with today's date (in Y-m-d format), uses PHP's strtotime and MySQL's UNIX_TIMESTAMP and compares the results. It then subtracts 1 day from each value and loops until they're no longer equal.

The result:

1983-10-29

On October 29, 1983, for some reason, strtotime and UNIX_TIMESTAMP return values that differ by 7200 seconds.

Any ideas?

Thanks for reading.


问:
How to redirect traffic from hostname to a custom IP address in Kubernetes (AKS)?
I'm following this tutorial:
https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/

But it seems not to be working even though when I run cat /etc/hosts inside the pod I can see my hostname there. Is there any other way of achieving this? I also tried with kube-dns, but that will just redirect the traffic to custom DNS server IP rather than normal server IP?

I have a service with a single pod where I would like to rewire one hostname to go to a custom IP address for testing purposes.

nslookup gives:

```<code>root@manager-admin-5944869775-x59n5:/app# nslookup xxxxx.azure-devices.net
Server:         10.0.0.10
Address:        10.0.0.10#53

Non-authoritative answer:
xxxxx.azure-devices.net        canonical name = ihsu-prod-bl-004.cloudapp.net.
Name:   ihsu-prod-bl-004.cloudapp.net
Address: 137.117.83.38
</code>```

While hosts are:

```<code>root@manager-admin-5944869775-x59n5:/app# cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
10.244.2.104    manager-admin-5944869775-x59n5
40.84.159.16 xxxxx.azure-devices.net
</code>```

Any ideas or help?

答:
That should work...Anyway its not a best practice as you probably know...

Anyway, try first if you have connectivity to the IP "telnet 40.84.159.16 80" (You will have to install telnet if you don't have it, and if 80 is the port you want call). It could be for example a firewall issue on the outbound connectivity of the cluster or the incoming connections from your service you are trying to connect.

However if you can't...Try to use core-dns as you mentioned with the Host Plugin.

And as a last resort you can specify on a Pod a DNS nameserver which modifies the /etc/resolv.conf file of the pod (You ccould do that with CoreDNS too).

Of course this last approach relies you can modify your DNS entries, and that you will not have any DNS conflict, which most sure will appear...

```<code>apiVersion: v1
kind: Pod
metadata:
  namespace: default
  name: dns-example
spec:
  containers:
    - name: test
      image: nginx
  dnsPolicy: "None"
  dnsConfig:
    nameservers:
      - 1.2.3.4
    searches:
      - ns1.svc.cluster-domain.example
      - my.dns.search.suffix
    options:
      - name: ndots
        value: "2"
      - name: edns0
</code>```

Body:
I'm following this tutorial:
https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/

But it seems not to be working even though when I run cat /etc/hosts inside the pod I can see my hostname there. Is there any other way of achieving this? I also tried with kube-dns, but that will just redirect the traffic to custom DNS server IP rather than normal server IP?

I have a service with a single pod where I would like to rewire one hostname to go to a custom IP address for testing purposes.

nslookup gives:

root@manager-admin-5944869775-x59n5:/app# nslookup xxxxx.azure-devices.net
Server:         10.0.0.10
Address:        10.0.0.10#53

Non-authoritative answer:
xxxxx.azure-devices.net        canonical name = ihsu-prod-bl-004.cloudapp.net.
Name:   ihsu-prod-bl-004.cloudapp.net
Address: 137.117.83.38

While hosts are:

root@manager-admin-5944869775-x59n5:/app# cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
10.244.2.104    manager-admin-5944869775-x59n5
40.84.159.16 xxxxx.azure-devices.net

Any ideas or help?

Body:
That should work...Anyway its not a best practice as you probably know...

Anyway, try first if you have connectivity to the IP "telnet 40.84.159.16 80" (You will have to install telnet if you don't have it, and if 80 is the port you want call). It could be for example a firewall issue on the outbound connectivity of the cluster or the incoming connections from your service you are trying to connect.

However if you can't...Try to use core-dns as you mentioned with the Host Plugin.

And as a last resort you can specify on a Pod a DNS nameserver which modifies the /etc/resolv.conf file of the pod (You ccould do that with CoreDNS too).

Of course this last approach relies you can modify your DNS entries, and that you will not have any DNS conflict, which most sure will appear...

apiVersion: v1
kind: Pod
metadata:
  namespace: default
  name: dns-example
spec:
  containers:
    - name: test
      image: nginx
  dnsPolicy: "None"
  dnsConfig:
    nameservers:
      - 1.2.3.4
    searches:
      - ns1.svc.cluster-domain.example
      - my.dns.search.suffix
    options:
      - name: ndots
        value: "2"
      - name: edns0


问:
Call Child Method from Parent with react-native
I know that this is a pretty common question but some answers I found on the internet are deprecated.
How do you call a method of a Child Component from the Parent Component in 2020?

My actual code is something like this but it's not working

Child:

```<code>export default class CustomComp extends React.Component{
  exampleMethod = () => {
    console.log('pressed');
  };

  render(){
    return (
      ...
    );
  }
}
</code>```

Parent:

```<code>export default class App extends React.Component{
  child = CustomComp;
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={this.child.exampleMethod} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}
</code>```

答:
You can follow in this example. Here I used React.createRef and pass the ref into child and then I called this.child.current.getAlert

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

export default class MyParent extends React.Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  onClick = () => {
    this.child.current.getAlert('Mr. Kamal');
  };

  render() {
    return (
      <div>
        <Child ref={this.child} />
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

class Child extends React.Component {
    getAlert(name) {
        alert(`Hi ${name}`);
    }

    render() {
        return <h1>Hello</h1>;
    }
}
</code>```

Body:
I know that this is a pretty common question but some answers I found on the internet are deprecated.
How do you call a method of a Child Component from the Parent Component in 2020?

My actual code is something like this but it's not working

Child:

export default class CustomComp extends React.Component{
  exampleMethod = () => {
    console.log('pressed');
  };

  render(){
    return (
      ...
    );
  }
}

Parent:

export default class App extends React.Component{
  child = CustomComp;
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={this.child.exampleMethod} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}

Body:
You can follow in this example. Here I used React.createRef and pass the ref into child and then I called this.child.current.getAlert

import React, {useRef} from "react";

export default class MyParent extends React.Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  onClick = () => {
    this.child.current.getAlert('Mr. Kamal');
  };

  render() {
    return (
      <div>
        <Child ref={this.child} />
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

class Child extends React.Component {
    getAlert(name) {
        alert(`Hi ${name}`);
    }

    render() {
        return <h1>Hello</h1>;
    }
}


问:
React CSSTransition between sub routes
```<code>App Component:
<TransitionGroup>
    <CSSTransition classNames="slide">
        <Switch>
            <Route path='/page1' component={Page1} />
            <Route path='/page2/:tab' component={Page2} />
        </Switch>
    </CSSTransition>
</TransitionGroup>

Page2 Component:
<TransitionGroup>
    <CSSTransition classNames="fade">
        <Switch>
            <Route path='/tab1' component={T1} />
            <Route path='/tab2' component={T2} />
        </Switch>
    </CSSTransition>
</TransitionGroup>
</code>```

I want two type of animations. One between pages and one between tabs within a page.
But when I click on page2/tab1 or page2/tab2 animations of pages (slide) apply.
When I want to apply animation of tabs (fade). Is there a way to fix it?

答: You should use SwitchTransition instead of TransitionGroup in your "App Component". Read second paragraph in documentation http://reactcommunity.org/react-transition-group/switch-transition

Title: React CSSTransition between sub routes

Body:
App Component:
<TransitionGroup>
    <CSSTransition classNames="slide">
        <Switch>
            <Route path='/page1' component={Page1} />
            <Route path='/page2/:tab' component={Page2} />
        </Switch>
    </CSSTransition>
</TransitionGroup>

Page2 Component:
<TransitionGroup>
    <CSSTransition classNames="fade">
        <Switch>
            <Route path='/tab1' component={T1} />
            <Route path='/tab2' component={T2} />
        </Switch>
    </CSSTransition>
</TransitionGroup>

I want two type of animations. One between pages and one between tabs within a page.
But when I click on page2/tab1 or page2/tab2 animations of pages (slide) apply.
When I want to apply animation of tabs (fade). Is there a way to fix it?


问:
Why batch sometimes does not process commands like CMD does and gives unexpected and different results
When I run a command from the CMD directly it works perfectly fine but when run the same command in a batch file (or Jenkins using batch) it gives me a different result and I dont understand why.

To explain it simple, I'm running command below to search for a literal string within a log file:

```<code>findstr /C:"MY STRING WITH A %variable%" M:\Logs\output.log
</code>```

If I check the %ERRORLEVEL% of the result it shows the expected values (0 = found the string or 1 = didnt find it)

However, when I run the same line from a batch file, even from Jenkins, the result is always 0, even though the string is not present in the log, the %ERRORLEVEL% is always 0.

This is the portion of the batch file which includes the command:

if %COUNTER% ==1 (
    if not exist M:\Logs\current_bak (
        ROBOCOPY "M:\Logs\tkcurrent" "M:\Logs\tkcurrent_bak"
        REN "M:\Logs\current" "M:\Logs\current_bak"
        MKDIR M:\Logs\current
        echo Folders have been backed up
    ) else (
        echo Back up folders are already in place )

    findstr /C:"MY STRING WITH A %variable%" M:\Logs\output.log
    if %ERRORLEVEL% == 0 (
        echo Process has already being kicked off for the files with date %YYMMDD%, skipping it...
        echo Download and backup compleated
        exit /b 0 )
    else (
        echo Triggering next Jenkins Job:
        curl -I http://<user>:<token>@remoteserver.domain.com:<port>/job/Hello_World/build?token=hello_world
        exit /b 0 )
)
```

Has someone experienced this in the past or can guide me better on what I'm doing wrong or not understanding?

Thanks a lot!

答:
Your error is a basic syntactical error that I've made plenty of times as well :P. The issue is in your else statement which is a peculiar issue, but what happens is that the else only will get processed if it is on the same line as the if statement.

PROOF OF CONCEPT

If I have the if statement and else on different lines like so:

@echo off
echo test
if errorlevel 1 (echo here)
else (echo not there)
pause
```

<p>This will have the error:</p>

```'else' is not recognized as an internal or external command,
operable program or batch file.
```

<p>However if I change the code a tiny bit so that the else is on the same line as the if, like so:</p>

<pre class="lang-bat prettyprint-override"><code>@echo off
echo test
if errorlevel 1 (echo here
) else (echo not there)
pause
</code>```

It will not have an error and output

```<code>test
not there
</code>```

Your code done correctly would be:

if %COUNTER%==1 (
    if not exist M:\Logs\current_bak (
        ROBOCOPY "M:\Logs\tkcurrent" "M:\Logs\tkcurrent_bak"
        REN "M:\Logs\current" "M:\Logs\current_bak"
        MKDIR M:\Logs\current
        echo Folders have been backed up
    ) else (
        echo Back up folders are already in place )

    findstr /C:"MY STRING WITH A %variable%" M:\Logs\output.log
    if %ERRORLEVEL% == 0 (
        echo Process has already being kicked off for the files with date %YYMMDD%, skipping it...
        echo Download and backup compleated
        exit /b 0
    ) else (
        echo Triggering next Jenkins Job:
        curl -I http://<user>:<token>@remoteserver.domain.com:<port>/job/Hello_World/build?token=hello_world
        exit /b 0 )
)
```

For more information on this type in if /? into cmd.

Note: I also fixed I believe a typo in your code of findsrt instead of findstr

Body:
When I run a command from the CMD directly it works perfectly fine but when run the same command in a batch file (or Jenkins using batch) it gives me a different result and I dont understand why.

To explain it simple, I'm running command below to search for a literal string within a log file:

findstr /C:"MY STRING WITH A %variable%" M:\Logs\output.log

If I check the %ERRORLEVEL% of the result it shows the expected values (0 = found the string or 1 = didnt find it)

However, when I run the same line from a batch file, even from Jenkins, the result is always 0, even though the string is not present in the log, the %ERRORLEVEL% is always 0.

This is the portion of the batch file which includes the command:

if %COUNTER% ==1 (
    if not exist M:\Logs\current_bak (
        ROBOCOPY "M:\Logs\tkcurrent" "M:\Logs\tkcurrent_bak"
        REN "M:\Logs\current" "M:\Logs\current_bak"
        MKDIR M:\Logs\current
        echo Folders have been backed up
    ) else (
        echo Back up folders are already in place )

    findstr /C:"MY STRING WITH A %variable%" M:\Logs\output.log
    if %ERRORLEVEL% == 0 (
        echo Process has already being kicked off for the files with date %YYMMDD%, skipping it...
        echo Download and backup compleated
        exit /b 0 )
    else (
        echo Triggering next Jenkins Job:
        curl -I http://<user>:<token>@remoteserver.domain.com:<port>/job/Hello_World/build?token=hello_world
        exit /b 0 )
)

Has someone experienced this in the past or can guide me better on what I'm doing wrong or not understanding?

Thanks a lot!

Body:
Your error is a basic syntactical error that I've made plenty of times as well :P. The issue is in your else statement which is a peculiar issue, but what happens is that the else only will get processed if it is on the same line as the if statement.

PROOF OF CONCEPT

If I have the if statement and else on different lines like so:

@echo off
echo test
if errorlevel 1 (echo here)
else (echo not there)
pause

This will have the error:

'else' is not recognized as an internal or external command,
operable program or batch file.

However if I change the code a tiny bit so that the else is on the same line as the if, like so:

@echo off
echo test
if errorlevel 1 (echo here
) else (echo not there)
pause

It will not have an error and output

test
not there

Your code done correctly would be:

if %COUNTER%==1 (
    if not exist M:\Logs\current_bak (
        ROBOCOPY "M:\Logs\tkcurrent" "M:\Logs\tkcurrent_bak"
        REN "M:\Logs\current" "M:\Logs\current_bak"
        MKDIR M:\Logs\current
        echo Folders have been backed up
    ) else (
        echo Back up folders are already in place )

    findstr /C:"MY STRING WITH A %variable%" M:\Logs\output.log
    if %ERRORLEVEL% == 0 (
        echo Process has already being kicked off for the files with date %YYMMDD%, skipping it...
        echo Download and backup compleated
        exit /b 0
    ) else (
        echo Triggering next Jenkins Job:
        curl -I http://<user>:<token>@remoteserver.domain.com:<port>/job/Hello_World/build?token=hello_world
        exit /b 0 )
)

For more information on this type in if /? into cmd.

Note: I also fixed I believe a typo in your code of findsrt instead of findstr


问:
Springboot with multiple filters
I am using spring boot and integrated Azure AD. For that, I have used AADAuthenticationFilter.

In my WebSecurityConfig which extends WebSecurityConfigurerAdapter I have written:

http.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);

How to add one more filter before executing the above line, for doing some custom filtering?

答:
You could use Order annotation.

The value Ordered.HIGHEST_PRECEDENCE can be used for overriding the highest priority among components.

```<code>@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyFilter implements Filter {
</code>```

Or you could control order at a more controlled way, like for the first one:

@Order(1)

For second:

@Order(2)

Useful reference:

@Order in Spring

How to define Spring Boot filter

Title: Springboot with multiple filters

Body:
You could use Order annotation.

The value Ordered.HIGHEST_PRECEDENCE can be used for overriding the highest priority among components.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyFilter implements Filter {

Or you could control order at a more controlled way, like for the first one:

@Order(1)

For second:

@Order(2)

Useful reference:

@Order in Spring

How to define Spring Boot filter


问:
How to create a directory and give permission in single command
How to create a directory and give permission in single command in Linux?

I have to create lots of folder with full permission 777.

Commands

```<code>mkdir path/foldername
chmod 777 path/foldername
</code>```

I don't like to create and give permission in two commands. Can I do this in single command?

答:
Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)
```

Note that this won't change the permissions if any of a, b and c already exist though.

Body:
How to create a directory and give permission in single command in Linux?

I have to create lots of folder with full permission 777.

Commands

mkdir path/foldername
chmod 777 path/foldername

I don't like to create and give permission in two commands. Can I do this in single command?

Body:
Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)

Note that this won't change the permissions if any of a, b and c already exist though.


问:
Why should someone use Identity Range Management with SQL Server
When I began to work on replication a few years ago, I was convinced that Identity Range Management was only made available in recent SQL Servers for legacy purposes as, prior to SQL Server 2000, the GUID type field did not exist and most primary keys were built on autoincrement fields.

I already saw some of these databases 'at work', and I can say that managing these Identity Ranges in a complex replication topology can be a real PITA, with guaranteed headaches and all-night-long debugging sessions.

I have just read here that Identity Range Management was still proposed as default with SQL Server 2008, followed by this other question on Best Practises and Identity Range Management where #mwolfe02 reaches the conclusion that, in some situations, users cannot insert data in the database unless they are granted db owner's right!

Disturbing, isn't it. So, with the exception of legacy databases, why should someone use Identity Range Management with SQL Servers? In a more generic way, why would someone promote any predetermined\autoincrement identification method in a database?

答:
I guess one of the reasons to continue to use identity values is because of the disadvantages of using GUIDs as primary keys in a database, which is documented here GUIDs as PRIMARY KEYs.

I personally have never worked with a complex replication topology and have always used integers when setting up replication. I manage the identity ranges by adjusting the increment value of the identity function, so if I have two servers in replication I would have odd numbers on one and even numbers on the other and increment by 2. The same setup applies with multiple servers, the increment set equal to the number of servers.

I would also start my identity range at the lowest number for an integer (-2,147,483,648 to 2,147,483,647) as there is a lot of values that don't get used as integer identity columns are more often than not started at one. Even if you have 20 servers involved that still gives you quite a range of values to use.


问:
Using PostMessage() or SendMessage() to send uppercase letters
I'm trying to send uppercase letters or symbols (!@# etc), using the PostMessage() function:

```<code>[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
</code>```

I tried sending both shift and the letter I want to send in upper case but it doesn't seem to work:

```<code>        public const uint WM_KEYUP = 0x0101;
        public const uint WM_KEYDOWN = 0x100;

        void function()
        {
            Keys key = Keys.A;
            Keys shift = Keys.ShiftKey;

            PostMessage(process.MainWindowHandle, WM_KEYDOWN, (IntPtr)shift, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYDOWN, (IntPtr)key, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYUP, (IntPtr)shift, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYUP, (IntPtr)key, IntPtr.Zero);
        }
</code>```

Edit: for those wondering: I ended up using SendInput() to send the shift key press, because apparently many games don't detect the shift key press the same way they detect other key presses that's why it didn't detect the shift key press when I tried sending it with PostMessage(), you can also use keybd_event() and SendKeys(). Note: that these methods don't send the keys to a specific process.

答:
Try this instead of using WM_KEYDOWN and WM_KEYUP:

```<code>        public const uint WM_CHAR = 0x0102;

            ...

            PostMessage(process.MainWindowHandle, WM_CHAR, (IntPtr)'A', IntPtr.Zero);
</code>```

Full Solution: Create a C# Console App (Mine was .NET Framework 4.7.2)

```<code>using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace PostMessageTest
{
    class Program
    {
        [DllImport("user32.dll")]
        public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        public const uint WM_CHAR = 0x0102;

        public static void function()
        {
            IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
            Console.WriteLine("Sending Keys...");
            PostMessage(handle, WM_CHAR, (IntPtr)'A', IntPtr.Zero); // 0x41
        }

        static void Main(string[] args)
        {
            function();
            Console.Read();
        }
    }
}

</code>```

Body:
I'm trying to send uppercase letters or symbols (!@# etc), using the PostMessage() function:

[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

I tried sending both shift and the letter I want to send in upper case but it doesn't seem to work:

        public const uint WM_KEYUP = 0x0101;
        public const uint WM_KEYDOWN = 0x100;

        void function()
        {
            Keys key = Keys.A;
            Keys shift = Keys.ShiftKey;

            PostMessage(process.MainWindowHandle, WM_KEYDOWN, (IntPtr)shift, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYDOWN, (IntPtr)key, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYUP, (IntPtr)shift, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYUP, (IntPtr)key, IntPtr.Zero);
        }

Edit: for those wondering: I ended up using SendInput() to send the shift key press, because apparently many games don't detect the shift key press the same way they detect other key presses that's why it didn't detect the shift key press when I tried sending it with PostMessage(), you can also use keybd_event() and SendKeys(). Note: that these methods don't send the keys to a specific process.

Body:
Try this instead of using WM_KEYDOWN and WM_KEYUP:

        public const uint WM_CHAR = 0x0102;

            ...

            PostMessage(process.MainWindowHandle, WM_CHAR, (IntPtr)'A', IntPtr.Zero);

Full Solution: Create a C# Console App (Mine was .NET Framework 4.7.2)

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace PostMessageTest
{
    class Program
    {
        [DllImport("user32.dll")]
        public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        public const uint WM_CHAR = 0x0102;

        public static void function()
        {
            IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
            Console.WriteLine("Sending Keys...");
            PostMessage(handle, WM_CHAR, (IntPtr)'A', IntPtr.Zero); // 0x41
        }

        static void Main(string[] args)
        {
            function();
            Console.Read();
        }
    }
}


问:
angular2 - How to DOM select a dynamically created element and focus it?
I have a dynamic HTML list of elements, that all have a specific attribute (for example 'role=option').

I want to select the first element and give it focus. In angular 1, it was possible through:

```<code>angular.element(document.querySelector('[role="option"]')).focus()
</code>```

In angular2, I can't find the equivalent way of doing this. All answers seem to involve viewChild and giving a specific #ref to an element, but the HTML is created dynamically through *ngFor, so every element would end up with the same #ref in the loop.

How to do this?

答:
You could still use the template reference variable and use ViewChildren and the first property to focus on the first element in the QueryList. Try the following

Template

<ng-container *ngFor="let item of items; let i=index">
  <input #input (change)="templateRefVariable(input.value)"/>

</ng-container>
```

<p>Controller</p>

<pre class="lang-js prettyprint-override"><code>import { Component, TemplateRef, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  items = ['item1', 'item2', 'item3', 'item4'];
  @ViewChildren('input') inputElems: QueryList<ElementRef>;

  templateRefVariable(value) {
    console.log(value);
  }

  ngAfterViewInit() {
    this.inputElems.first.nativeElement.focus();
  }
}
</code>```

Working example: Stackblitz

Body:
I have a dynamic HTML list of elements, that all have a specific attribute (for example 'role=option').

I want to select the first element and give it focus. In angular 1, it was possible through:

angular.element(document.querySelector('[role="option"]')).focus()

In angular2, I can't find the equivalent way of doing this. All answers seem to involve viewChild and giving a specific #ref to an element, but the HTML is created dynamically through *ngFor, so every element would end up with the same #ref in the loop.

How to do this?

Body:
You could still use the template reference variable and use ViewChildren and the first property to focus on the first element in the QueryList. Try the following

Template

<ng-container *ngFor="let item of items; let i=index">
  <input #input (change)="templateRefVariable(input.value)"/>
  <br />
</ng-container>

Controller

import { Component, TemplateRef, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  items = ['item1', 'item2', 'item3', 'item4'];
  @ViewChildren('input') inputElems: QueryList<ElementRef>;

  templateRefVariable(value) {
    console.log(value);
  }

  ngAfterViewInit() {
    this.inputElems.first.nativeElement.focus();
  }
}

Working example: Stackblitz


问:
Iterating over double 'for-each' function in javascript returning undefined when getting property from 'this' keyword
This must be a stupid question, but I am not able to figure anything to do about it.

I have a simple HTML table with every  element having a property 'data-value'. I need to do some operations based on that, but one column at a time. Hence, I wrote a function which only runs on the first td element of each row. I am getting the rows by running another for each function.

When I use console.log($(this)), I am getting the expected td element from the all the first columns. Now, I want to store the 'data-value' property in another variable and do stuff on it.

```<code>  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});
</code>```

As seen here, all the td elements are correctly being logged on console.

But when I use jquery to get the property 'data-value' from it, I get undefined.

What could be the error ? Is this the best way to iterate every column's tds property  ?

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this).attr('data-value'));
    //returns tr object which does not have the 'data-value'property
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}</code>```

HTML Table

      first_name
      is_staff
      last_name

      id

      1
      1
      True
      1

      3
      1
      True
      1

      4
      1
      True
      1

      5
      1
      True
      1

      6
      1
      True
      1

      7
      1
      True
      1

```

答:
Here's a simple way to obtain the data, using vanilla JavaScript:

form array of
 elements

map tr array to array of td data-property values

// array of
 elements
let trs = Array.from(document.querySelectorAll('#table_canvas tbody tr'));

// array of 'data-property' values
let props = trs.map(tr =>
  tr.querySelector('td').dataset.property);
console.log('props:', JSON.stringify(props));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}</code>```

      first_name
      is_staff
      last_name

      id

      1
      1
      True
      1

      3
      1
      True
      1

      4
      1
      True
      1

      5
      1
      True
      1

      6
      1
      True
      1

      7
      1
      True
      1

```

Body:
This must be a stupid question, but I am not able to figure anything to do about it.

I have a simple HTML table with every  element having a property 'data-value'. I need to do some operations based on that, but one column at a time. Hence, I wrote a function which only runs on the first td element of each row. I am getting the rows by running another for each function.

When I use console.log($(this)), I am getting the expected td element from the all the first columns. Now, I want to store the 'data-value' property in another variable and do stuff on it.

  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});

As seen here, all the td elements are correctly being logged on console.

But when I use jquery to get the property 'data-value' from it, I get undefined.

What could be the error ? Is this the best way to iterate every column's tds property  ?

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this).attr('data-value'));
    //returns tr object which does not have the 'data-value'property
  })
});

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

HTML Table

      first_name
      is_staff
      last_name

      id

      1
      1
      True
      1

      3
      1
      True
      1

      4
      1
      True
      1

      5
      1
      True
      1

      6
      1
      True
      1

      7
      1
      True
      1

Body:
Here's a simple way to obtain the data, using vanilla JavaScript:

form array of <tr> elements

map tr array to array of td data-property values

// array of <tr> elements
let trs = Array.from(document.querySelectorAll('#table_canvas tbody tr'));

// array of 'data-property' values
let props = trs.map(tr =>
  tr.querySelector('td').dataset.property);
console.log('props:', JSON.stringify(props));

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

<table id="table_canvas" class="table table--bordered" style="width: 100%; height: 100%;">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>first_name</th>
      <th>is_staff</th>
      <th>last_name</th>
    </tr>
    <tr>
      <th>id</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th hello="hi">1</th>
      <td data-property="1">1</td>
      <td data-property="True">True</td>
      <td data-property="1">1</td>
    </tr>
    <tr>
      <th>3</th>
      <td data-property="1">1</td>
      <td data-property="True">True</td>
      <td data-property="1">1</td>
    </tr>
    <tr>
      <th>4</th>
      <td data-property="1">1</td>
      <td data-property="True">True</td>
      <td data-property="1">1</td>
    </tr>
    <tr>
      <th>5</th>
      <td data-property="1">1</td>
      <td data-property="True">True</td>
      <td data-property="1">1</td>
    </tr>
    <tr>
      <th>6</th>
      <td data-property="1">1</td>
      <td data-property="True">True</td>
      <td data-property="1">1</td>
    </tr>
    <tr>
      <th>7</th>
      <td data-property="1">1</td>
      <td data-property="True">True</td>
      <td data-property="1">1</td>
    </tr>
  </tbody>
</table>


问:
how can i check multiple (&&) in PHP if...else Statements
how can i check multiple (&&) in if else Statements

```<code>if (!$lock1 && !$lock2 && !$lock3 && !$lock4 && !$lock5 && !$lock6 && !$lock7 && !$lock8)
        {
            echo "ok";
        }else{
            echo 1;
        }
</code>```

note : the all variable just true or false

答:
You can use array_filter for this.</p>

```<code>$arr = [$lock1,$lock2,$lock3,$lock4,$lock5,$lock6,$lock7,$lock8];

if(count(array_filter($arr)) === 0){
  echo " all false ";
}else{
  echo "all not false";
}
</code>```

Body:
how can i check multiple (&&) in if else Statements

if (!$lock1 && !$lock2 && !$lock3 && !$lock4 && !$lock5 && !$lock6 && !$lock7 && !$lock8)
        {
            echo "ok";
        }else{
            echo 1;
        }

note : the all variable just true or false

Body:
You can use array_filter for this.

$arr = [$lock1,$lock2,$lock3,$lock4,$lock5,$lock6,$lock7,$lock8];

if(count(array_filter($arr)) === 0){
  echo " all false ";
}else{
  echo "all not false";
}


问:
Azure Function App Python Blob Trigger Huge file sizes
I am using Azure function apps(Python) with a blob trigger to process a CSV and move the records to a event hub. I have a working code(up to 50 rows) after following a standard documentation. However I want to know what approach should be followed if the file is in size range of a few GBs.
Will this entire file be sent to the Azure function in one go? What if it needs to be read in a chunks of fixed size or line by line, will the trigger concept of Azure support that?

I am looking for any approach/code for the above problem in python that avoid loading the complete file in the azure function container memory.

答:
If you have a file which is unwieldly for a normal web request, you will probably be better served by uploading it to an object storage implementation (presumably Azure Blob Storage will be most convenient for you) and sending the new destination address to the function.

AMQP messages (these are what Event Hub is under the hood) are really more suited for short amounts of data. You could perhaps also make each line, or blocks of lines, in your CSV a unique message, but that would depend hugely on your use case.

You will then likely want to choose an object which supports a stream, instead of a whole file at once, such as BlockBlobService here's a reasonable example showing how to do this.


问:
Initialization of a struct instance data member in constructor?
I have a c++ class which as a private data member has a struct defined:

```<code>Class example {

...

private:
   struct Impl;
   Impl& structure_;
};
</code>```

Assuming that the struct Impl is defined as follows:

```<code>struct example::Impl{
    int m1;
    int m2;
    int m3;
};
</code>```

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

```<code>example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}
</code>```

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks

答: You store your struct by reference in your class. A reference must point to a physical object, you can do two things. Store the object by value or by pointer.</p>

Body:
I have a c++ class which as a private data member has a struct defined:

Class example {

...

private:
   struct Impl;
   Impl& structure_;
};

Assuming that the struct Impl is defined as follows:

struct example::Impl{
    int m1;
    int m2;
    int m3;
};

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks


问:
Getting the access to the System.Printing namespace in .NET Core Console Application
Is there a way to get access to the System.Printing namespace from a .net core console application. I see it is available for a .net core WPF application. There is nothing in the documentation that specifies it is only available for WPF.

I have looked for System.Printing NuGet package with no luck

I am using C# .NET Core 3.1 on Windows 10

答:
Add the following framework reference to your .csproj file to be able to reference the System.Printing namespace:

```<code><ItemGroup>
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
</ItemGroup>
</code>```

Sources: https://github.com/dotnet/wpf/issues/871#issuecomment-501498045
https://learn.microsoft.com/en-us/dotnet/core/porting/cpp-cli

Sample:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
  </ItemGroup>

</Project>
</code>```

Body:
Add the following framework reference to your .csproj file to be able to reference the System.Printing namespace:

<ItemGroup>
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
</ItemGroup>

Sources: https://github.com/dotnet/wpf/issues/871#issuecomment-501498045
https://learn.microsoft.com/en-us/dotnet/core/porting/cpp-cli

Sample:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
  </ItemGroup>

</Project>


问:
Why does javascript import take so long?
I am importing a JSON file from my website's own directory on the front-end. After a user clicks a button, this code is executed in the browser:

```<code>const file = await import('./path-to-file')
</code>```

The file is exceptionally small - only 4KB. Yet using console.time() is showing that it takes about 300ms to execute this command. I have checked my own web speed which comes out at 74Mb/s. I am using Netlify to deploy the website and Bitcatcha is saying the server is 'exceptionally fast' with a response time of 133ms. I'm not sure exactly how the response time fits into all this - but all in all, 300ms seems absurdly long to be transferring just 4KB of data.

Why does it take so long, and what can be done to make it faster?

答:
Try doing:

```<code>const file = await require("./path-to-file"); //instead of import();
</code>```

I believe that it takes so long because of the use of await, so if the above does not work, try removing the await, because what await does is it stops async function execution until the require(); has resolved. If the code continues running as you get the content of the file, the overall time should shrink.
If none of the above works, try this:

```<code>const fs = require("fs");
fs.readFile("./path-to-file","utf-8",(err,d)=>{
    d = JSON.parse(d);
    //Then you do whatever you wanted to do with the file here
});
</code>```

Body:
I am importing a JSON file from my website's own directory on the front-end. After a user clicks a button, this code is executed in the browser:

const file = await import('./path-to-file')

The file is exceptionally small - only 4KB. Yet using console.time() is showing that it takes about 300ms to execute this command. I have checked my own web speed which comes out at 74Mb/s. I am using Netlify to deploy the website and Bitcatcha is saying the server is 'exceptionally fast' with a response time of 133ms. I'm not sure exactly how the response time fits into all this - but all in all, 300ms seems absurdly long to be transferring just 4KB of data.

Why does it take so long, and what can be done to make it faster?

Body:
Try doing:

const file = await require("./path-to-file"); //instead of import();

I believe that it takes so long because of the use of await, so if the above does not work, try removing the await, because what await does is it stops async function execution until the require(); has resolved. If the code continues running as you get the content of the file, the overall time should shrink.
If none of the above works, try this:

const fs = require("fs");
fs.readFile("./path-to-file","utf-8",(err,d)=>{
    d = JSON.parse(d);
    //Then you do whatever you wanted to do with the file here
});


问:
Indy 10.5.8.0 + XE2 + Windows 10 "Access violation at address 00000000. Read of address 00000000"
The code below works perfectly on Windows 7 machines 32 and 64 bits, it posts data to a https server on 5443 port and receive its response. However, machines with windows 10 it throws an Access violation at address 00000000. Read of address 00000000 message.

Some situations we might consider:

```<code> - Delphi XE2
 - Indy 10.5.8.0
 - [OpenSSL v1.1.1g][1]
 - Windows 10 Version 1909
 - No firewall and antivirus for tests
</code>```

Here's the code:

```<code>_idHTTP := TIdHTTP.Create(Self);
_idHTTP.AllowCookies := True;
_idHTTP.HandleRedirects := True;
_idHTTP.HTTPOptions := [hoForceEncodeParams];
_idHTTP.ProxyParams.BasicAuthentication := False;
_idHTTP.Request.Accept := 'text/html, */*';
_idHTTP.Request.BasicAuthentication := False;
_idHTTP.Request.ContentLength := -1;
_idHTTP.Request.ContentRangeEnd := -1;
_idHTTP.Request.ContentRangeInstanceLength := -1;
_idHTTP.Request.ContentRangeStart := -1;
_idHTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
_idHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(_idHTTP);

_idHTTP.Request.CustomHeaders.Clear;
_idHTTP.Request.CustomHeaders.AddValue('Content-Type', 'application/json');
_idHTTP.Request.CustomHeaders.AddValue('Accept', 'application/json');

try
    json := '{user: "<myuser>", pass: "<mypass>"}';
    RequestBody := TStringStream.Create(json, TEncoding.UTF8);
    try
        sRet := _idHTTP.Post('https://10.200.200.213:5443/auth', RequestBody);
    except
        raise ex;
    end;
finally
    _idHTTP.Free;
end;
</code>```

Edit:
The error message is throwing by the line

```<code>sRet := _idHTTP.Post('https://10.200.200.213:5443/auth', RequestBody);
</code>```

答:
As @zed commented, the problem is my OpenSSL version, it cannot be 1.1.1.
I installed 1.0.2 version from here and it's working now!</p>

Body:
The code below works perfectly on Windows 7 machines 32 and 64 bits, it posts data to a https server on 5443 port and receive its response. However, machines with windows 10 it throws an Access violation at address 00000000. Read of address 00000000 message.

Some situations we might consider:

 - Delphi XE2
 - Indy 10.5.8.0
 - [OpenSSL v1.1.1g][1]
 - Windows 10 Version 1909
 - No firewall and antivirus for tests

Here's the code:

_idHTTP := TIdHTTP.Create(Self);
_idHTTP.AllowCookies := True;
_idHTTP.HandleRedirects := True;
_idHTTP.HTTPOptions := [hoForceEncodeParams];
_idHTTP.ProxyParams.BasicAuthentication := False;
_idHTTP.Request.Accept := 'text/html, */*';
_idHTTP.Request.BasicAuthentication := False;
_idHTTP.Request.ContentLength := -1;
_idHTTP.Request.ContentRangeEnd := -1;
_idHTTP.Request.ContentRangeInstanceLength := -1;
_idHTTP.Request.ContentRangeStart := -1;
_idHTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
_idHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(_idHTTP);

_idHTTP.Request.CustomHeaders.Clear;
_idHTTP.Request.CustomHeaders.AddValue('Content-Type', 'application/json');
_idHTTP.Request.CustomHeaders.AddValue('Accept', 'application/json');

try
    json := '{user: "<myuser>", pass: "<mypass>"}';
    RequestBody := TStringStream.Create(json, TEncoding.UTF8);
    try
        sRet := _idHTTP.Post('https://10.200.200.213:5443/auth', RequestBody);
    except
        raise ex;
    end;
finally
    _idHTTP.Free;
end;

Edit:
The error message is throwing by the line

sRet := _idHTTP.Post('https://10.200.200.213:5443/auth', RequestBody);


问:
CSS 3: text rotation bug?
I don't understand how text rotation works in CSS3.

For instance, you can see it here, the rotated text is never on the right location as you want it,

```<code>right: 0;
bottom: 0;
</code>```

it will always have the gap/ margin to the right. and always overrun at the bottom of the box that contain it.

How can I fix this?

Can I use jquery to fix it or any reliable jquery plugin for text rotation out there ?

Thanks.

答:
Positioning rotated text in CSS is very difficult. You have to remember that the position takes effect BEFORE the text is rotated. If you remove the rotation in your example, you will see that the unrotated text is correctly positioned.

To correctly position rotated text, you have to calculate how the rotation will affect the position...and then correct that position in the stylesheet.

In your case, you need:

```<code>position: absolute;
right: -11px;
bottom: 9px;
</code>```

Title: CSS 3: text rotation bug?

Body:
I don't understand how text rotation works in CSS3.

For instance, you can see it here, the rotated text is never on the right location as you want it,

right: 0;
bottom: 0;

it will always have the gap/ margin to the right. and always overrun at the bottom of the box that contain it.

How can I fix this?

Can I use jquery to fix it or any reliable jquery plugin for text rotation out there ?

Thanks.

Body:
Positioning rotated text in CSS is very difficult. You have to remember that the position takes effect BEFORE the text is rotated. If you remove the rotation in your example, you will see that the unrotated text is correctly positioned.

To correctly position rotated text, you have to calculate how the rotation will affect the position...and then correct that position in the stylesheet.

In your case, you need:

position: absolute;
right: -11px;
bottom: 9px;


问:
How do I make my flex cell fill up its whole space?
Whenever I hover over the box, the cell's background takes up the full width (thanks to the width: 100%) but when I do the same with height, it doesn't do so. The parent doesn't have any padding, so how can I fix this?

I have looked at links like "https://css-tricks.com/boxes-fill-height-dont-squish/" and tried using flex-grow but it doesn't seem to work for me, but I am probably messing it up.

div {
  display: flex;
  flex-direction: row;
  background-color: lightgray;
  text-align: center;
  justify-content: space-evenly;
}

div p {
  font-size: 20px;
  color: black;
  font-weight: bold;
  width: 100%;
  height: 100%;
}

div p:hover {
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>Header1</p>
  <p>Header2</p>
  <p>Header3</p>
</div></code>```

答:
The paragraph elements have a default margin set on them.

You need to disable those and, instead, give a height to the container.

div {
  display: flex;
  justify-content: space-evenly;
  height: 75px;
  background-color: lightgray;
}

div p {
  margin: 0;      /* override default margins */
  flex: 1;        /* consume full width */
  display: flex;  /* for aligning content of flex item */
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: black;
  font-weight: bold;
}

div p:hover {
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>Header1</p>
  <p>Header2</p>
  <p>Header3</p>
</div></code>```

Understanding "block start":

"block-start" is the top in horizontal writing mode.

"inline-start" is the side where text begins. It's the left side in LTR.

"-end" refers to the opposite side.

source: § 6.2. Flow-relative Directions

Body:
Whenever I hover over the box, the cell's background takes up the full width (thanks to the width: 100%) but when I do the same with height, it doesn't do so. The parent doesn't have any padding, so how can I fix this?

I have looked at links like "https://css-tricks.com/boxes-fill-height-dont-squish/" and tried using flex-grow but it doesn't seem to work for me, but I am probably messing it up.

div {
  display: flex;
  flex-direction: row;
  background-color: lightgray;
  text-align: center;
  justify-content: space-evenly;
}

div p {
  font-size: 20px;
  color: black;
  font-weight: bold;
  width: 100%;
  height: 100%;
}

div p:hover {
  background-color: green;
}

Header1

Header2

Header3

Body:
The paragraph elements have a default margin set on them.

You need to disable those and, instead, give a height to the container.

div {
  display: flex;
  justify-content: space-evenly;
  height: 75px;
  background-color: lightgray;
}

div p {
  margin: 0;      /* override default margins */
  flex: 1;        /* consume full width */
  display: flex;  /* for aligning content of flex item */
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: black;
  font-weight: bold;
}

div p:hover {
  background-color: green;
}

<div>
  <p>Header1</p>
  <p>Header2</p>
  <p>Header3</p>
</div>

Understanding "block start":

"block-start" is the top in horizontal writing mode.

"inline-start" is the side where text begins. It's the left side in LTR.

"-end" refers to the opposite side.

source: § 6.2. Flow-relative Directions


问:
SwiftUi - hide "Back" button and navigation bar (appears for a fraction of second)
I'm using this code to hide a navigation bar and Back button but when the view is loaded i still can see the back button for a fraction of second and then it disappears. Is there any way to prevent it from being shown?

```<code>var body: some View {
    NavigationView {
        NavigationLink(destination: DeferView { WeekView(journey: self.launcher.completeJourney!) }, isActive: self.$launcher.readyJourney ) { EmptyView () }
        .navigationBarHidden(true)
        .navigationBarTitle("")
    }
}
</code>```

Thank you in advance,

答:
Add the same modifiers also for link destination,</p>

```<code>var body: some View {
    NavigationView {
        NavigationLink(destination: DeferView { WeekView(journey: self.launcher.completeJourney!) }
                                    .navigationBarHidden(true)   // here !!
                                    .navigationBarTitle("")      // here !!

              , isActive: self.$launcher.readyJourney ) { EmptyView () }
        .navigationBarHidden(true)
        .navigationBarTitle("")
    }
}
</code>```

Body:
I'm using this code to hide a navigation bar and Back button but when the view is loaded i still can see the back button for a fraction of second and then it disappears. Is there any way to prevent it from being shown?

var body: some View {
    NavigationView {
        NavigationLink(destination: DeferView { WeekView(journey: self.launcher.completeJourney!) }, isActive: self.$launcher.readyJourney ) { EmptyView () }
        .navigationBarHidden(true)
        .navigationBarTitle("")
    }
}

Thank you in advance,

Body:
Add the same modifiers also for link destination,

var body: some View {
    NavigationView {
        NavigationLink(destination: DeferView { WeekView(journey: self.launcher.completeJourney!) }
                                    .navigationBarHidden(true)   // here !!
                                    .navigationBarTitle("")      // here !!

              , isActive: self.$launcher.readyJourney ) { EmptyView () }
        .navigationBarHidden(true)
        .navigationBarTitle("")
    }
}


问:
Message flow intermittent when using Lenses MQTT Source connector with confluent kafka
I am trying to use Lenses MQTT source connector [https://docs.lenses.io/connectors/source/mqtt.html] with confluent kafka v5.4.

Following is my MQTT source connector properties file:

```<code>connector.class=com.datamountaineer.streamreactor.connect.mqtt.source.MqttSourceConnector
connect.mqtt.clean=false
key.converter.schemas.enable=false
connect.mqtt.timeout=1000
value.converter.schemas.enable=false
name=kmd-source-4
connect.mqtt.kcql=INSERT INTO kafka-source-topic-2   SELECT * FROM ctt/+/+/location WITHCONVERTER=`com.datamountaineer.streamreactor.connect.converters.source.JsonSimpleConverter` WITHKEY(id)
value.converter=org.apache.kafka.connect.json.JsonConverter
connect.mqtt.service.quality=1
key.converter=org.apache.kafka.connect.json.JsonConverter
connect.mqtt.hosts=tcp://ip:1883
connect.mqtt.converter.throw.on.error=true
connect.mqtt.username=username
connect.mqtt.password=password
errors.log.include.messages=true
errors.log.enable=true
</code>```

I am publishing messages from UI based MQTT client MQTT fx to MQTT topic 'ctt/+/+/location' and subscribing those messages on the kafka topic 'kafka-source-topic-2'.I am using Rabbit MQ as my MQTT broker and my confluent platform and RabbitMQ are on different VMs. I do not think using RabbitMQ broker instead of Mosquitto MQTT should be a problem. Whatever and whenever I publish from MQTT fx I successfully see the messages in the MQTT fx upon subscription. I had also set up confleunt MongoDB source connector and it works seamlessly.

But my problem is - the messages published on MQTT topic are available on the mapped kafka topic in an intermittent manner. What could be the reason? I do not see any error messages in kafka connect logs. Are there any connection related properties with respect to MQTT broker that I need to specify in my MQTT source properties file? Are there any properties to be included for sure in Rabbit MQ broker? Has anyone used Lenses MQTT source and sink connectors and would like to suggest anything about them?

答: Your connect.mqtt.timeout is only 1 second?!?  Intermittent messages suggests to me that your connector is timing out and has to re-establish its connection, and while its busy doing that, MQTT messages are coming in but not making it to the connector as it is not subscribed to the broker at that instance.  Try increasing your timeout to something like 60000 (1 minute) and see what happens. Is there any reason you need it to timeout?  RabbitMQ can handle connections that stay open for long periods of time with no traffic.</p>

Body:
I am trying to use Lenses MQTT source connector [https://docs.lenses.io/connectors/source/mqtt.html] with confluent kafka v5.4.

Following is my MQTT source connector properties file:

connector.class=com.datamountaineer.streamreactor.connect.mqtt.source.MqttSourceConnector
connect.mqtt.clean=false
key.converter.schemas.enable=false
connect.mqtt.timeout=1000
value.converter.schemas.enable=false
name=kmd-source-4
connect.mqtt.kcql=INSERT INTO kafka-source-topic-2   SELECT * FROM ctt/+/+/location WITHCONVERTER=`com.datamountaineer.streamreactor.connect.converters.source.JsonSimpleConverter` WITHKEY(id)
value.converter=org.apache.kafka.connect.json.JsonConverter
connect.mqtt.service.quality=1
key.converter=org.apache.kafka.connect.json.JsonConverter
connect.mqtt.hosts=tcp://ip:1883
connect.mqtt.converter.throw.on.error=true
connect.mqtt.username=username
connect.mqtt.password=password
errors.log.include.messages=true
errors.log.enable=true

I am publishing messages from UI based MQTT client MQTT fx to MQTT topic 'ctt/+/+/location' and subscribing those messages on the kafka topic 'kafka-source-topic-2'.I am using Rabbit MQ as my MQTT broker and my confluent platform and RabbitMQ are on different VMs. I do not think using RabbitMQ broker instead of Mosquitto MQTT should be a problem. Whatever and whenever I publish from MQTT fx I successfully see the messages in the MQTT fx upon subscription. I had also set up confleunt MongoDB source connector and it works seamlessly.

But my problem is - the messages published on MQTT topic are available on the mapped kafka topic in an intermittent manner. What could be the reason? I do not see any error messages in kafka connect logs. Are there any connection related properties with respect to MQTT broker that I need to specify in my MQTT source properties file? Are there any properties to be included for sure in Rabbit MQ broker? Has anyone used Lenses MQTT source and sink connectors and would like to suggest anything about them?