问:
How do I capture a tap on a custom card view in a ZStack?
I'm trying pretty hard to recreate something like the Wallet view, but cannot really figure it out. I've hard-coded offsets into my ZStack, but of course I want to avoid that too. It seems like the offsets are keeping the taps from registering at all. Here is my code so far, tapping a card should change its title's colour between white and yellow.

Eventually, of course, I want to add animations to the stack of cards and be able to "pull" one from it place to make it the primary view. But I have to figure out how to catch the taps first...

I used this video as a base, but it doesn't really go as far as I'd like:

https://nsscreencast.com/episodes/399-swiftui-transforms-and-animations

```<code>import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
                ZStack {
                    CardView(title: "adidas", color: .blue, offset: 0.0)
                    CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                    CardView(title: " Card", color: .black, offset: 180.0)
                    CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
        }) {
            ZStack {
                 Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }

            }.shadow(radius: 2.0)
            .offset(x: 0, y: offset)

            }.onTapGesture {
            print("Tapped: \(self.title)")
        }
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}
</code>```

答:
struct ContentView: View {
    var body: some View {

        ScrollView (.vertical) {
            ZStack(alignment: .top) {
                CardView(title: "adidas", color: .blue, paddingOffset: 0)
                CardView(title: "Le Crueset", color: .pink, paddingOffset: 90)
                CardView(title: " Card", color: .black, paddingOffset: 180)
                CardView(title: "Sandusk", color: .orange, paddingOffset: 270)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    var paddingOffset: CGFloat

    var body: some View {
        ZStack {
            Rectangle()
                .fill(color)
            VStack {
                Text(title)
                    .font(.largeTitle)
                    .bold()
                    .foregroundColor(isYellow ? .yellow : .white)
                    .padding()
                Spacer()
            }

        }.shadow(radius: 2.0)
            .cornerRadius(10)
            .frame(width: 320, height: 210)
            .padding(.top, paddingOffset)
            .onTapGesture {
                self.isYellow.toggle()
                print("Tapped: \(self.title)")
        }
    }
}

```

Body:
I'm trying pretty hard to recreate something like the Wallet view, but cannot really figure it out. I've hard-coded offsets into my ZStack, but of course I want to avoid that too. It seems like the offsets are keeping the taps from registering at all. Here is my code so far, tapping a card should change its title's colour between white and yellow.

Eventually, of course, I want to add animations to the stack of cards and be able to "pull" one from it place to make it the primary view. But I have to figure out how to catch the taps first...

I used this video as a base, but it doesn't really go as far as I'd like:

https://nsscreencast.com/episodes/399-swiftui-transforms-and-animations

import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
                ZStack {
                    CardView(title: "adidas", color: .blue, offset: 0.0)
                    CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                    CardView(title: " Card", color: .black, offset: 180.0)
                    CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
        }) {
            ZStack {
                 Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }

            }.shadow(radius: 2.0)
            .offset(x: 0, y: offset)

            }.onTapGesture {
            print("Tapped: \(self.title)")
        }
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}


来源: stackexchange

问:
How to change colours of a group bar plot?
i am fairly new to R and I am having trouble changing the colours of a grouped bar plot. My code that I have inputted is the following:

```<code>library(plotly)
Samples <- c("1" , "2" , "P3")
D0 <- c(5.55, 5.605, 5.414)
D28 <- c(5.642, 1.658, 5.551)
data <- data.frame(Samples, D0, D28)
p <- plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0') %>%
  add_trace(y = ~D28, name = 'D28') %>%
  layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')
p
</code>```

this is the resulting graph. i am interested in just changing the colour of the blue and the colour of the orange and to keep the same format they are coloured in (first bar plot=one colour and second bar plot=another colour). I have tried a different code but this results in all of them getting coloured with the same colour. Does anyone know which code to use to get what I want? Thanks in advance!

答:
You can use the marker option in plotly to have your custom color for each plots:

Below is the modified code:

```<code>library(plotly)
Samples <- c("1" , "2" , "P3")
D0 <- c(5.55, 5.605, 5.414)
D28 <- c(5.642, 1.658, 5.551)
data <- data.frame(Samples, D0, D28)
p <- plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0',marker = list(color=c('green'))) %>%
  add_trace(y = ~D28, name = 'D28',marker = list(color=c('red'))) %>%
  layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')

p
</code>```

Output:

ContentLicense: CC BY-SA 4.0

Body:
i am fairly new to R and I am having trouble changing the colours of a grouped bar plot. My code that I have inputted is the following:

library(plotly)
Samples <- c("1" , "2" , "P3")
D0 <- c(5.55, 5.605, 5.414)
D28 <- c(5.642, 1.658, 5.551)
data <- data.frame(Samples, D0, D28)
p <- plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0') %>%
  add_trace(y = ~D28, name = 'D28') %>%
  layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')
p

this is the resulting graph. i am interested in just changing the colour of the blue and the colour of the orange and to keep the same format they are coloured in (first bar plot=one colour and second bar plot=another colour). I have tried a different code but this results in all of them getting coloured with the same colour. Does anyone know which code to use to get what I want? Thanks in advance!

Body:
You can use the marker option in plotly to have your custom color for each plots:

Below is the modified code:

library(plotly)
Samples <- c("1" , "2" , "P3")
D0 <- c(5.55, 5.605, 5.414)
D28 <- c(5.642, 1.658, 5.551)
data <- data.frame(Samples, D0, D28)
p <- plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0',marker = list(color=c('green'))) %>%
  add_trace(y = ~D28, name = 'D28',marker = list(color=c('red'))) %>%
  layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')

p

Output:


问:
How to translate callbacks to kotlin
I need to make this request with Kotlin:

```<code>One one = One.getInstance(getApplicationContext());
one.sendInteraction("/interactionName", new GetCallback<ResponseObject>() {

    public void done(ResponseObject response, ThunderheadException e) {
        if (e == null) {
             // Success!
            one.processResponse(response);
        } else {
            // Failure!
        }
    }
});
</code>```

When I try to convert on Android Studio translator the code not fit well. I am a newbie with Kotlin, I tried some ways but always fail.
My problem it's with callback method

```<code>new GetCallback<ResponseObject>() { public void done(ResponseObject response, ThunderHeadException e){...}}`
</code>```

Could you help me to find the way to do it in Kotlin?

答:
Usually, you implement the interface using the object keyword. It might look something like this:

```<code>one.sendInteraction("/interactionName", object : GetCallback<ResponseObject> {
    // ...
})
</code>```

Then follow the autocomplete instructions from IntelliJ to override the functions.

Title: How to translate callbacks to kotlin

Body:
I need to make this request with Kotlin:

One one = One.getInstance(getApplicationContext());
one.sendInteraction("/interactionName", new GetCallback<ResponseObject>() {

    public void done(ResponseObject response, ThunderheadException e) {
        if (e == null) {
             // Success!
            one.processResponse(response);
        } else {
            // Failure!
        }
    }
});

When I try to convert on Android Studio translator the code not fit well. I am a newbie with Kotlin, I tried some ways but always fail.
My problem it's with callback method

new GetCallback<ResponseObject>() { public void done(ResponseObject response, ThunderHeadException e){...}}`

Could you help me to find the way to do it in Kotlin?

Body:
Usually, you implement the interface using the object keyword. It might look something like this:

one.sendInteraction("/interactionName", object : GetCallback<ResponseObject> {
    // ...
})

Then follow the autocomplete instructions from IntelliJ to override the functions.


问:
Url Rewrite for hosted application on IIS
I have developed asp.net mvc core 3.0 web application and deployed in windows server. I would like to hide controller name in url.

Example :

orginal url  : www.example.com/test/authenticate/login

expected url : www.example.com/test/login

Im not sure about it by achieve it code or IIS.

startup.cs route code.

```<code>app.UseEndpoints(endpoints =>
{
       endpoints.MapControllerRoute(
           name: "default",
           pattern: "{controller=Home}/{action=Index}/{id?}");

});
</code>```

答:
Use Attribute routing:</p>

```<code>[Route("/")]
public class AuthenticateController : ControllerBase
{
    [HttpGet("login")]
    public IActionResult Get()
    {
        return Ok("Ok");
    }
}
</code>```

Body:
I have developed asp.net mvc core 3.0 web application and deployed in windows server. I would like to hide controller name in url.

Example :

orginal url  : www.example.com/test/authenticate/login

expected url : www.example.com/test/login

Im not sure about it by achieve it code or IIS.

startup.cs route code.

app.UseEndpoints(endpoints =>
{
       endpoints.MapControllerRoute(
           name: "default",
           pattern: "{controller=Home}/{action=Index}/{id?}");

});

Body:
Use Attribute routing:

[Route("/")]
public class AuthenticateController : ControllerBase
{
    [HttpGet("login")]
    public IActionResult Get()
    {
        return Ok("Ok");
    }
}


问:
Error 6 Initializing SQL*Plus
When i open sqlplus it shows</p>

```<code>Error 6 Initializing SQL*Plus
Message file sp1<Lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
</code>```

答:
Generally speaking, you don't want to set ORACLE_HOME in a Windows environment - it's handled in the registry, and it's given me grief the times I've set it. Here is an Oracle Doc on Oracle Homes.

How many Oracle installations are on this computer?

ContentLicense: CC BY-SA 3.0

Title: Error 6 Initializing SQL*Plus

Body:
When i open sqlplus it shows

Error 6 Initializing SQL*Plus
Message file sp1<Lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory


问:
start etcd failed by "bind: cannot assign requested address"
i run etcd as docker container ,and 10.132.41.234 is my host ip which i run docker container on ,and i get error info like this ,i do not know if it is right and i do now familiar with etcd,some one can help? thx!</p>

```<code>2017-09-13 08:55:03.339612 I | etcdmain: etcd Version: 3.0.17
2017-09-13 08:55:03.339891 I | etcdmain: Git SHA: cc198e2
2017-09-13 08:55:03.339902 I | etcdmain: Go Version: go1.6.4
2017-09-13 08:55:03.339912 I | etcdmain: Go OS/Arch: linux/amd64
2017-09-13 08:55:03.339921 I | etcdmain: setting maximum number of CPUs to 2, total number of available CPUs is 2
2017-09-13 08:55:03.340059 I | etcdmain: peerTLS: cert = /etc/ssl/certs/server.pem, key = /etc/ssl/certs/server-key.pem, ca = , trusted-ca = /etc/ssl/certs/ca.pem, client-cert-auth = true
2017-09-13 08:55:03.342794 I | etcdmain: listening for peers on https://127.0.0.1:2380
2017-09-13 08:55:03.342844 I | etcdmain: clientTLS: cert = /etc/ssl/certs/server.pem, key = /etc/ssl/certs/server-key.pem, ca = , trusted-ca = /etc/ssl/certs/ca.pem, client-cert-auth = true
2017-09-13 08:55:03.345340 I | etcdmain: stopping listening for peers on https://127.0.0.1:2380
2017-09-13 08:55:03.345386 C | etcdmain: listen tcp 10.132.41.234:2379: bind: cannot assign requested address

 docker run -d -v /opt/certs:/etc/ssl/certs -v /opt/etcd-data:/etcd-data -p 2380:2380 -p 2379:2379 \
 --name etcd gcr.io/google_containers/etcd-amd64:3.0.17 \
  /usr/local/bin/etcd \
 --name etcd0 \
 --data-dir=/etcd-data \
 --advertise-client-urls https://10.132.41.234:2379,https://127.0.0.1:2379 \
 --listen-client-urls https://10.132.41.234:2379,https://127.0.0.1:2379 \
 --initial-advertise-peer-urls https://127.0.0.1:2380 \
 --listen-peer-urls https://127.0.0.1:2380 \
 --initial-cluster-token etcd-cluster-1 \
 --initial-cluster etcd0=https://127.0.0.1:2380,etcd1=https://127.0.0.1:2380,etcd2=https://127.0.0.1:2380 \
 --initial-cluster-state new \
 --cert-file=/etc/ssl/certs/server.pem \
 --key-file=/etc/ssl/certs/server-key.pem \
 --peer-cert-file=/etc/ssl/certs/server.pem \
 --peer-key-file=/etc/ssl/certs/server-key.pem \
 --trusted-ca-file=/etc/ssl/certs/ca.pem \
 --peer-trusted-ca-file=/etc/ssl/certs/ca.pem \
 --peer-client-cert-auth=true \
 --client-cert-auth=true
</code>```

答:
If you follow the etcd guide, check if this point to the machine you are running the command on:

```<code>THIS_NAME=${NAME_4}
THIS_IP=${HOST_4}
</code>```

Replace 4 with the correct number.

Body:
i run etcd as docker container ,and 10.132.41.234 is my host ip which i run docker container on ,and i get error info like this ,i do not know if it is right and i do now familiar with etcd,some one can help? thx!

2017-09-13 08:55:03.339612 I | etcdmain: etcd Version: 3.0.17
2017-09-13 08:55:03.339891 I | etcdmain: Git SHA: cc198e2
2017-09-13 08:55:03.339902 I | etcdmain: Go Version: go1.6.4
2017-09-13 08:55:03.339912 I | etcdmain: Go OS/Arch: linux/amd64
2017-09-13 08:55:03.339921 I | etcdmain: setting maximum number of CPUs to 2, total number of available CPUs is 2
2017-09-13 08:55:03.340059 I | etcdmain: peerTLS: cert = /etc/ssl/certs/server.pem, key = /etc/ssl/certs/server-key.pem, ca = , trusted-ca = /etc/ssl/certs/ca.pem, client-cert-auth = true
2017-09-13 08:55:03.342794 I | etcdmain: listening for peers on https://127.0.0.1:2380
2017-09-13 08:55:03.342844 I | etcdmain: clientTLS: cert = /etc/ssl/certs/server.pem, key = /etc/ssl/certs/server-key.pem, ca = , trusted-ca = /etc/ssl/certs/ca.pem, client-cert-auth = true
2017-09-13 08:55:03.345340 I | etcdmain: stopping listening for peers on https://127.0.0.1:2380
2017-09-13 08:55:03.345386 C | etcdmain: listen tcp 10.132.41.234:2379: bind: cannot assign requested address

 docker run -d -v /opt/certs:/etc/ssl/certs -v /opt/etcd-data:/etcd-data -p 2380:2380 -p 2379:2379 \
 --name etcd gcr.io/google_containers/etcd-amd64:3.0.17 \
  /usr/local/bin/etcd \
 --name etcd0 \
 --data-dir=/etcd-data \
 --advertise-client-urls https://10.132.41.234:2379,https://127.0.0.1:2379 \
 --listen-client-urls https://10.132.41.234:2379,https://127.0.0.1:2379 \
 --initial-advertise-peer-urls https://127.0.0.1:2380 \
 --listen-peer-urls https://127.0.0.1:2380 \
 --initial-cluster-token etcd-cluster-1 \
 --initial-cluster etcd0=https://127.0.0.1:2380,etcd1=https://127.0.0.1:2380,etcd2=https://127.0.0.1:2380 \
 --initial-cluster-state new \
 --cert-file=/etc/ssl/certs/server.pem \
 --key-file=/etc/ssl/certs/server-key.pem \
 --peer-cert-file=/etc/ssl/certs/server.pem \
 --peer-key-file=/etc/ssl/certs/server-key.pem \
 --trusted-ca-file=/etc/ssl/certs/ca.pem \
 --peer-trusted-ca-file=/etc/ssl/certs/ca.pem \
 --peer-client-cert-auth=true \
 --client-cert-auth=true

Body:
If you follow the etcd guide, check if this point to the machine you are running the command on:

THIS_NAME=${NAME_4}
THIS_IP=${HOST_4}

Replace 4 with the correct number.


问:
How to dismiss keyboard when user tap other area outside textfield?
today I tried to run my code on my iPod (iOS 6.1.3) and I found something interesting here...

first, when I tap on textfield the keyboard shows up but it won't hide when I tap somewhere else outside textfield.

so I decided to Googling and found this solution :

```<code>_fieldEmail.delegate = self;
_fieldEmail.returnKeyType = UIReturnKeyDone;

_fieldPassword.delegate = self;
_fieldPassword.returnKeyType = UIReturnKeyDone;

_fieldRegisterName.delegate = self;
_fieldRegisterName.returnKeyType = UIReturnKeyDone;

_fieldRegisterEmail.delegate = self;
_fieldRegisterEmail.returnKeyType = UIReturnKeyDone;

_fieldRegisterPassword.delegate = self;
_fieldRegisterPassword.returnKeyType = UIReturnKeyDone;
</code>```

it works... it gives a 'DONE' button on the bottom of keyboard and now the keyboard can be hidden by pressing it.

but I have 2 problems here :

the keyboard only hide when 'DONE' button is tapped. not by tapping other area outside text field. I don't know if this normal on iOS world, but usually I see lot of apps don't act like this.

is there any way to loop this process so I don't have manually add that delegate one by one of all textfield that I have? how to do that?

that's all I need to know

答:
If you're using scroll view (or table view) controller, add these lines there:</p>

```<code>    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
</code>```

Body:
today I tried to run my code on my iPod (iOS 6.1.3) and I found something interesting here...

first, when I tap on textfield the keyboard shows up but it won't hide when I tap somewhere else outside textfield.

so I decided to Googling and found this solution :

_fieldEmail.delegate = self;
_fieldEmail.returnKeyType = UIReturnKeyDone;

_fieldPassword.delegate = self;
_fieldPassword.returnKeyType = UIReturnKeyDone;

_fieldRegisterName.delegate = self;
_fieldRegisterName.returnKeyType = UIReturnKeyDone;

_fieldRegisterEmail.delegate = self;
_fieldRegisterEmail.returnKeyType = UIReturnKeyDone;

_fieldRegisterPassword.delegate = self;
_fieldRegisterPassword.returnKeyType = UIReturnKeyDone;

it works... it gives a 'DONE' button on the bottom of keyboard and now the keyboard can be hidden by pressing it.

but I have 2 problems here :

the keyboard only hide when 'DONE' button is tapped. not by tapping other area outside text field. I don't know if this normal on iOS world, but usually I see lot of apps don't act like this.

is there any way to loop this process so I don't have manually add that delegate one by one of all textfield that I have? how to do that?

that's all I need to know

Body:
If you're using scroll view (or table view) controller, add these lines there:

    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }


问:
Extract common methods from Gradle build script
I have a Gradle build script (build.gradle), in which I created some tasks. These tasks consist mostly of method calls. The called methods are also in the build script.

Now, here's the situation:

I am creating a fair amount of build scripts, which contain different tasks, but utilise the same methods from the original script. Thus, I would like to extract these "common methods" in some way, so I can easily re-use them instead of copying them for each new script I create.

If Gradle were PHP, something like the following would be ideal:

```<code>//script content
...
require("common-methods.gradle");
...
//more script content
</code>```

But of course, that isn't possible. Or is it?

Anyway, how can I achieve this result? What is the best possible method to do this?   I've read through the Gradle documentation already, but I can't seem to determine which method will be the easiest and best suited for this.

UPDATE:

I've managed to extract the methods in another file

(using apply from: 'common-methods.gradle'),

so the structure is as follows:

```<code>parent/
      /build.gradle              // The original build script
      /common-methods.gradle     // The extracted methods
      /gradle.properties         // Properties used by the build script
</code>```

After executing a task from build.gradle, I've bumped into a new problem: apparently, methods don't get recognized when they're in common-methods.gradle.

How can that be fixed?

答:
Another approach for Kotlin DSL could be:

my-plugin.gradle.kts

extra["sum"] = { x: Int, y: Int -> x + y }
```
<p><strong>settings.gradle.kts</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T

apply("my-plugin.gradle.kts")

val sum = uncheckedCast<(Int, Int) -> Int>(extra["sum"])

println(sum(1, 2))
</code>```

Body:
I have a Gradle build script (build.gradle), in which I created some tasks. These tasks consist mostly of method calls. The called methods are also in the build script.

Now, here's the situation:

I am creating a fair amount of build scripts, which contain different tasks, but utilise the same methods from the original script. Thus, I would like to extract these "common methods" in some way, so I can easily re-use them instead of copying them for each new script I create.

If Gradle were PHP, something like the following would be ideal:

//script content
...
require("common-methods.gradle");
...
//more script content

But of course, that isn't possible. Or is it?

Anyway, how can I achieve this result? What is the best possible method to do this?   I've read through the Gradle documentation already, but I can't seem to determine which method will be the easiest and best suited for this.

UPDATE:

I've managed to extract the methods in another file

(using apply from: 'common-methods.gradle'),

so the structure is as follows:

parent/
      /build.gradle              // The original build script
      /common-methods.gradle     // The extracted methods
      /gradle.properties         // Properties used by the build script

After executing a task from build.gradle, I've bumped into a new problem: apparently, methods don't get recognized when they're in common-methods.gradle.

How can that be fixed?

Body:
Another approach for Kotlin DSL could be:

my-plugin.gradle.kts

extra["sum"] = { x: Int, y: Int -> x + y }

settings.gradle.kts

@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T

apply("my-plugin.gradle.kts")

val sum = uncheckedCast<(Int, Int) -> Int>(extra["sum"])

println(sum(1, 2))


问:
why doesn't this function return a value?
Learning javascript, I am trying understand why the following function doesn't return true or false. When I step through the code with debugger I see that it steps into either return true or return false case.

```<code>doesNumExistInArray = (objArray, num) => {
    Object.keys(objArray).forEach(key => {
      if (objArray[key].number === parseInt(num)) {
        return true;
      } else {
        return false;
      }
    });
  };
</code>```

But calling isDuplicate = doesNumExistInArray(objects, num) always assigns isDuplicate undefined. What am I missing?

答:
You should be using Array.prototype.some.

If at any point, there is a match, the function will return true.

The Array.prototype.forEach method returns undefined, so this will not work as a returable function.

doesNumExistInArray = (objArray, num) => {
  return Object.keys(objArray).some(key => {
    return objArray[key].number === parseInt(num);
  });
};```

Body:
Learning javascript, I am trying understand why the following function doesn't return true or false. When I step through the code with debugger I see that it steps into either return true or return false case.

doesNumExistInArray = (objArray, num) => {
    Object.keys(objArray).forEach(key => {
      if (objArray[key].number === parseInt(num)) {
        return true;
      } else {
        return false;
      }
    });
  };

But calling isDuplicate = doesNumExistInArray(objects, num) always assigns isDuplicate undefined. What am I missing?


问:
How can I have a single goroutine function that waits for values from multiple others?
I've created a Go playground sample that illustrates what I'm talking about.

In the example, I create one goroutine, func2, which I would simply like to wait for inputs through its channel and print the value once it arrives.

```<code>func func2(ch chan int) {
    fmt.Println("func2")
    v:=<-ch
    fmt.Println(v)
}
</code>```

Then, in a loop, I create goroutines for another function, and these are part of a WaitGroup.

```<code>func func1(ch chan int, wg *sync.WaitGroup) {
    fmt.Println("func1")
    ch <- 11032
    wg.Done()
}
</code>```

And in main, I wait for the WaitGroup. I'm running into a deadlock and I'm not sure how to fix it. Just so it's clear what I'm trying to achieve, I want func2 to stay open as a thread once I call it, to process n values, where n is the number of goroutines I call for func1. I considered using a WaitGroup Wait inside of func2, but I don't want it blocking, as it needs to process new data from func1 as it's sent.

答:
What you are looking for is a clean way to close the channels when all the values have finished streaming through. When new values come in, you may create a new channel and start streaming values on this. This is the way I do it, maybe it helps</p>

```<code>var wg sync.WaitGroup

toUpdate := make(chan *someType, BufferSize)

for i := 0; i < BufferSize; i++ {
    go processEvents(toUpdate, &wg)
}

// // wait till all the checks have come back
go func(toUpdate chan * someType, group *sync.WaitGroup) {
    group.Wait()
    close(toCreate)
}(toCreate, toUpdate, &wg)
</code>```

Body:
I've created a Go playground sample that illustrates what I'm talking about.

In the example, I create one goroutine, func2, which I would simply like to wait for inputs through its channel and print the value once it arrives.

func func2(ch chan int) {
    fmt.Println("func2")
    v:=<-ch
    fmt.Println(v)
}

Then, in a loop, I create goroutines for another function, and these are part of a WaitGroup.

func func1(ch chan int, wg *sync.WaitGroup) {
    fmt.Println("func1")
    ch <- 11032
    wg.Done()
}

And in main, I wait for the WaitGroup. I'm running into a deadlock and I'm not sure how to fix it. Just so it's clear what I'm trying to achieve, I want func2 to stay open as a thread once I call it, to process n values, where n is the number of goroutines I call for func1. I considered using a WaitGroup Wait inside of func2, but I don't want it blocking, as it needs to process new data from func1 as it's sent.

Body:
What you are looking for is a clean way to close the channels when all the values have finished streaming through. When new values come in, you may create a new channel and start streaming values on this. This is the way I do it, maybe it helps

var wg sync.WaitGroup

toUpdate := make(chan *someType, BufferSize)

for i := 0; i < BufferSize; i++ {
    go processEvents(toUpdate, &wg)
}

// // wait till all the checks have come back
go func(toUpdate chan * someType, group *sync.WaitGroup) {
    group.Wait()
    close(toCreate)
}(toCreate, toUpdate, &wg)


问:
Is it more efficient to separate code that doesn't need to be run as often from the main game loop in another loop in Javascript?
I'm creating my first Javascript game, and I want the game to continuously make a check for something as the game goes on. The check is somewhat costly, and the main game loop runs every 25 miliseconds, so I'd rather it not be in the game loop. I was thinking about separating that check in a function that will be called by a setInterval() every second. I would think this would make my code more efficient, right?

This is what the main loop looks like:

```<code>var gameLoop = new CustomEvent("gameLoop")
function main() {
    document.dispatchEvent(gameLoop)
}
setInterval(main, 25)
</code>```

So basically, I could either do this:

```<code>function check() {
      //Check code here
    }
}
setInterval(check, 1000)
</code>```

Or:

```<code>document.addEventListener("gameLoop", function() {
    //check code here
})```

```

答:
Yes, that is a clean way to separate the high frequency events from the low frequency events.

To mix in other intervals like 50 ms or 75 ms you can also add a global variable like tick_count_25 and use the mod operator in the 25 ms function.

outside of function

```<code>var tick_count_25 = 0;
</code>```

inside of function

```<code>tick_count_25++;
....
if ((tick_count_25 % 3) == 0)  // every 75 ms
{
      ... some function that only needs to run once every 3 ticks
}
</code>```

That lets you avoid creating 20 interrupts and keeps your game loop logic in 1-2 places instead of many.

It also lets you set delayed triggers, say if you want something to happen 20 ticks from now, though you can also do that by adding more global counters that persist outside of the interrupt.

Body:
I'm creating my first Javascript game, and I want the game to continuously make a check for something as the game goes on. The check is somewhat costly, and the main game loop runs every 25 miliseconds, so I'd rather it not be in the game loop. I was thinking about separating that check in a function that will be called by a setInterval() every second. I would think this would make my code more efficient, right?

This is what the main loop looks like:

var gameLoop = new CustomEvent("gameLoop")
function main() {
    document.dispatchEvent(gameLoop)
}
setInterval(main, 25)

So basically, I could either do this:

function check() {
      //Check code here
    }
}
setInterval(check, 1000)

Or:

document.addEventListener("gameLoop", function() {
    //check code here
})```

Body:
Yes, that is a clean way to separate the high frequency events from the low frequency events.

To mix in other intervals like 50 ms or 75 ms you can also add a global variable like tick_count_25 and use the mod operator in the 25 ms function.

outside of function

var tick_count_25 = 0;

inside of function

tick_count_25++;
....
if ((tick_count_25 % 3) == 0)  // every 75 ms
{
      ... some function that only needs to run once every 3 ticks
}

That lets you avoid creating 20 interrupts and keeps your game loop logic in 1-2 places instead of many.

It also lets you set delayed triggers, say if you want something to happen 20 ticks from now, though you can also do that by adding more global counters that persist outside of the interrupt.


问:
vuejs - cached data used with different url
I have built a profile vue page but I realized that when I change URL parameter it does not load new user but displays the first user. I load data in created which is probably the cause. How can I tell the page that it has a different parameter and it shall reload?

router.js

```<code>export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/profile/:id',
      name: 'user-profile',
      component: () => import('./views/Profile.vue'),
      props: true,
    },
</code>```

Profile.vue

```<code>async created() {
  const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id: this.id });
  this.userProfile = response.data.data;
</code>```

URLs:

http://localhost:8080/profile/1dvklq9cnz

http://localhost:8080/profile/1e0tcb2kn2

答:
The created hook only gets executed when the component is actually created.  changing the url to load the same route, but with a different ID is a routeUpdate instead.

Remember that params or query changes won't trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard.

  https://router.vuejs.org/guide/advanced/navigation-guards.html

Abstract out the fetch & set that you have in your created hook.  Then, call it in both created() and beforeRouteUpdate().

```<code>{
methods: {
    async getProfile(id) {
        const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id});
        this.userProfile = response.data.data;
    }
    created() { this.getProfile(this.id); },
    beforeRouteUpdate(to, from, next) {
        const { params: {id} } = to;
        this.getProfile(id);
        next();
    }
}
</code>```

Body:
I have built a profile vue page but I realized that when I change URL parameter it does not load new user but displays the first user. I load data in created which is probably the cause. How can I tell the page that it has a different parameter and it shall reload?

router.js

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/profile/:id',
      name: 'user-profile',
      component: () => import('./views/Profile.vue'),
      props: true,
    },

Profile.vue

async created() {
  const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id: this.id });
  this.userProfile = response.data.data;

URLs:

http://localhost:8080/profile/1dvklq9cnz

http://localhost:8080/profile/1e0tcb2kn2

Body:
The created hook only gets executed when the component is actually created.  changing the url to load the same route, but with a different ID is a routeUpdate instead.

Remember that params or query changes won't trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard.

  https://router.vuejs.org/guide/advanced/navigation-guards.html

Abstract out the fetch & set that you have in your created hook.  Then, call it in both created() and beforeRouteUpdate().

{
methods: {
    async getProfile(id) {
        const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id});
        this.userProfile = response.data.data;
    }
    created() { this.getProfile(this.id); },
    beforeRouteUpdate(to, from, next) {
        const { params: {id} } = to;
        this.getProfile(id);
        next();
    }
}


问:
cmake, linux: build directory given as symbolic link does not work: why?
I have setup with build directory set to ./bin within source root.
Everything works until I change ./bin to symbolic link.
Then everything configures correctly but make starts complaining about not found source files:

```<code>make[2]: *** No rule to make target '../cpp/foo.cpp', needed by 'CMakeFiles/mylib.dir/cpp/foo.cpp.o'.
</code>```

Why it happens and what could I do about it?
I had idea to convert this path to absolute (inside makefile) and dump it to console in order to figure-out where it points to but it turned out that this "build.cmake" is recreated automatically at every make invocation :(

答: Thanks to Tsyvarev I realized that it is unmovable OS constraint with potential workaround using mount bind

Body:
I have setup with build directory set to ./bin within source root.
Everything works until I change ./bin to symbolic link.
Then everything configures correctly but make starts complaining about not found source files:

make[2]: *** No rule to make target '../cpp/foo.cpp', needed by 'CMakeFiles/mylib.dir/cpp/foo.cpp.o'.

Why it happens and what could I do about it?
I had idea to convert this path to absolute (inside makefile) and dump it to console in order to figure-out where it points to but it turned out that this "build.cmake" is recreated automatically at every make invocation :(


问:
How to integrate ibm watson chatbot with slack , using only OAuth access token
When I was trying to connect my IBM Watson chatbot to slack, I noticed that slack has optimized their App options for connection and integration, where they generate only 'Bot User OAuth Access Token'.
But IBM Watson slack integration process still asking in the second step: both: OAuth access token and User OAuth Access Token.
I tried to use the same token but doesn't work, I get my chatbot app on my slack workspace but no interaction.

My question is: how can I integrate my IBM Watson to slack with this new changes?

答: Have you thought about using a different system to Watson? I had a Bot powered by it but jumped shipped when it became difficult to use OAuth.</p>


问:
Remove charset in Content-Type header
In what way the charset for the Content-Type response be removed?

```<code>Content-Type: text/plain;charset=iso-8859-1
</code>```

The nginx.conf file is already set to

```<code>http {
   sendfile on;
   tcp_nopush on;
   tcp_nodelay on;
   keepalive_timeout 65;
   types_hash_max_size 2048;
   charset off;

   server {
          listen 80;
          server_name ~. "";
          location / {
                 proxy_pass http://localhost:8080;
                 proxy_set_header X-Forwarded-Host $host:$server_port;
                 proxy_set_header X-Forwarded-Server $host;
                 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                 proxy_set_header Host $host;
          }
   }
}
</code>```

Is there a way to force remove the charset?

答:
Can you try this:</p>

```<code>    map $upstream_http_content_type $stripped_content_type {
        "~^(.+);charset="  $1;
        default            $upstream_http_content_type;
    }

    server {
        ...
        location / {
            ...
            proxy_hide_header Content-Type;
            add_header Content-Type $stripped_content_type;
        }
    }
</code>```

Title: Remove charset in Content-Type header

Body:
In what way the charset for the Content-Type response be removed?

Content-Type: text/plain;charset=iso-8859-1

The nginx.conf file is already set to

http {
   sendfile on;
   tcp_nopush on;
   tcp_nodelay on;
   keepalive_timeout 65;
   types_hash_max_size 2048;
   charset off;

   server {
          listen 80;
          server_name ~. "";
          location / {
                 proxy_pass http://localhost:8080;
                 proxy_set_header X-Forwarded-Host $host:$server_port;
                 proxy_set_header X-Forwarded-Server $host;
                 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                 proxy_set_header Host $host;
          }
   }
}

Is there a way to force remove the charset?

Body:
Can you try this:

    map $upstream_http_content_type $stripped_content_type {
        "~^(.+);charset="  $1;
        default            $upstream_http_content_type;
    }

    server {
        ...
        location / {
            ...
            proxy_hide_header Content-Type;
            add_header Content-Type $stripped_content_type;
        }
    }


问:
Get Parent Code based on Parent Tag all in one query
We need to get the Parent CODE based on the Parent TAG from a result set similar to below all in one query or one query with subquery. The TAG field gets added by multiples of 3 (e.g. AAA, AAAAAA, AAAAAB and so one). So the Parent TAG is always the length of the Childs TAG - 3).
We thought maybe a subquery like below but it is returning NULL for every record.

```<code>Select [Level], [Code], [TAG], LEFT([TAG], LEN([TAG]) -3) AS [Parent TAG], [Parent Code] = CASE WHEN [LEVEL] = 1 THEN NULL ELSE (SELECT [CODE] FROM [MyTable] WHERE [TAG] = LEFT([TAG], LEN([TAG]) -3) END)
FROM [MyTable]
</code>```

Or:

```<code>Select [Level], [Code], [TAG], LEFT([TAG], LEN([TAG]) -3) AS [Parent TAG], [Parent Code] = CASE WHEN [LEVEL] = 1 THEN NULL ELSE (SELECT [CODE] FROM [MyTable] WHERE [TAG] = [Parent Tag] END)
FROM [MyTable]
</code>```

Data:

```<code>|Level|Code |Tag      |Parent Tag|Parent Code|
|     |     |         |          |           |
| 1   |1.0  |AAA      |          |           |
| 2   |1.1  |AAAAAA   |AAA       |           |
| 3   |1.1.1|AAAAAAAAA|AAAAAA    |           |
| 2   |1.2  |AAAAAB   |AAA       |           |
| 3   |1.1.2|AAAAAAAAB|AAAAAB    |           |
| 2   |1.3  |AAAAAC   |AAA       |           |
| 3   |1.3.1|AAAAACAAA|AAAAAC    |           |
</code>```

So the first Level 2 record Parent Code would be 1.0, first level 3 record Parent Code would be 1.1.1 and so on...

Any suggestions would be appreciated.

答:
You can self-join the table:

```<code>select
    t.*,
    p.code
from mytable t
left join mytable p on p.tag = t.parent_tag
</code>```

It is important to use left join here, so records without a parent are not evicted from the resultset (unless you do want to do so).

If the same tag may appear on different levels, you can make the join condition more specific:

```<code>select
    t.*,
    p.code
from mytable t
left join mytable p on p.tag = t.parent_tag and p.level = t.level - 1
</code>```

Body:
We need to get the Parent CODE based on the Parent TAG from a result set similar to below all in one query or one query with subquery. The TAG field gets added by multiples of 3 (e.g. AAA, AAAAAA, AAAAAB and so one). So the Parent TAG is always the length of the Childs TAG - 3).
We thought maybe a subquery like below but it is returning NULL for every record.

Select [Level], [Code], [TAG], LEFT([TAG], LEN([TAG]) -3) AS [Parent TAG], [Parent Code] = CASE WHEN [LEVEL] = 1 THEN NULL ELSE (SELECT [CODE] FROM [MyTable] WHERE [TAG] = LEFT([TAG], LEN([TAG]) -3) END)
FROM [MyTable]

Or:

Select [Level], [Code], [TAG], LEFT([TAG], LEN([TAG]) -3) AS [Parent TAG], [Parent Code] = CASE WHEN [LEVEL] = 1 THEN NULL ELSE (SELECT [CODE] FROM [MyTable] WHERE [TAG] = [Parent Tag] END)
FROM [MyTable]

Data:

|Level|Code |Tag      |Parent Tag|Parent Code|
|     |     |         |          |           |
| 1   |1.0  |AAA      |          |           |
| 2   |1.1  |AAAAAA   |AAA       |           |
| 3   |1.1.1|AAAAAAAAA|AAAAAA    |           |
| 2   |1.2  |AAAAAB   |AAA       |           |
| 3   |1.1.2|AAAAAAAAB|AAAAAB    |           |
| 2   |1.3  |AAAAAC   |AAA       |           |
| 3   |1.3.1|AAAAACAAA|AAAAAC    |           |

So the first Level 2 record Parent Code would be 1.0, first level 3 record Parent Code would be 1.1.1 and so on...

Any suggestions would be appreciated.

Body:
You can self-join the table:

select
    t.*,
    p.code
from mytable t
left join mytable p on p.tag = t.parent_tag

It is important to use left join here, so records without a parent are not evicted from the resultset (unless you do want to do so).

If the same tag may appear on different levels, you can make the join condition more specific:

select
    t.*,
    p.code
from mytable t
left join mytable p on p.tag = t.parent_tag and p.level = t.level - 1


问:
Perform different actions on button up and down
Ok. I've been digging around trying to find a way to capture button up and down actions. I'm not even sure what the proper terminology in Xcode for this would be. It's pretty easy in MS Visual, but I can't seem to find how to do this with Xcode.

Essentially, I want to fire an action when the button is pressed down and held, and then another when the button is released.

I'm not really sure how to go about this. Any hints, or pointers in the right direction would be greatly appreciated!

答: You didn't specify, so I'm going to assume this is for the Mac and not iOS. You should read the NSResponder documentation. You can do exactly what you want with that.


问:
How to concatenate two unique arrays and remove 'nan'?
Using the Pokemon Dataset, I want to extract all the unique types in columns: "Type 1" & "Type 2" and print them out after. So far, I've been able to concatenate the unique values from both columns together into an array. Now I'm having trouble removing 'nan' from the array.

My code:

```<code>import pandas as pd
import numpy as np
df = pd.read_csv("/Users/edwinandrew/Documents/Datasets/Pokemon.csv")
type_class1 = df['Type 1'].unique()
type_class2 = df['Type 2'].unique()
all_types = np.concatenate((type_class1, type_class2))
print(all_types)
</code>```

Output:

```<code>['Grass' 'Fire' 'Water' 'Bug' 'Normal' 'Poison' 'Electric' 'Ground'
 'Fairy' 'Fighting' 'Psychic' 'Rock' 'Ghost' 'Ice' 'Dragon' 'Dark' 'Steel'
 'Flying' 'Poison' nan 'Flying' 'Dragon' 'Ground' 'Fairy' 'Grass'
 'Fighting' 'Psychic' 'Steel' 'Ice' 'Rock' 'Dark' 'Water' 'Electric'
 'Fire' 'Ghost' 'Bug' 'Normal']
</code>```

I tried using x = x[~numpy.isnan(x)] to see if that would remove the nan value but I got an error. What would be the best way to solve this problem?

答:
stack + dropna

Create one Series, drop the missing values and call unique.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'Type_1': ['Grass', 'Fire', 'Steel', 'Ghost'],
                   'Type_2': [np.NaN, 'Water', 'Fire', 'Grass']})

df[['Type_1', 'Type_2']].stack().dropna().unique()
#array(['Grass', 'Fire', 'Water', 'Steel', 'Ghost'], dtype=object)
</code>```

Body:
Using the Pokemon Dataset, I want to extract all the unique types in columns: "Type 1" & "Type 2" and print them out after. So far, I've been able to concatenate the unique values from both columns together into an array. Now I'm having trouble removing 'nan' from the array.

My code:

import pandas as pd
import numpy as np
df = pd.read_csv("/Users/edwinandrew/Documents/Datasets/Pokemon.csv")
type_class1 = df['Type 1'].unique()
type_class2 = df['Type 2'].unique()
all_types = np.concatenate((type_class1, type_class2))
print(all_types)

Output:

['Grass' 'Fire' 'Water' 'Bug' 'Normal' 'Poison' 'Electric' 'Ground'
 'Fairy' 'Fighting' 'Psychic' 'Rock' 'Ghost' 'Ice' 'Dragon' 'Dark' 'Steel'
 'Flying' 'Poison' nan 'Flying' 'Dragon' 'Ground' 'Fairy' 'Grass'
 'Fighting' 'Psychic' 'Steel' 'Ice' 'Rock' 'Dark' 'Water' 'Electric'
 'Fire' 'Ghost' 'Bug' 'Normal']

I tried using x = x[~numpy.isnan(x)] to see if that would remove the nan value but I got an error. What would be the best way to solve this problem?

Body:
stack + dropna

Create one Series, drop the missing values and call unique.

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type_1': ['Grass', 'Fire', 'Steel', 'Ghost'],
                   'Type_2': [np.NaN, 'Water', 'Fire', 'Grass']})

df[['Type_1', 'Type_2']].stack().dropna().unique()
#array(['Grass', 'Fire', 'Water', 'Steel', 'Ghost'], dtype=object)


问:
Typescript Decorators before class instance
Iam playing around with Typescript decorators and everything is quite good working when I have instanciated a class.
With the following code, my Class-decorator gets called:
import { MyClass } from "./MyClass";
const myClass = new MyClass();

But when I dont instanciate the class explicit like in the example above, no decorators are called. For example, this module: https://github.com/xrobert35/es-mapping-ts relies on such a structure to save all classes in a storage and generate a mapping. I tried it without instanciating the classes first and generate a mapping, but it does not work either. Is there any Webpack or Typescript configuration that has to be set to get decorators executed before instanciating the classes where the decorators are placed? In my state of knowledge and in some online tutorials it is defined that class decorators are called when the class is defined and not when the class is instanciated.
Cheers!

答:
You can replace original class constructor with a class level decorator to do all kinds of cool stuff:

```<code>function example(target: any) {
    // save a reference to the original constructor
    const original = target;

    // the new constructor behaviour
    const f: any = function (...args: any[]) {
        console.log("Hook before original constructor...");

        const newArgs = [...args].reverse();

        const instance = new original(...newArgs);

        console.log("Hook after original constructor...");

        instance.d = 'ddd';

        return instance;
    }

    // copy prototype so intanceof operator still works
    f.prototype = original.prototype;

    // return new constructor (will override original)
    return f;
}

@example
class SomeClass {
    constructor(public a: number, public b: number, public c: number) {
        console.log("Hello from constructor!")
    }
}

const instance1 = new SomeClass(1, 2, 3);
console.log(instance1); // SomeClass {a: 3, b: 2, c: 1, d: "ddd"}
</code>```

Link to playground

Body:
You can replace original class constructor with a class level decorator to do all kinds of cool stuff:

function example(target: any) {
    // save a reference to the original constructor
    const original = target;

    // the new constructor behaviour
    const f: any = function (...args: any[]) {
        console.log("Hook before original constructor...");

        const newArgs = [...args].reverse();

        const instance = new original(...newArgs);

        console.log("Hook after original constructor...");

        instance.d = 'ddd';

        return instance;
    }

    // copy prototype so intanceof operator still works
    f.prototype = original.prototype;

    // return new constructor (will override original)
    return f;
}

@example
class SomeClass {
    constructor(public a: number, public b: number, public c: number) {
        console.log("Hello from constructor!")
    }
}

const instance1 = new SomeClass(1, 2, 3);
console.log(instance1); // SomeClass {a: 3, b: 2, c: 1, d: "ddd"}

<a href="https://www.typescriptlang.org/play/?experimentalDecorators=true&ssl=1&ssc=1&pln=35&pc=66#code/GYVwdgxgLglg9mABAUwB4EMC2AHANsgCinQCcBzZKALkXTAE8BKRAbwFgAoRbxAel8QBndADdktRCWTBkUyOKhxEUABbi4JGGRhh0uRBASCoJENA2ceBo1EQatOvYgC8y0hSgBuTpZ79laohgyADu1mDGpuYkiABGyCqi8CAkvtyGEbbANHT0LoigkLAIiAQAdBXugjkMANoAuszsXFY8GYJw%20GW4cGQEAEQAEnBwANZx0hrqmtq6%20u0mZookFWX9jN4caa0LQaEAguSC%20bWrVfVlUmIkgoQbPi2t4caIOsZ0EOKuwWH2s3rlCo-Q5kQT3LaPHZGTrIbq9AbDMa0YBQWR2GaOeY2KLLVbrTbbKxvYjyMoAE3yAHIyTTKQTIVYpFAUkhiR9kJsrABfB5WfyGbB5bAkOCKKD0bDiDqvMAkz5wYB2SUkdDLISwXD6EIaUaCbbAMrC0WiiVfdEOOaGkVi030vkCJksvZhBY4jSlEIwTV2a6aMnTC16RjbR0kJDATY8iEAATQWDwyE4EFw6EExwAynBMMgAMIptOsbaupYaAjYECxXAwCC0GhgECYeIkAA0iHLlercTrDabrfbVZrEG7jdkTUJbWhXR6fSGyE1SmAIswz0W0QAhOttlGo0mbDL3vIAIz5H6ITPZvOpwQEQ%20tgBMrYAzOD2jC4X02UeNnwBOfc-nBAAApYdAaEfVtYhoB8DBoW9EDJGh%20hpMl%20i5IA" rel="nofollow noreferrer">Link to playground


问:
Reading/writing files: Is "a" faster than "a+" mode?
Based on many people's answer, it looks the only difference between "a" and "a+" mode is that "a+" is not only write/append, but also "read".

From my using file open experience, without "a+" mode, I can do write append with "a" pretty well. Does "a" give me performance improvement if I don't need read for the file at all?

For example:

with open('file.txt', 'a') as f:
    f.write('line\n');
```

答:
If you run this test on identical text files, the loop using ‘a+’ runs about one one hundredth of a second slower that ‘a’. This difference does not change significantly as the test is repeated and the files continue to grow larger and larger. This would indicate that even though ‘a+’ is very slightly slower, it does not seem to spend any extra time reading the file first. </p>

```<code>from time import time

start = time ()
with open ('testfile1.txt', 'a') as file :
    for index in range (9999) :
        file.write ('This is a test to see how long this will take.\n')
stop = time ()
first_total = stop - start

start = time ()
with open ('testfile2.txt', 'a+') as file :
    for index in range (9999) :
        file.write ('This is a test to see how long this will take.\n')
stop = time ()
second_total = stop - start

print ('First = ', first_total)
print ('Second = ', second_total)
print ('Differenct = ', second_total - first_total)
</code>```

Body:
If you run this test on identical text files, the loop using ‘a+’ runs about one one hundredth of a second slower that ‘a’. This difference does not change significantly as the test is repeated and the files continue to grow larger and larger. This would indicate that even though ‘a+’ is very slightly slower, it does not seem to spend any extra time reading the file first.

from time import time

start = time ()
with open ('testfile1.txt', 'a') as file :
    for index in range (9999) :
        file.write ('This is a test to see how long this will take.\n')
stop = time ()
first_total = stop - start

start = time ()
with open ('testfile2.txt', 'a+') as file :
    for index in range (9999) :
        file.write ('This is a test to see how long this will take.\n')
stop = time ()
second_total = stop - start

print ('First = ', first_total)
print ('Second = ', second_total)
print ('Differenct = ', second_total - first_total)


问:
write one specific formula in python
I have a question, everyone knows how can I write this formula with python?

答:
Assuming those square brackets are just nested parentheses,

def r(x):
    # ???

def c(x):
    # ???

def w(x):
    # ???

def f(x):
    return r(x) * min(c_ub / c(x), (w_ub / w(x)) ** 3)
```

Title: write one specific formula in python


问:
Pass CheckBox-Objects
How do I have to pass CheckBox-Objects correct to other Subs/Functions?
Had to pass it multiples times. For illustation it worked for
case 1: MsgBox "1) " & ckBox.Name
but not in:
case 2: MsgBox "2) " & ckBox.Name

It starts with a Click-Event from the ClickBox in "ControlBox_Click_100".

```<code># Modul_1 ---------------------------------------------------
Sub ControlBox_Click_100()
    Call fColOnOff(bRowSearch, "New", "Old", , True)
End Sub

# Modul_2 ---------------------------------------------------
Sub fColOnOff(ByVal bRow As Byte, Optional ByVal sSuchen1 As String, _
                                  Optional ByVal sSuchen2 As String, _
                                  Optional ByVal sSuchen3 As String, _
                                  Optional ByVal bolSuchen2 As Boolean, _
                                  Optional ByVal bolSuchen3 As Boolean) _

Call fActCheckBox

    MsgBox "2) " & ckBox.Name

...

End Sub

# Modul_2 ---------------------------------------------------
Private Sub fActCheckBox()

Dim ckBox As CheckBox
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

    MsgBox "1) " & ckBox.Name

End Sub
</code>```

答:
Constellations like this you can handle with a global variable. This worked:</p>

```<code>Public ckBox As CheckBox

Function fActCheckBox()
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)
    MsgBox "1) " & ckBox.Name
End Function

Sub fSpalteEinAusBlenden(... )
    MsgBox "2) " & ckBox.Name
End Sub
</code>```

Title: Pass CheckBox-Objects

Body:
How do I have to pass CheckBox-Objects correct to other Subs/Functions?
Had to pass it multiples times. For illustation it worked for
case 1: MsgBox "1) " & ckBox.Name
but not in:
case 2: MsgBox "2) " & ckBox.Name

It starts with a Click-Event from the ClickBox in "ControlBox_Click_100".

# Modul_1 ---------------------------------------------------
Sub ControlBox_Click_100()
    Call fColOnOff(bRowSearch, "New", "Old", , True)
End Sub

# Modul_2 ---------------------------------------------------
Sub fColOnOff(ByVal bRow As Byte, Optional ByVal sSuchen1 As String, _
                                  Optional ByVal sSuchen2 As String, _
                                  Optional ByVal sSuchen3 As String, _
                                  Optional ByVal bolSuchen2 As Boolean, _
                                  Optional ByVal bolSuchen3 As Boolean) _

Call fActCheckBox

    MsgBox "2) " & ckBox.Name

...

End Sub

# Modul_2 ---------------------------------------------------
Private Sub fActCheckBox()

Dim ckBox As CheckBox
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

    MsgBox "1) " & ckBox.Name

End Sub

Body:
Constellations like this you can handle with a global variable. This worked:

Public ckBox As CheckBox

Function fActCheckBox()
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)
    MsgBox "1) " & ckBox.Name
End Function

Sub fSpalteEinAusBlenden(... )
    MsgBox "2) " & ckBox.Name
End Sub


问:
self captured by a closure before all members were initialized - but I did initialize them
This is a toy example but it reduces exactly the situation I'm in:

```<code>class MyDataSource: UITableViewDiffableDataSource<String,String> {
    var string : String?
    init(string:String?) {
        self.string = string
        super.init(tableView: UITableView()) { (_, _, _) -> UITableViewCell? in
            print(self.string) // error
            return nil
        }
    }
}
</code>```

I'm trying to make my table view data source self-contained, and my way of doing that (so far) is to subclass UITableViewDiffableDataSource. This works fine except when I try to give my subclass a custom initializer. The toy example shows the problem.

The way I want to populate the cell absolutely depends upon a value that can change later in the life of the data source. Therefore it cannot be hard-coded into the cell provider function. I cannot refer here simply to string, the value that was passed in the initializer; I must refer to self.string because other code is going to have the power to change this data source's string instance property later on, and I want the cell provider to use that new value when that happens.

However, I'm getting the error "self captured by a closure before all members were initialized". That seems unfair. I did initialize my string instance property before calling super.init. So it does have a value at the earliest moment when the cell provider method can possibly be called.

答: you can access self via tableView.datasource and it will sort most of the problem.

Body:
This is a toy example but it reduces exactly the situation I'm in:

class MyDataSource: UITableViewDiffableDataSource<String,String> {
    var string : String?
    init(string:String?) {
        self.string = string
        super.init(tableView: UITableView()) { (_, _, _) -> UITableViewCell? in
            print(self.string) // error
            return nil
        }
    }
}

I'm trying to make my table view data source self-contained, and my way of doing that (so far) is to subclass UITableViewDiffableDataSource. This works fine except when I try to give my subclass a custom initializer. The toy example shows the problem.

The way I want to populate the cell absolutely depends upon a value that can change later in the life of the data source. Therefore it cannot be hard-coded into the cell provider function. I cannot refer here simply to string, the value that was passed in the initializer; I must refer to self.string because other code is going to have the power to change this data source's string instance property later on, and I want the cell provider to use that new value when that happens.

However, I'm getting the error "self captured by a closure before all members were initialized". That seems unfair. I did initialize my string instance property before calling super.init. So it does have a value at the earliest moment when the cell provider method can possibly be called.


问:
StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response
I use Firebase Storage to upfile. But it does not work
THIS IS MY CODE.

```<code>FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://the-food-house.appspot.com/");
// Create a reference to "file"
    StorageReference mStorage = storageRef.child("Album Avatar")
            .child(UserUID)
            .child(AvatarUser.getLastPathSegment());
    mStorage.putFile(AvatarUser).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Toast.makeText(SignUpWithEmail.this, "UPLOAD FILE OK", Toast.LENGTH_SHORT).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("ERROR", e.toString());
            Toast.makeText(SignUpWithEmail.this, "Failed", Toast.LENGTH_SHORT).show();
        }
    };
</code>```

Here is the error I am having:

```<code>com.google.firebase.storage.StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response.
</code>```

And this is details of error:

```<code>Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1
E/UploadTask: could not locate file for uploading:https://firebasestorage.googleapis.com/v0/b/the-food-house.appspot.com/o/Avatar%20Default%2Fmale.png?alt=media&token=3f285cab-c32b-4f33-a909-5a85ef62d74d
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
    Code: -13000 HttpResult: 0
E/StorageException: No content provider: https://firebasestorage.googleapis.com/v0/b/the-food-house.appspot.com/o/Avatar%20Default%2Fmale.png?alt=media&token=3f285cab-c32b-4f33-a909-5a85ef62d74d
java.io.FileNotFoundException: No content provider: https://firebasestorage.googleapis.com/v0/b/the-food-house.appspot.com/o/Avatar%20Default%2Fmale.png?alt=media&token=3f285cab-c32b-4f33-a909-5a85ef62d74d
    at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1131)
    at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:982)
    at android.content.ContentResolver.openInputStream(ContentResolver.java:702)
    at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
    at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
    at thedark.example.com.thefoodhouse.Activity.Authencation.SignUpWithEmail.submitAvatarStorage(SignUpWithEmail.java:111)
    at thedark.example.com.thefoodhouse.Activity.Authencation.SignUpWithEmail.access$1200(SignUpWithEmail.java:38)
    at thedark.example.com.thefoodhouse.Activity.Authencation.SignUpWithEmail$5.onComplete(SignUpWithEmail.java:170)
    at com.google.android.gms.tasks.zzf.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
</code>```

This is rule firebase:

```<code>allow read, write: if request.auth != null;
</code>```

It has given me a headache these past few days. Hope that someone finds the problem. Help me please. Thank you.

答:
So the I had the same problem and I easily fixed it!, so this is not a problem with firebase, but the problem is that your file can not be accessed from your local disk!

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

for api 21+ you will need to request permission, for security reasons, check this article for more information:
How to request storage permission

Body:
I use Firebase Storage to upfile. But it does not work
THIS IS MY CODE.

FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://the-food-house.appspot.com/");
// Create a reference to "file"
    StorageReference mStorage = storageRef.child("Album Avatar")
            .child(UserUID)
            .child(AvatarUser.getLastPathSegment());
    mStorage.putFile(AvatarUser).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Toast.makeText(SignUpWithEmail.this, "UPLOAD FILE OK", Toast.LENGTH_SHORT).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("ERROR", e.toString());
            Toast.makeText(SignUpWithEmail.this, "Failed", Toast.LENGTH_SHORT).show();
        }
    };

Here is the error I am having:

com.google.firebase.storage.StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response.

And this is details of error:

Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1
E/UploadTask: could not locate file for uploading:https://firebasestorage.googleapis.com/v0/b/the-food-house.appspot.com/o/Avatar%20Default%2Fmale.png?alt=media&token=3f285cab-c32b-4f33-a909-5a85ef62d74d
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
    Code: -13000 HttpResult: 0
E/StorageException: No content provider: https://firebasestorage.googleapis.com/v0/b/the-food-house.appspot.com/o/Avatar%20Default%2Fmale.png?alt=media&token=3f285cab-c32b-4f33-a909-5a85ef62d74d
java.io.FileNotFoundException: No content provider: https://firebasestorage.googleapis.com/v0/b/the-food-house.appspot.com/o/Avatar%20Default%2Fmale.png?alt=media&token=3f285cab-c32b-4f33-a909-5a85ef62d74d
    at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1131)
    at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:982)
    at android.content.ContentResolver.openInputStream(ContentResolver.java:702)
    at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
    at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
    at thedark.example.com.thefoodhouse.Activity.Authencation.SignUpWithEmail.submitAvatarStorage(SignUpWithEmail.java:111)
    at thedark.example.com.thefoodhouse.Activity.Authencation.SignUpWithEmail.access$1200(SignUpWithEmail.java:38)
    at thedark.example.com.thefoodhouse.Activity.Authencation.SignUpWithEmail$5.onComplete(SignUpWithEmail.java:170)
    at com.google.android.gms.tasks.zzf.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

This is rule firebase:

allow read, write: if request.auth != null;

It has given me a headache these past few days. Hope that someone finds the problem. Help me please. Thank you.

Body:
So the I had the same problem and I easily fixed it!, so this is not a problem with firebase, but the problem is that your file can not be accessed from your local disk!

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

for api 21+ you will need to request permission, for security reasons, check this article for more information:
How to request storage permission


问:
debugging a struct implementing an increment function
I’m trying to implement an increment function on my struct. I’m not sure why, but it appears that when I call F.incr() in main, the fib struct’s parameters appear to remain constant. I think I may have an incorrect idea about what I’m doing in my incr() function, though I’m not able to find the right documentation. What am I missing?

```<code>type fib struct {
    i uint64
    fa uint64
    fb uint64
}

func (F fib) incr(){
    F.i++
    F.fa, F.fb = F.fa+F.fb, F.fa
}

func main() {
    F := fib{1,1,0}
    var sum uint64 = 0
    for; F.i <= 10; F.incr() {
        k := f(F.i, F.fb, F.fa)
        fmt.Printf("calculating the %vth f(i,F_%v, F_%v): %v\n", F.i, F.i-1, F.i, k)
—snip-
</code>```

edit: thanks @peterSO, I needed to change incr to
func (F *fib) incr(){

答:
You need to update your method to increase the value of the variable at the location. Hence, you need to change the F() method

```<code>func (F *fib) incr(){
    F.i++
    F.fa, F.fb = F.fa+F.fb, F.fa
}
</code>```

The difference being the *

Body:
I’m trying to implement an increment function on my struct. I’m not sure why, but it appears that when I call F.incr() in main, the fib struct’s parameters appear to remain constant. I think I may have an incorrect idea about what I’m doing in my incr() function, though I’m not able to find the right documentation. What am I missing?

type fib struct {
    i uint64
    fa uint64
    fb uint64
}

func (F fib) incr(){
    F.i++
    F.fa, F.fb = F.fa+F.fb, F.fa
}

func main() {
    F := fib{1,1,0}
    var sum uint64 = 0
    for; F.i <= 10; F.incr() {
        k := f(F.i, F.fb, F.fa)
        fmt.Printf("calculating the %vth f(i,F_%v, F_%v): %v\n", F.i, F.i-1, F.i, k)
—snip-

edit: thanks @peterSO, I needed to change incr to
func (F *fib) incr(){

Body:
You need to update your method to increase the value of the variable at the location. Hence, you need to change the F() method

func (F *fib) incr(){
    F.i++
    F.fa, F.fb = F.fa+F.fb, F.fa
}

The difference being the *


问:
Inserting hyperlinks to UIAlertController's message text (Xamarin.iOS)
UIAlertController uses an UILabel to display text, and I have read that only UITextViews can show clickable links.
I would replace the label in the dialog, however as soon as I remove it, the program throws an error that its constraint cannot be activated.
To remove that constraint, I cycled through the UILabel's superviews, but it is not to be found.
Does anyone have had success with it?</p>

```<code>UIAlertController dialog = UIAlertController.Create("", message, UIAlertControllerStyle.Alert);
dialog.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

UILabel label = (UILabel)dialog.View.Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[2];
UIView view = label;

do
{
    view = view.Superview;

    Console.WriteLine(view);

    foreach (NSLayoutConstraint constraint in view.Constraints)
    {
        Console.WriteLine("Constraint: " + constraint.FirstItem + " --- " + constraint.FirstAttribute + " --- " + constraint.SecondItem + " --- " + constraint.SecondAttribute + " --- " + constraint.Constant);
        if (constraint.FirstItem == label)
        {
            Console.WriteLine("FirstItem found");
            view.RemoveConstraint(constraint);
        }
        if (constraint.SecondItem == label)
        {
            Console.WriteLine("SecondItem found");
            view.RemoveConstraint(constraint);
        }
    }

} while (view != dialog.View);

//label.RemoveFromSuperview();
</code>```

答:
Well, you can just change the label's visibility, and insert the textview. As Ivan pointed out, it is good to have a backup solution.</p>

```<code>UIAlertController dialog = UIAlertController.Create("", message, UIAlertControllerStyle.Alert);
dialog.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

try
{
    UILabel label = (UILabel)dialog.View.Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[2];
    label.Hidden = true;

    UITextView textView = new UITextView();
    dialog.View.Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[0].InsertSubviewAbove(textView, label);

    textView.TranslatesAutoresizingMaskIntoConstraints = false;
    textView.LeadingAnchor.ConstraintEqualTo(label.LeadingAnchor).Active = true;
    textView.TopAnchor.ConstraintEqualTo(label.TopAnchor, -8).Active = true;

    textView.BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0);
    textView.ScrollEnabled = false;
    textView.Editable = false;
    textView.DataDetectorTypes = UIDataDetectorType.Link;
    textView.Selectable = true;
    textView.Font = UIFont.SystemFontOfSize(13);
    textView.Text = message;
}
catch
{
}

context.PresentViewController(dialog, true, null);
</code>```

Body:
UIAlertController uses an UILabel to display text, and I have read that only UITextViews can show clickable links.
I would replace the label in the dialog, however as soon as I remove it, the program throws an error that its constraint cannot be activated.
To remove that constraint, I cycled through the UILabel's superviews, but it is not to be found.
Does anyone have had success with it?

UIAlertController dialog = UIAlertController.Create("", message, UIAlertControllerStyle.Alert);
dialog.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

UILabel label = (UILabel)dialog.View.Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[2];
UIView view = label;

do
{
    view = view.Superview;

    Console.WriteLine(view);

    foreach (NSLayoutConstraint constraint in view.Constraints)
    {
        Console.WriteLine("Constraint: " + constraint.FirstItem + " --- " + constraint.FirstAttribute + " --- " + constraint.SecondItem + " --- " + constraint.SecondAttribute + " --- " + constraint.Constant);
        if (constraint.FirstItem == label)
        {
            Console.WriteLine("FirstItem found");
            view.RemoveConstraint(constraint);
        }
        if (constraint.SecondItem == label)
        {
            Console.WriteLine("SecondItem found");
            view.RemoveConstraint(constraint);
        }
    }

} while (view != dialog.View);

//label.RemoveFromSuperview();

Body:
Well, you can just change the label's visibility, and insert the textview. As Ivan pointed out, it is good to have a backup solution.

UIAlertController dialog = UIAlertController.Create("", message, UIAlertControllerStyle.Alert);
dialog.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

try
{
    UILabel label = (UILabel)dialog.View.Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[2];
    label.Hidden = true;

    UITextView textView = new UITextView();
    dialog.View.Subviews[0].Subviews[0].Subviews[0].Subviews[0].Subviews[0].InsertSubviewAbove(textView, label);

    textView.TranslatesAutoresizingMaskIntoConstraints = false;
    textView.LeadingAnchor.ConstraintEqualTo(label.LeadingAnchor).Active = true;
    textView.TopAnchor.ConstraintEqualTo(label.TopAnchor, -8).Active = true;

    textView.BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0);
    textView.ScrollEnabled = false;
    textView.Editable = false;
    textView.DataDetectorTypes = UIDataDetectorType.Link;
    textView.Selectable = true;
    textView.Font = UIFont.SystemFontOfSize(13);
    textView.Text = message;
}
catch
{
}

context.PresentViewController(dialog, true, null);


问:
Complex JS onclick events from multiple elements
Ok ( the title may be misleading ) however it is the best i can come up with.

What we want to achieve ?

Ok we have an svg map, of Australia.

On click of a state on that map, the map state changes colour to selected. ( in our case Pink )
At the same time ( a useless button ) which is on page load blank, changes its value to that of the state.
Simultaneously a drop down menu, with the state names in, which on page load has the value , Please Select , changes its value to that of the state.

So : here is what happens.

User visits page and sees map. They also see drop down select box.

They can choose to either click the select dropdown, or click the map.

Scenario 1.
They click the map, and click on the state QUEENSLAND , which has a value of QLD.

On clicking the state, the state changes from grey to pink.
The select drop down, changes from Please select, to Queensland
The gray button changes from blank to QLD

Here is an image:

Ok what we have working is.

The map click events work, and propagate the grey button values, so thats all fine.
The select element works, in so far as if we select a state on the map it changes select box value.

What we dont have working is.

on click of map, we cannot propagate BOTH the select drop down and the gray button values.

we cannot on using the select drop down box, change the "select" state of the map , ie, doesnt change from grey to pink. Also it doesnt change the value of the button from its current value.

So here is some code:

Its SVG so here is the wrap element for the map.

```<code><a xlink:href="javascript:void goToOption(document.australia.state,'WA')" target="_top">
    <path
        id="WA"
        class="territory"
        fill="#a9a9a9"
        onmouseup="clickTerritory(evt)"
        d="m 38.318056,168.24244 c -4.79245,0.99662 -8.64245,1.61598 l -7,1.12612 -8.18526,4.91727 -8.18526,4.91727 -5.31474,-0.0902 c -2.92311,-0.0496 -6.88974,-0.54005 -8.81474,-1.08988 z"/></a>
</code>```

Here is the JS that controls the map click events:

```<code>function prepare(){}
function ready(){
    svgdoc = document.sv.getSVGDocument();
    svgRoot = svgdoc.documentElement;
}
function onTerritoryClick(territory){
    document.getElementById("territory-name").innerHTML=territory;
}

var selected_territory = "None";

  function init(evt) {
    if (window.svgDocument == null)
    {
        svgDocument = evt.target.ownerDocument;
    }
  }

  function clickTerritory(evt) {
    var clicked_territory;

    if (evt.target.parentNode.getAttributeNS(null, "id") != "australia-map")
    {
        // Hack to deal with groups
        clicked_territory = evt.target.parentNode;
    } else {
        clicked_territory = evt.target;
    }

    if (selected_territory != clicked_territory) {
        if (selected_territory != "None") {
            // Unselect previous territory
            selected_territory.setAttributeNS(null, "fill", "#a9a9a9");
        }
        selected_territory = clicked_territory;
        selected_territory.setAttributeNS(null, "fill", "#ec008c");
        top.onTerritoryClick(selected_territory.getAttributeNS(null, "id"));
    }
  }
</code>```

Here is the JS to handle the select box, which fires the href.

```<code>function goToOption(sel, val) {
  var opt, o = 0;
  while (opt = sel[o++]) if (opt.value == val) sel.selectedIndex = o - 1;
}
</code>```

Here is the button html:

```<code><div class="selected-state left">
    <button id="territory-name" class="mystate grayNohover button" style="position:absolute;top:250px;left:50px">ALL</button>
</div>
</code>```

Here is the select menu html:

```<code><select name="state" id="speedF" style="width:180px;">
<option value="">Please Select</option>
<option value="QLD">Queensland</option>
<option value="NT">Northern Territory</option>
<option value="WA">Western Australia</option>
<option value="SA">South Australia</option>
<option value="NSW">New South Wales</option>
<option value="VIC">Victoria</option>
<option value="ACT">A.C.T.</option>
<option value="TAS">Tasmania</option>
</select>
</code>```

sample: http://sitehelp.com.au/demos/svgmap2/

Version 2: http://dev.30.com.au/422-svg/

答:
I'm not an expert in dealing with events, but this sounds like it requires expert knowledge of event bubbling and capturing.

So here is a page that might lead you in the right direction: http://www.quirksmode.org/js/events_order.html

I also happen to know that there is a whole chapter (12) in Nicholas Zakas' book
Professional Javascript for Web Developers devoted to explaining events.

Body:
Ok ( the title may be misleading ) however it is the best i can come up with.

What we want to achieve ?

Ok we have an svg map, of Australia.

On click of a state on that map, the map state changes colour to selected. ( in our case Pink )
At the same time ( a useless button ) which is on page load blank, changes its value to that of the state.
Simultaneously a drop down menu, with the state names in, which on page load has the value , Please Select , changes its value to that of the state.

So : here is what happens.

User visits page and sees map. They also see drop down select box.

They can choose to either click the select dropdown, or click the map.

Scenario 1.
They click the map, and click on the state QUEENSLAND , which has a value of QLD.

On clicking the state, the state changes from grey to pink.
The select drop down, changes from Please select, to Queensland
The gray button changes from blank to QLD

Here is an image:

Ok what we have working is.

The map click events work, and propagate the grey button values, so thats all fine.
The select element works, in so far as if we select a state on the map it changes select box value.

What we dont have working is.

on click of map, we cannot propagate BOTH the select drop down and the gray button values.

we cannot on using the select drop down box, change the "select" state of the map , ie, doesnt change from grey to pink. Also it doesnt change the value of the button from its current value.

So here is some code:

Its SVG so here is the wrap element for the map.

    <path
        id="WA"
        class="territory"
        fill="#a9a9a9"
        onmouseup="clickTerritory(evt)"
        d="m 38.318056,168.24244 c -4.79245,0.99662 -8.64245,1.61598 l -7,1.12612 -8.18526,4.91727 -8.18526,4.91727 -5.31474,-0.0902 c -2.92311,-0.0496 -6.88974,-0.54005 -8.81474,-1.08988 z"/>

Here is the JS that controls the map click events:

function prepare(){}
function ready(){
    svgdoc = document.sv.getSVGDocument();
    svgRoot = svgdoc.documentElement;
}
function onTerritoryClick(territory){
    document.getElementById("territory-name").innerHTML=territory;
}

var selected_territory = "None";

  function init(evt) {
    if (window.svgDocument == null)
    {
        svgDocument = evt.target.ownerDocument;
    }
  }

  function clickTerritory(evt) {
    var clicked_territory;

    if (evt.target.parentNode.getAttributeNS(null, "id") != "australia-map")
    {
        // Hack to deal with groups
        clicked_territory = evt.target.parentNode;
    } else {
        clicked_territory = evt.target;
    }

    if (selected_territory != clicked_territory) {
        if (selected_territory != "None") {
            // Unselect previous territory
            selected_territory.setAttributeNS(null, "fill", "#a9a9a9");
        }
        selected_territory = clicked_territory;
        selected_territory.setAttributeNS(null, "fill", "#ec008c");
        top.onTerritoryClick(selected_territory.getAttributeNS(null, "id"));
    }
  }

Here is the JS to handle the select box, which fires the href.

function goToOption(sel, val) {
  var opt, o = 0;
  while (opt = sel[o++]) if (opt.value == val) sel.selectedIndex = o - 1;
}

Here is the button html:

    <button id="territory-name" class="mystate grayNohover button" style="position:absolute;top:250px;left:50px">ALL</button>

Here is the select menu html:

<select name="state" id="speedF" style="width:180px;">
<option value="">Please Select</option>
<option value="QLD">Queensland</option>
<option value="NT">Northern Territory</option>
<option value="WA">Western Australia</option>
<option value="SA">South Australia</option>
<option value="NSW">New South Wales</option>
<option value="VIC">Victoria</option>
<option value="ACT">A.C.T.</option>
<option value="TAS">Tasmania</option>
</select>

sample: http://sitehelp.com.au/demos/svgmap2/

Version 2: http://dev.30.com.au/422-svg/


问:
How can I correctly parse array of JSON objects?
this is my data:

```<code>var data = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "lllllllllllllllll": "sssssssssss", "ppppppppppp": null, "__typename": "xx" }, { "_id": "5e4595374bee49300c47e1ab", "xxTitle": "ggggggg", "hhhhhhhhhh": "ggggggg", "xxzzzzzz": "ggggggg", "oooooooooooooo": "ggggggg", "xxDescription": "ggggggg", "xxDetails": "ggggggg", "lllllllllllllllll": "ggggggg", "ppppppppppp": "ggggggg", "__typename": "xx" } ]
</code>```

I want to pass this data as a string via HTTP and then read it back as json, instead I'm getting [ '[object Object]', '[object Object]' ]

please assist.

答:
You need to parse your JSON into a var
In your case it’ll be:

var jsonData = JSON.parse(data)
    var id = jsonData._id

Body:
this is my data:

var data = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "lllllllllllllllll": "sssssssssss", "ppppppppppp": null, "__typename": "xx" }, { "_id": "5e4595374bee49300c47e1ab", "xxTitle": "ggggggg", "hhhhhhhhhh": "ggggggg", "xxzzzzzz": "ggggggg", "oooooooooooooo": "ggggggg", "xxDescription": "ggggggg", "xxDetails": "ggggggg", "lllllllllllllllll": "ggggggg", "ppppppppppp": "ggggggg", "__typename": "xx" } ]

I want to pass this data as a string via HTTP and then read it back as json, instead I'm getting [ '[object Object]', '[object Object]' ]

please assist.


问:
extract characters from second occurrence of dash in a string
I have a string "apple-rose-orange-21-X-84"; I need to extract the string after the second occurrence of "-" using shell script.

The answer should be orange-21-X-84.

How would I do this in shell script, I have tried several ways, couldn't find an answer.

答:
Here's a few POSIX shell methods, (no bash or external utils needed):

Using pipes and read:

```<code>echo apple-rose-orange-21-X-84 | (IFS="-" read a b c; echo $c;)
</code>```

Using parameter substitution:

```<code>s=apple-rose-orange-21-X-84; echo ${s#*-*-}
</code>```

Body:
Here's a few POSIX shell methods, (no bash or external utils needed):

Using pipes and read:

echo apple-rose-orange-21-X-84 | (IFS="-" read a b c; echo $c;)

Using parameter substitution:

s=apple-rose-orange-21-X-84; echo ${s#*-*-}


问:
How can I get my AWS Lambda to access gems stored in vendor/bundle?
I'm writing a Lambda function in Ruby which will eventually send me some notifications in Slack via Webhook.  So what I have for my lambda_function file is

```<code>require 'json'
require 'webhook'

def lambda_handler(event:, context:)
    # TODO implement
    { statusCode: 200, body: JSON.generate('Hello from Lambda!') }
    Webhook.post('https://mywebhookurl', {message: 'test'})
end
</code>```

And the directory structure in my inline code editor looks like this:

```<code>Gemfile
Gemfile.lock
lambda_function.rb
vendor/
  bundle/
    ruby
      2.3.0
        gems/webhook
</code>```

also under the 2.3.0 bath are several other folders including build_info,  cache, doc etc.  In order to get this code onto AWS Lambda, I'm running

zip -r myLambda.zip * to get everything into a zip file and uploaded to Lambda.

However, when I finally go to run a basic test on the lambda, I get the following error:

```<code>{
  "errorMessage": "cannot load such file -- webhook",
  "errorType": "Init<LoadError>",
  "stackTrace": [
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/task/lambda_function.rb:2:in `<top (required)>'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'"
  ]
}
</code>```

There shouldn't be any more to this as the following tutorial shows exactly how to set up what I have, but doesn't work.  Does anyone have success pulling gems from their gemfile in AWS Lambda?

答:
I think you should not change the GEM_PATH or having to set $LOAD_PATH in every lambda functions.
The "best" way is to do this little hack when you create the layer archive:

```<code>bundle install --path vendor/bundle
cd vendor/bundle
mkdir ruby/gems
mv ruby/2.5.0 ruby/gems/
zip -r layer.zip ruby/gems/2.5.0/
</code>```

Body:
I'm writing a Lambda function in Ruby which will eventually send me some notifications in Slack via Webhook.  So what I have for my lambda_function file is

require 'json'
require 'webhook'

def lambda_handler(event:, context:)
    # TODO implement
    { statusCode: 200, body: JSON.generate('Hello from Lambda!') }
    Webhook.post('https://mywebhookurl', {message: 'test'})
end

And the directory structure in my inline code editor looks like this:

Gemfile
Gemfile.lock
lambda_function.rb
vendor/
  bundle/
    ruby
      2.3.0
        gems/webhook

also under the 2.3.0 bath are several other folders including build_info,  cache, doc etc.  In order to get this code onto AWS Lambda, I'm running

zip -r myLambda.zip * to get everything into a zip file and uploaded to Lambda.

However, when I finally go to run a basic test on the lambda, I get the following error:

{
  "errorMessage": "cannot load such file -- webhook",
  "errorType": "Init<LoadError>",
  "stackTrace": [
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/task/lambda_function.rb:2:in `<top (required)>'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'"
  ]
}

There shouldn't be any more to this as the following tutorial shows exactly how to set up what I have, but doesn't work.  Does anyone have success pulling gems from their gemfile in AWS Lambda?

Body:
I think you should not change the GEM_PATH or having to set $LOAD_PATH in every lambda functions.
The "best" way is to do this little hack when you create the layer archive:

bundle install --path vendor/bundle
cd vendor/bundle
mkdir ruby/gems
mv ruby/2.5.0 ruby/gems/
zip -r layer.zip ruby/gems/2.5.0/


问:
Can't sync Gradle in Android Studio in Iran
I use Android Studio version 1.5.1,
and I'm trying to compile 'com.android.volley:volley:1.0.0' in build.gradle, but I can't sync Gradle.
I think this error is because of my Internet connection or access being blocked from my country (Iran).</p>

答: Certainly Google as an american company has to obey US foreign policies. Google has too many services, among them those which relate to developers are blocked. There are many ways to work around these bans using proxies and VPNs but i personally wish for changes to happen between Iran and US.</p>


答:
While I'm not entirely sure why Swift doesn't allow this (something to do with capturing self to create the closure before the actual call to super.init is made), I do at least know of a workaround for it. Capture a weak local variable instead, and after the call to super.init set that local variable to self:

class MyDataSource: UITableViewDiffableDataSource<String,String> {
    var string : String?
    init(string:String?) {
        self.string = string
        weak var selfWorkaround: MyDataSource?
        super.init(tableView: UITableView()) { (_, _, _) -> UITableViewCell? in
            print(selfWorkaround?.string)
            return nil
        }

        selfWorkaround = self
    }
}
```

The only problem with this, though, is that if the closure is executed during the call to super.init, then selfWorkaround would be nil inside the closure and you may get unexpected results. (In this case, though, I don't think it is - so you should be safe to do this.)

Edit: The reason we make the local variable weak is to prevent the self object from being leaked.

Title: self captured by a closure before all members were initialized - but I did initialize them

Body:
While I'm not entirely sure why Swift doesn't allow this (something to do with capturing self to create the closure before the actual call to super.init is made), I do at least know of a workaround for it. Capture a weak local variable instead, and after the call to super.init set that local variable to self:

class MyDataSource: UITableViewDiffableDataSource<String,String> {
    var string : String?
    init(string:String?) {
        self.string = string
        weak var selfWorkaround: MyDataSource?
        super.init(tableView: UITableView()) { (_, _, _) -> UITableViewCell? in
            print(selfWorkaround?.string)
            return nil
        }

        selfWorkaround = self
    }
}

The only problem with this, though, is that if the closure is executed during the call to super.init, then selfWorkaround would be nil inside the closure and you may get unexpected results. (In this case, though, I don't think it is - so you should be safe to do this.)

Edit: The reason we make the local variable weak is to prevent the self object from being leaked.


问:
How to unmount based on volume type using Python GIO library
I am trying to mimic the behaviour of shell command gio mount which unmounts all gphoto2 cameras

```<code>gio mount -s gphoto2
</code>```

How to detect if volume is gphoto2? I tried getting volume type but there doesn't seem to be variable that holds it,

```<code>from gi.repository import Gio, GObject

def main():
    mo = Gio.MountOperation()
    mo.set_anonymous(True)

    vl = Gio.VolumeMonitor.get()

    loop = GObject.MainLoop()

    for v in vl.get_mounts():
        print(dir(v))
        print(v.get_name(), v.get_uuid(), v.g_type_instance, v.get_drive(),
              v.get_volume(),
              v.get_root(),
              v.get_drive(),
              v.get_sort_key(),
              v.get_uuid())
</code>```

答:
Get the root of the mount (https://developer.gnome.org/gio/stable/GMount.html#g-mount-get-root) and check its URI scheme (https://developer.gnome.org/gio/stable/GFile.html#g-file-has-uri-scheme). If the scheme is gphoto2, you can unmount it.

See the C implementation of gio mount -s.

Body:
I am trying to mimic the behaviour of shell command gio mount which unmounts all gphoto2 cameras

gio mount -s gphoto2

How to detect if volume is gphoto2? I tried getting volume type but there doesn't seem to be variable that holds it,

from gi.repository import Gio, GObject

def main():
    mo = Gio.MountOperation()
    mo.set_anonymous(True)

    vl = Gio.VolumeMonitor.get()

    loop = GObject.MainLoop()

    for v in vl.get_mounts():
        print(dir(v))
        print(v.get_name(), v.get_uuid(), v.g_type_instance, v.get_drive(),
              v.get_volume(),
              v.get_root(),
              v.get_drive(),
              v.get_sort_key(),
              v.get_uuid())