问:
Chat app list last messages of each peer using parse server
I am doing a chat app using parse server, everything is great but i tried make to list just last message for every remote peer. i didn't find any query limitation how to get just one message from every remote peer how can i make this ?</p>

答:
Query limitation with Parse SDK

To limit the number of object that you get from a query you use limit

Here is a little example:

```<code>    const Messages = Parse.Object.extend("Messages");
    const query = new Parse.Query(Messages);
    query.descending("createdAt");
    query.limit(1); // Get only one result
</code>```

Get the first object of a query with Parse SDK

In you case as you really want only one result you can use Query.first.
Like Query.find the method Query.first make a query and will return only the first result of the Query

Here is an example:

```<code>    const Messages = Parse.Object.extend("Messages");
    const query = new Parse.Query(Messages);
    query.descending("createdAt");
    const message = await query.first();
</code>```

I hope my answer help you

Body:
Query limitation with Parse SDK

To limit the number of object that you get from a query you use limit

Here is a little example:

    const Messages = Parse.Object.extend("Messages");
    const query = new Parse.Query(Messages);
    query.descending("createdAt");
    query.limit(1); // Get only one result

Get the first object of a query with Parse SDK

In you case as you really want only one result you can use Query.first.
Like Query.find the method Query.first make a query and will return only the first result of the Query

Here is an example:

    const Messages = Parse.Object.extend("Messages");
    const query = new Parse.Query(Messages);
    query.descending("createdAt");
    const message = await query.first();

I hope my answer help you


来源: stackexchange

问:
Retrieving one value from JSON works, but identical approach on the other value fails
The source .json file is as simple as this:

```<code>{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}
</code>```

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

```<code>Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub
</code>```

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

```<code>MsgBox oJSON.rates.EURUSD.rate
</code>```

auto-transforms into

```<code>MsgBox oJSON.rates.EURUSD.Rate
</code>```

How can I return the "rate" value?

答:
A workaround could be evaluating it :

```<code>MsgBox scriptControl.Eval("(" + .responsetext + ").rates.EURUSD.rate")
</code>```

The object can also be assigned to JS variable (not tested) :

```<code>Set EURUSD = scriptControl.Eval("EURUSD = (" + .responsetext + ").rates.EURUSD")
Debug.Print scriptControl.Eval("EURUSD.rate")
Debug.Print EURUSD.timestamp
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The source .json file is as simple as this:

{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

MsgBox oJSON.rates.EURUSD.rate

auto-transforms into

MsgBox oJSON.rates.EURUSD.Rate

How can I return the "rate" value?

Body:
A workaround could be evaluating it :

MsgBox scriptControl.Eval("(" + .responsetext + ").rates.EURUSD.rate")

The object can also be assigned to JS variable (not tested) :

Set EURUSD = scriptControl.Eval("EURUSD = (" + .responsetext + ").rates.EURUSD")
Debug.Print scriptControl.Eval("EURUSD.rate")
Debug.Print EURUSD.timestamp


问:
Matplotlib: plotting function plt.contourf() fails to plot over 9 colors from colormap jet
I am trying to plot vertical lines with different colors from continuous colormap 'jet' and noticed that function plt.contourf() is not capable of plotting over 9 colors.

Here is an example about the situation where number of colors can be controlled by changing the value of the variable num_colors. I used specific values for this example because I noticed this phenomenon in another program which uses same values for Z.

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

num_colors = 10
values = [x / 10.0 for x in range(5, (10*num_colors)+5, 10)]  # [0.5, 1.5, ..., 9.5]
# create example color-map (vertical strides)
list = []
for k in range(10*num_colors):
    tmp_list = []
    for i in range(len(values)):
        for j in range(10):
            tmp_list.append(values[i])
    list.append(tmp_list)

Z = np.array(list)
x = np.arange(0, num_colors, 0.1)
y = np.arange(0, num_colors, 0.1)
xx, yy = np.meshgrid(x, y)

plt.contourf(xx, yy, Z, cmap='jet', alpha=1.0)
plt.show()
</code>```

答:
Try to define the number of level in contourf:

```<code>plt.contourf(xx, yy, Z, levels=10, cmap='jet', alpha=1.0)
</code>```

Output:

Body:
I am trying to plot vertical lines with different colors from continuous colormap 'jet' and noticed that function plt.contourf() is not capable of plotting over 9 colors.

Here is an example about the situation where number of colors can be controlled by changing the value of the variable num_colors. I used specific values for this example because I noticed this phenomenon in another program which uses same values for Z.

import matplotlib.pyplot as plt
import numpy as np

num_colors = 10
values = [x / 10.0 for x in range(5, (10*num_colors)+5, 10)]  # [0.5, 1.5, ..., 9.5]
# create example color-map (vertical strides)
list = []
for k in range(10*num_colors):
    tmp_list = []
    for i in range(len(values)):
        for j in range(10):
            tmp_list.append(values[i])
    list.append(tmp_list)

Z = np.array(list)
x = np.arange(0, num_colors, 0.1)
y = np.arange(0, num_colors, 0.1)
xx, yy = np.meshgrid(x, y)

plt.contourf(xx, yy, Z, cmap='jet', alpha=1.0)
plt.show()

Body:
Try to define the number of level in contourf:

plt.contourf(xx, yy, Z, levels=10, cmap='jet', alpha=1.0)

Output:


问:
Trouble with Task.WhenAny
I am using .NET framework to create a server, which listens on two ports on localhost.  It is a simple console application.

It works when I keep connecting to one of the ports, but after I connect to first, another does not respond.  First still is alive.

Here is my code:

```<code>    static void Main(string[] args)
    {
        IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
        List<TcpListener> listeners = new List<TcpListener>()
        {
            new TcpListener(hostIP, 6060),
            new TcpListener(hostIP, 6061)
        };
        foreach (TcpListener listener in listeners)
        {
            listener.Start();
        }
        try
        {
            while (true)
            {
                Socket socket = AcceptAnyConnection(listeners).Result;
                NetworkStream stream = new NetworkStream(socket);
                byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                stream.Write(bytes, 0, bytes.Length);
                //stream.Close();
                socket.Close();
            }
        }
        finally
        {
            foreach (TcpListener listener in listeners)
            {
                listener.Stop();
            }
        }
    }

    private static async Task<Socket> AcceptAnyConnection(List<TcpListener> listeners)
    {
        List<Task<Socket>> tasks = new List<Task<Socket>>();
        foreach (TcpListener listener in listeners)
        {
            tasks.Add(AcceptConnection(listener));
        }
        Task<Socket> completedTask = await Task.WhenAny(tasks);
        return await completedTask;
    }
    private static async Task<Socket> AcceptConnection(TcpListener listener)
    {
        Socket socket = await listener.AcceptSocketAsync();
        return socket;
    }
</code>```

await Task.WhenAny() blocks if I connect to another port.

I must be doing something wrong, but I am not sure what.

BTW, I did try the same with .NET Core console application, and it works fine.

Thanks

答:
I'd suggest refactoring your code to something like this, and taking it from there. That is, run an infinite loop for each listener. That avoids problems with making sure that you only call AcceptTcpClientAsync once at a time for each client.

(Note there's no code to actually stop the listeners. Also completely untested - please use it only as an indication of the sort of approach to take)

```<code>static void Main(string[] args)
{
    IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
    List<TcpListener> listeners = new List<TcpListener>()
    {
        new TcpListener(hostIP, 6060),
        new TcpListener(hostIP, 6061)
    };

    var listenerTasks = listeners.Select(x => RunTcpListener(x)).ToArray();
    Task.WaitAll(listenerTasks);
}

private static async Task RunTcpListener(TcpListener listener)
{
    listener.Start();

    try
    {
        while (true)
        {
            using (var client = await listener.AcceptTcpClientAsync())
            {
                var stream = client.GetStream();
                byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                stream.Write(bytes, 0, bytes.Length);

                client.Close();
            }
        }
    }
    finally
    {
        listener.Stop();
    }
}
</code>```

Title: Trouble with Task.WhenAny

Body:
I am using .NET framework to create a server, which listens on two ports on localhost.  It is a simple console application.

It works when I keep connecting to one of the ports, but after I connect to first, another does not respond.  First still is alive.

Here is my code:

    static void Main(string[] args)
    {
        IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
        List<TcpListener> listeners = new List<TcpListener>()
        {
            new TcpListener(hostIP, 6060),
            new TcpListener(hostIP, 6061)
        };
        foreach (TcpListener listener in listeners)
        {
            listener.Start();
        }
        try
        {
            while (true)
            {
                Socket socket = AcceptAnyConnection(listeners).Result;
                NetworkStream stream = new NetworkStream(socket);
                byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                stream.Write(bytes, 0, bytes.Length);
                //stream.Close();
                socket.Close();
            }
        }
        finally
        {
            foreach (TcpListener listener in listeners)
            {
                listener.Stop();
            }
        }
    }

    private static async Task<Socket> AcceptAnyConnection(List<TcpListener> listeners)
    {
        List<Task<Socket>> tasks = new List<Task<Socket>>();
        foreach (TcpListener listener in listeners)
        {
            tasks.Add(AcceptConnection(listener));
        }
        Task<Socket> completedTask = await Task.WhenAny(tasks);
        return await completedTask;
    }
    private static async Task<Socket> AcceptConnection(TcpListener listener)
    {
        Socket socket = await listener.AcceptSocketAsync();
        return socket;
    }

await Task.WhenAny() blocks if I connect to another port.

I must be doing something wrong, but I am not sure what.

BTW, I did try the same with .NET Core console application, and it works fine.

Thanks

Body:
I'd suggest refactoring your code to something like this, and taking it from there. That is, run an infinite loop for each listener. That avoids problems with making sure that you only call AcceptTcpClientAsync once at a time for each client.

(Note there's no code to actually stop the listeners. Also completely untested - please use it only as an indication of the sort of approach to take)

static void Main(string[] args)
{
    IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
    List<TcpListener> listeners = new List<TcpListener>()
    {
        new TcpListener(hostIP, 6060),
        new TcpListener(hostIP, 6061)
    };

    var listenerTasks = listeners.Select(x => RunTcpListener(x)).ToArray();
    Task.WaitAll(listenerTasks);
}

private static async Task RunTcpListener(TcpListener listener)
{
    listener.Start();

    try
    {
        while (true)
        {
            using (var client = await listener.AcceptTcpClientAsync())
            {
                var stream = client.GetStream();
                byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                stream.Write(bytes, 0, bytes.Length);

                client.Close();
            }
        }
    }
    finally
    {
        listener.Stop();
    }
}


问:
React TypeError: Cannot read property 'searchField' of undefined
```<code>TypeError: Cannot read property 'searchField' of undefined
Function.mapStateToProps [as mapToProps]
C:/Users/windw/Desktop/robofriends/src/containers/App.js:11
   8 |
   9 | const mapStateToProps = state => {
  10 |     return {
> 11 |         searchField: state.searchRobots.searchField
  12 |     }
  13 | }
  14 |
</code>```

答:
use this
   searchField: state.searchField
 instead of
searchField: state.searchRobots.searchField

And you instructor will also guide you to remove searchRobots in later part of video.


问:
Spring boot run ends successfully but embedded server is down
I am executing a maven spring-boot:run command which ends without errors but it's embedded server keeps down.

```<code>[CPRO][ INFO] [2019-05-30 10:01:03] [es.ja.ctpd.calcprod.CalcProdApplication.main()] [org.apache.juli.logging.DirectJDKLog.log(179)] Using a shared selector for servlet write/read
[CPRO][ INFO] [2019-05-30 10:01:03] [es.ja.ctpd.calcprod.CalcProdApplication.main()] [org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(185)] Tomcat started on port(s): 8090 (http)
[CPRO][ INFO] [2019-05-30 10:01:03] [es.ja.ctpd.calcprod.CalcProdApplication.main()] [org.springframework.boot.StartupInfoLogger.logStarted(57)] Started CalcProdApplication in 10.351 seconds (JVM running for 13.681)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.806 s
[INFO] Finished at: 2019-05-30T10:01:03+02:00
[INFO] ------------------------------------------------------------------------
</code>```

I'm working in a multi-module project. The comand I lauch is this (positioned in the \application folder)

```<code>mvn spring-boot:start -P dev -s <path>\settings.xml -Dspring.profiles.active=dev
</code>```

I've seen that it is possible to launch boot using java -jar, but my application is a war so I don't know if I could use this option.

I've also noticed that from my STS IDE when launching the server (this works fine) there are some log lines "AUTO-CONFIGURATION REPORT" in the console that are not present in my command-line boot.

Thanks!

UPDATE

Ok, as @andy-wilkinson says, I had to use spring-boot:run, but I still had issues. I've finally been able to run my app with this setup:

1 - A spring-boot:repackage command:

```<code>mvn clean install spring-boot:repackage -P dev -s <path>\settings.xml -Dspring.profiles.active=dev -Dstart-class=<myclass>
</code>```

2 - Launch command with java -jar:

```<code>java -jar -Dspring.profiles.active=dev application\target\application-1.0.0.BUILD-SNAPSHOT-exec.war
</code>```

Two final coments:

I'm aware I should use a different running profile, that'll be the next big step.

I've had to delete a useles orm.xml file I had that was giving an XML parse error and now it runs without problems. There's only a tomcat cache log line during boot up that I'll ask in another post.

答:
If you want to run your application from the command line using Maven you should use spring-boot:run rather than spring-boot:start.

mvn spring-boot:start is intended for use with integration tests and Failsafe. It starts the application and then moves on. It's typically followed by Failsafe invoking a number of integration tests against the running application and then an invocation of spring-boot:stop to stop the application. You're specifically running the start goal so there's nothing else to do and Maven exits.

I've seen that it is possible to launch boot using java -jar, but my application is a war so I don't know if I could use this option.

An executable war (one built using Spring Boot's Maven plugin) can be run using java -jar. That is how it should be run outside of development, with spring-boot:run being intended for us only at dev time.

Body:
I am executing a maven spring-boot:run command which ends without errors but it's embedded server keeps down.

[CPRO][ INFO] [2019-05-30 10:01:03] [es.ja.ctpd.calcprod.CalcProdApplication.main()] [org.apache.juli.logging.DirectJDKLog.log(179)] Using a shared selector for servlet write/read
[CPRO][ INFO] [2019-05-30 10:01:03] [es.ja.ctpd.calcprod.CalcProdApplication.main()] [org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(185)] Tomcat started on port(s): 8090 (http)
[CPRO][ INFO] [2019-05-30 10:01:03] [es.ja.ctpd.calcprod.CalcProdApplication.main()] [org.springframework.boot.StartupInfoLogger.logStarted(57)] Started CalcProdApplication in 10.351 seconds (JVM running for 13.681)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.806 s
[INFO] Finished at: 2019-05-30T10:01:03+02:00
[INFO] ------------------------------------------------------------------------

I'm working in a multi-module project. The comand I lauch is this (positioned in the \application folder)

mvn spring-boot:start -P dev -s <path>\settings.xml -Dspring.profiles.active=dev

I've seen that it is possible to launch boot using java -jar, but my application is a war so I don't know if I could use this option.

I've also noticed that from my STS IDE when launching the server (this works fine) there are some log lines "AUTO-CONFIGURATION REPORT" in the console that are not present in my command-line boot.

Thanks!

UPDATE

Ok, as @andy-wilkinson says, I had to use spring-boot:run, but I still had issues. I've finally been able to run my app with this setup:

1 - A spring-boot:repackage command:

mvn clean install spring-boot:repackage -P dev -s <path>\settings.xml -Dspring.profiles.active=dev -Dstart-class=<myclass>

2 - Launch command with java -jar:

java -jar -Dspring.profiles.active=dev application\target\application-1.0.0.BUILD-SNAPSHOT-exec.war

Two final coments:

I'm aware I should use a different running profile, that'll be the next big step.

I've had to delete a useles orm.xml file I had that was giving an XML parse error and now it runs without problems. There's only a tomcat cache log line during boot up that I'll ask in another post.


问:
What advantages does jQuery have over other JavaScript libraries?
I am trying to convince those who set standards at my current organization that we should use jQuery rather than Prototype and/or YUI. What are some convincing advantages I can use to convince them?</p>

答: Empirically each has their own strengths and weaknesses given a very specific role within your applications. Making a global determination may not be the most appropriate approach.  Carve out the specific task at hand and analyze performance, bloat, experience etc then make a specific decision / proposal.</p>

OwnerDisplayName: mcherm

LastEditorDisplayName: JasonBunting

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Procedure to install an Ingress controller
Unable to install ingress-nginx for kubernetes on Docker desktop

I was using the following in cmd line to install ingress nginx so far:

$ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/mandatory.yaml
$ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/provider/cloud-generic.yaml

as shown in the web page: https://che.eclipse.org/running-eclipse-che-on-kubernetes-using-docker-desktop-for-mac-5d972ed511e1

I seems like the installatio procedure has changed. Can anyone let me know step by step instructions to install ingress-nginx? I coudnt install it by following the procedure described here: https://github.com/kubernetes/ingress-nginx/blob/master/docs/deploy/index.md

答:
Installation via helm works perfectly for me. Assuming you have kubectl binary installed and configured to use for your k8s cluster you can follow below steps one by one to achieve installation of nginx-ingress controller

1.Install helm binary (if doesn't exist)

```<code>curl -s https://raw.githubusercontent.com/nurlanf/deployments-kubernetes/master/helm/get_helm.sh | bash
</code>```

2.Install helm for your cluster (if not installed yet)

```<code>curl -s https://raw.githubusercontent.com/nurlanf/deployments-kubernetes/master/helm/install.sh | bash
</code>```

You should see output like

```<code>...
Waiting for tiller install...
Helm install complete
</code>```

3.Then install nginx-ingress via helm

```<code>helm install stable/nginx-ingress --name nginx-ingress
</code>```

Body:
Installation via helm works perfectly for me. Assuming you have kubectl binary installed and configured to use for your k8s cluster you can follow below steps one by one to achieve installation of nginx-ingress controller

1.Install helm binary (if doesn't exist)

curl -s https://raw.githubusercontent.com/nurlanf/deployments-kubernetes/master/helm/get_helm.sh | bash

2.Install helm for your cluster (if not installed yet)

curl -s https://raw.githubusercontent.com/nurlanf/deployments-kubernetes/master/helm/install.sh | bash

You should see output like

...
Waiting for tiller install...
Helm install complete

3.Then install nginx-ingress via helm

helm install stable/nginx-ingress --name nginx-ingress


问:
Why is it possible to specify React elements (JavaScript objects) as children to a React component?
The result of a call to React.createElement(...) is an object along the lines of:

```<code>{
    $$typeof: Symbol(react.element),
    key: null,
    props: {children: Array(2)},
    ref: null,
    type: "div",
    _owner: null,
    _store: {validated: true},
    _self: null,
    _source: null,
    __proto__: Object
}
</code>```

I take this to be the representation of a DOM element in React's virtual DOM (please let me know if this is not correct).

Whilst creating functionality for dynamically adding elements to a page, I mistakingly tried by keeping an array of react elements in the state object:

```<code>class Form extends Component {
  constructor(props) {
    super(props)
    this.state = { things: [], count: 0 }
  }
  updateForm(obj, cb) {...}
  render() {
    return (<>
        {this.props.render({
          updateForm: this.updateForm.bind(this),
          ...this.state
        })}
    </>)
  }
}

const makeThing = props =>
  <div>
    I am a thing. count is: {props.count}
  </div>

const App = () =>
  <Form
  render={
    props => (
      <div>
        {props.things.map(t => t)} // RENDERING ELEMENTS DIRECTLY
        <button onClick={() => props.updateForm({things: [...props.things, makeThing(props)]})}>Add thing</button>
        <button onClick={() => props.updateForm({count: props.count + 1})}>Increase count</button>
      </div>
    )
  } />
</code>```

I have subsequently learned that specifying pre-created react elements as children of some component just isn't a good idea.

Why is it even possible? Surely there is NEVER a case when I would actually want to do this... I.e. it should error?

答:
I can't see any problem with what you've posted. You're free to create your Components wherever and however you like and pass them around. They're just objects so they can go in state if you like.

The only caveat is that it's more efficient (and better in terms of separation of concerns) to pass around your viewData and handlers and then use that to render your components at the point when you actually need to.

Body:
The result of a call to React.createElement(...) is an object along the lines of:

{
    $$typeof: Symbol(react.element),
    key: null,
    props: {children: Array(2)},
    ref: null,
    type: "div",
    _owner: null,
    _store: {validated: true},
    _self: null,
    _source: null,
    __proto__: Object
}

I take this to be the representation of a DOM element in React's virtual DOM (please let me know if this is not correct).

Whilst creating functionality for dynamically adding elements to a page, I mistakingly tried by keeping an array of react elements in the state object:

class Form extends Component {
  constructor(props) {
    super(props)
    this.state = { things: [], count: 0 }
  }
  updateForm(obj, cb) {...}
  render() {
    return (<>
        {this.props.render({
          updateForm: this.updateForm.bind(this),
          ...this.state
        })}
    </>)
  }
}

const makeThing = props =>

    I am a thing. count is: {props.count}

const App = () =>
  <Form
  render={
    props => (

        {props.things.map(t => t)} // RENDERING ELEMENTS DIRECTLY
        <button onClick={() => props.updateForm({things: [...props.things, makeThing(props)]})}>Add thing</button>
        <button onClick={() => props.updateForm({count: props.count + 1})}>Increase count</button>

    )
  } />

I have subsequently learned that specifying pre-created react elements as children of some component just isn't a good idea.

Why is it even possible? Surely there is NEVER a case when I would actually want to do this... I.e. it should error?


问:
Run all Python scripts in a folder - from Python
How can I write a Python program that runs all Python scripts in the current folder? The program should run in Linux, Windows and any other OS in which python  is installed.

Here is what I tried:

```<code>import glob, importlib

for file in glob.iglob("*.py"):
    importlib.import_module(file)
</code>```

This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).

If I change the last line to:

```<code>    importlib.import_module(file.replace(".py",""))
</code>```

then I get no error, but also the scripts do not run.

Another attempt:

```<code>import glob, os

for file in glob.iglob("*.py"):
    os.system(file)
</code>```

This does not work on Windows - it tries to open each file in Notepad.

答:
If you have control over the content of the scripts, perhaps you might consider using a plugin technique, this would bring the problem more into the Python domain and thus makes it less platform dependent. Take a look at pyPlugin as an example.

This way you could run each "plugin" from within the original process, or using the Python::multiprocessing library you could still seamlessly use sub-processes.

Body:
How can I write a Python program that runs all Python scripts in the current folder? The program should run in Linux, Windows and any other OS in which python  is installed.

Here is what I tried:

import glob, importlib

for file in glob.iglob("*.py"):
    importlib.import_module(file)

This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).

If I change the last line to:

    importlib.import_module(file.replace(".py",""))

then I get no error, but also the scripts do not run.

Another attempt:

import glob, os

for file in glob.iglob("*.py"):
    os.system(file)

This does not work on Windows - it tries to open each file in Notepad.


问:
How to validate JSON input using Golang?
I'm using Beego framework to build a web application in Go. I have to validate the incoming JSON in an API request.

I can unmarshal the JSON into a struct which works fine, but I want to validate the data as well. For example, if the type doesn't match with the type in struct json.Unmarshal will reutrn an error on the first occurence. I want to validate and get all the errors at once for JSON.

I've tried https://github.com/thedevsaddam/govalidator but the package needs a reference to request object which is not available in the controller of Beego. There are other validators which can validate a struct but i want the json validation as well.

EDIT:

A reference to the request object in beego can be found from the controller's context object as:

```<code>func (this *MainController) Post() {
    fmt.Println(this.Ctx.Request)
}
</code>```

But the problem remains same with json unmarshal. If there's any slight mismatch in the type, json.unmarshal will immediately panic. I want to be able to validate the type as well.

答: We've used go-playground/validator.v8 for a similar purpose. You can define the data validations with the tags that come out of the box (basic stuff like equality, min/max and even has somthing of an expression lang). On top of that you can add your custom validations. It's all in the docs, hope it helps.</p>

Body:
I'm using Beego framework to build a web application in Go. I have to validate the incoming JSON in an API request.

I can unmarshal the JSON into a struct which works fine, but I want to validate the data as well. For example, if the type doesn't match with the type in struct json.Unmarshal will reutrn an error on the first occurence. I want to validate and get all the errors at once for JSON.

I've tried https://github.com/thedevsaddam/govalidator but the package needs a reference to request object which is not available in the controller of Beego. There are other validators which can validate a struct but i want the json validation as well.

EDIT:

A reference to the request object in beego can be found from the controller's context object as:

func (this *MainController) Post() {
    fmt.Println(this.Ctx.Request)
}

But the problem remains same with json unmarshal. If there's any slight mismatch in the type, json.unmarshal will immediately panic. I want to be able to validate the type as well.


问:
Styling what's shipped in the slot element
My request is weird, since I used another approach that totally worked and is way more clean. However, SEO called and told me, my kind of structure isn't really googlebot-friendly.

So here is the situation (please don't judge it, I know there are other ways to do what I try to achieve, by not using childfragments at all):

This is my component:

```<code>class Container extends LitElement {
  static get tagName() {
    return 'container';
  }

  static get styles() {
    return css`
      ${unsafeCSS(styles)}
    `;
  }

  render() {
    return html`
      <article class="o-container">
        <slot></slot>
      </article>
    `;
  }
}

defineOnce(Container.tagName, Container);

export default Container;
</code>```

This is how I use it:

```<code>  <footer>
    <div class="o-footer__collection">
      <div class="o-footer__main">
        <h1 class="o-footer__title-desktop">
          me & me
        </h1>
        <button
          class="o-footer__accordion-button"
        >
          <h1 class="o-footer__title">
            you & you
          </h1>
          <span
            class="o-footer__accordion-button-caret o-footer__accordion-button-caret--open"
          >
            blabla
          </span>
        </button>
        <ul
          class="o-footer__main-content-panel o-footer__main-content-panel--open"
        >
          <li
            class="o-footer__main-content-panel-list-item"
          >
            <a
              href="https://google.com"
              target="_blank"
              >Contact</a
            >
          </li>
        </ul>
      </div>
  </footer>
</code>```

You see, all those children land within the slot area of the component. Initially, those children were part of the component and had a styling. Now they are outside of it and the styling no longer gets applied. Does anyone know how to get around this problem? I found in the docs, that you could use the ::slotted() css attribute, but apparently that one doesn't seem to work. Or did I probably do something else wrong? I also tried to put the style-tag into the render html, but that only has minor impacts.

I don't know which route I should focus on. Any help is appreciated. IMHO the styling should be part of the component itself and not up to the guy using the component. But that slot element broke everything, although the rest of the structure is still the same.

答:
The ::slotted syntax will work with a disclaimer I will explain after this. If you want all text inside p tags within your slot to be green the syntax would be:

```<code>::slotted(p) {
  color: green;
}
</code>```

The disclaimer is that this is not part of the ShadowDom so it is not protected. i.e., the host document can still override the css. Elements inside the slot are considered to be in the "light DOM".

To have control over the elements inside the slot you can approach this using one of the lifecycle events. For example:

```<code>firstUpdated(changedProperties) {
    requestAnimationFrame(() => {
      const paras = document.querySelector("test-element").querySelectorAll('p');

      [].forEach.call(paras, (e)=>{
        e.style.color = "green";
      });
});
</code>```

Inside the firstUpdated handler you can programmatically style the slot contents. Not the requestAnimation frame. I reference the following gitHub discussion for this https://github.com/Polymer/lit-html/issues/338. The context of that discussion is a web component inside the slot of another web component, but I think it may be good practice to do this because the slot elements may not be fully rendered when the custom component firstUpdated gets fired.

Body:
My request is weird, since I used another approach that totally worked and is way more clean. However, SEO called and told me, my kind of structure isn't really googlebot-friendly.

So here is the situation (please don't judge it, I know there are other ways to do what I try to achieve, by not using childfragments at all):

This is my component:

class Container extends LitElement {
  static get tagName() {
    return 'container';
  }

  static get styles() {
    return css`
      ${unsafeCSS(styles)}
    `;
  }

  render() {
    return html`

        <slot></slot>

    `;
  }
}

defineOnce(Container.tagName, Container);

export default Container;

This is how I use it:

          me & me

        <button
          class="o-footer__accordion-button"
        >

            you & you

            blabla

        </button>

            Contact

You see, all those children land within the slot area of the component. Initially, those children were part of the component and had a styling. Now they are outside of it and the styling no longer gets applied. Does anyone know how to get around this problem? I found in the docs, that you could use the ::slotted() css attribute, but apparently that one doesn't seem to work. Or did I probably do something else wrong? I also tried to put the style-tag into the render html, but that only has minor impacts.

I don't know which route I should focus on. Any help is appreciated. IMHO the styling should be part of the component itself and not up to the guy using the component. But that slot element broke everything, although the rest of the structure is still the same.

Body:
The ::slotted syntax will work with a disclaimer I will explain after this. If you want all text inside p tags within your slot to be green the syntax would be:

::slotted(p) {
  color: green;
}

The disclaimer is that this is not part of the ShadowDom so it is not protected. i.e., the host document can still override the css. Elements inside the slot are considered to be in the "light DOM".

To have control over the elements inside the slot you can approach this using one of the lifecycle events. For example:

firstUpdated(changedProperties) {
    requestAnimationFrame(() => {
      const paras = document.querySelector("test-element").querySelectorAll('p');

      [].forEach.call(paras, (e)=>{
        e.style.color = "green";
      });
});

Inside the firstUpdated handler you can programmatically style the slot contents. Not the requestAnimation frame. I reference the following gitHub discussion for this https://github.com/Polymer/lit-html/issues/338. The context of that discussion is a web component inside the slot of another web component, but I think it may be good practice to do this because the slot elements may not be fully rendered when the custom component firstUpdated gets fired.


问:
Enumerating the available keyboard layouts in Windows
Is it possible to enumerate all the currently available keyboard layouts. By available I mean  the user can switch to them by pressing Alt+Shift (or whatever his chosen shortcut is), i.e. they are in the Language Bar's menu.

Alternatively, checking if a specific layout is available in the Language Bar would also be useful.

Edit:

Many thanks to @oleg, I finally made a function that works:

```<code>bool IsActiveKeyboardLayout(DWORD dwPrimaryLangID)
{
    TCHAR buf[KL_NAMELENGTH];
    GetKeyboardLayoutName(buf);

    DWORD dwActiveLangID = 0;
    _stscanf(buf, _T("%X"), &dwActiveLangID);
    if (dwPrimaryLangID == PRIMARYLANGID(dwActiveLangID))
        return true;

    return false;
}

bool IsKeyboardLayoutPresent(DWORD dwPrimaryLangID)
{
    if (IsActiveKeyboardLayout(dwPrimaryLangID))
        return true;

    DWORD dwThreadID = GetCurrentThreadId();
    HKL hOld = GetKeyboardLayout(dwThreadID);
    for (;;)
    {
        ActivateKeyboardLayout((HKL) HKL_NEXT, 0);
        if (hOld == GetKeyboardLayout(dwThreadID))
            return false;

        if (IsActiveKeyboardLayout(dwPrimaryLangID))
        {
            ActivateKeyboardLayout(hOld, 0);
            return true;
        }
    }
}
</code>```

答:
The function GetKeyboardLayoutList seems get most close information to what you need. The returned information is the array of HKL, the HANDLE has values like

0x04070407 - German
0x04110411 - Japanese
0x04190419 - Russian
0xe0200411 - Japanese

If you have for some language more as one input methods or more as one layout for one language you can have more items as you can see in the language bar menu. On 64-bit operation system the value 0x04070407 will be represented as 0x0000000004070407.

Here you can read more about the input locale identifier and keyboard layouts.

Body:
Is it possible to enumerate all the currently available keyboard layouts. By available I mean  the user can switch to them by pressing Alt+Shift (or whatever his chosen shortcut is), i.e. they are in the Language Bar's menu.

Alternatively, checking if a specific layout is available in the Language Bar would also be useful.

Edit:

Many thanks to @oleg, I finally made a function that works:

bool IsActiveKeyboardLayout(DWORD dwPrimaryLangID)
{
    TCHAR buf[KL_NAMELENGTH];
    GetKeyboardLayoutName(buf);

    DWORD dwActiveLangID = 0;
    _stscanf(buf, _T("%X"), &dwActiveLangID);
    if (dwPrimaryLangID == PRIMARYLANGID(dwActiveLangID))
        return true;

    return false;
}

bool IsKeyboardLayoutPresent(DWORD dwPrimaryLangID)
{
    if (IsActiveKeyboardLayout(dwPrimaryLangID))
        return true;

    DWORD dwThreadID = GetCurrentThreadId();
    HKL hOld = GetKeyboardLayout(dwThreadID);
    for (;;)
    {
        ActivateKeyboardLayout((HKL) HKL_NEXT, 0);
        if (hOld == GetKeyboardLayout(dwThreadID))
            return false;

        if (IsActiveKeyboardLayout(dwPrimaryLangID))
        {
            ActivateKeyboardLayout(hOld, 0);
            return true;
        }
    }
}


问:
str.translate vs str.replace - When to use which one?
When and why to use the former instead of the latter and vice versa?

It is not entirely clear why some use the former and why some use the latter.

答:
They serve different purposes.

translate can only replace single characters with arbitrary strings, but a single call can perform multiple replacements. Its argument is a special table that maps single characters to arbitrary strings.

replace can only replace a single string, but that string can have arbitrary length.

```<code>>>> table = str.maketrans({'f': 'b', 'o': 'r'})
>>> table
{102: 'b', 111: 'r'}
>>> 'foo'.translate(table)
'brr'
>>> 'foo'.translate(str.maketrans({'fo': 'ff'}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: string keys in translate table must be of length 1
>>> 'foo'.replace('fo', 'ff')
'ffo'
</code>```

Body:
They serve different purposes.

translate can only replace single characters with arbitrary strings, but a single call can perform multiple replacements. Its argument is a special table that maps single characters to arbitrary strings.

replace can only replace a single string, but that string can have arbitrary length.

>>> table = str.maketrans({'f': 'b', 'o': 'r'})
>>> table
{102: 'b', 111: 'r'}
>>> 'foo'.translate(table)
'brr'
>>> 'foo'.translate(str.maketrans({'fo': 'ff'}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: string keys in translate table must be of length 1
>>> 'foo'.replace('fo', 'ff')
'ffo'


问:
Why does it always return true?
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

```<code>if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}
</code>```

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

答:
In Javascript there's something called truthy and falsy values. In summary, is how a value evaluates in a Boolean (true or false) context.

All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

In your code, when you wrote:

```<code>if (firstSymbol === "A" || "a" || "D" || "d")
</code>```

You are checking 4 boolean conditions:

firstSymbol === "A" - The result will depend on firstSymbol

"a" - Will always evaluate to true

"D" - Will always evaluate to true

"d" - Will always evaluate to true

So, since conditions 2, 3 and 4 will always be true, your code will always enter the if statement. If even a single one of these would be true the behaviour would be the same.

You can rewrite it in some ways:

```<code>if (firstSymbol === "A" || firstSymbol === "a" || firstSymbol === "D" || firstSymbol === "d")
</code>```

or

```<code>if (["A", "a", "D", "d"].indexOf(firstSymbol) > -1)
</code>```

or

```<code>if (["A", "D"].indexOf(firstSymbol.toUpperCase()) > -1)
</code>```

Title: Why does it always return true?

Body:
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

Body:
In Javascript there's something called truthy and falsy values. In summary, is how a value evaluates in a Boolean (true or false) context.

All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

In your code, when you wrote:

if (firstSymbol === "A" || "a" || "D" || "d")

You are checking 4 boolean conditions:

firstSymbol === "A" - The result will depend on firstSymbol

"a" - Will always evaluate to true

"D" - Will always evaluate to true

"d" - Will always evaluate to true

So, since conditions 2, 3 and 4 will always be true, your code will always enter the if statement. If even a single one of these would be true the behaviour would be the same.

You can rewrite it in some ways:

if (firstSymbol === "A" || firstSymbol === "a" || firstSymbol === "D" || firstSymbol === "d")

or

if (["A", "a", "D", "d"].indexOf(firstSymbol) > -1)

or

if (["A", "D"].indexOf(firstSymbol.toUpperCase()) > -1)


问:
How to add a few layers before the model in transfer learning with tensorflow
I am trying to use transfer learning in tensorflow. I know the high level paradigm

```<code>base_model=MobileNet(weights='imagenet',include_top=False) #imports the

mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(120,activation='softmax')(x) #final layer with softmax activation
</code>```

and then one compiles it by

```<code>model=Model(inputs=base_model.input,outputs=preds)
</code>```

However i want the there to be a few other layers before the base_model.input. I want to add adversarial noise to the images that come in and a few other things. So effectively i want to know how to :

```<code>base_model=MobileNet(weights='imagenet',include_top=False) #imports the

mobilenet model and discards the last 1000 neuron layer

x = somerandomelayers(x_in)
base_model.input = x_in
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(120,activation='softmax')(x) #final layer with softmax activation
model=Model(inputs=x_in,outputs=preds)
</code>```

but the line base_model.input = x_in is apparently not the way to do it as it throws can't set attribute error. How do i go about achieving the desired behavior?

答:
You need to define input layer. It's rather straightforward, just be sure to set right shapes. For example, you can use any predefined model from Keras.

base_model = keras.applications.any_model(...)
input_layer = keras.layers.Input(shape)
x = keras.layers.Layer(...)(input_layer)
...
x = base_model(x)
...
output = layers.Dense(num_classes, activation)(x)
model = keras.Model(inputs=input_layer, outputs=output)
```

Body:
I am trying to use transfer learning in tensorflow. I know the high level paradigm

base_model=MobileNet(weights='imagenet',include_top=False) #imports the

mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(120,activation='softmax')(x) #final layer with softmax activation

and then one compiles it by

model=Model(inputs=base_model.input,outputs=preds)

However i want the there to be a few other layers before the base_model.input. I want to add adversarial noise to the images that come in and a few other things. So effectively i want to know how to :

base_model=MobileNet(weights='imagenet',include_top=False) #imports the

mobilenet model and discards the last 1000 neuron layer

x = somerandomelayers(x_in)
base_model.input = x_in
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(120,activation='softmax')(x) #final layer with softmax activation
model=Model(inputs=x_in,outputs=preds)

but the line base_model.input = x_in is apparently not the way to do it as it throws can't set attribute error. How do i go about achieving the desired behavior?


问:
Need to run a stored procedure on all non system databases
I'm trying to loop through all non system databases and run a stored procedure. This stored procedure exists in all of the user databases.

This is what I have found so far:

```<code>DECLARE @command varchar(1000)
SELECT @command = 'USE ? SELECT name FROM sysobjects WHERE xtype = ''U'' ORDER BY name'

USE @command;
GO

EXECUTE Support.CleanIndiciesAndShrinkDatabase;
GO
</code>```

I get an error this error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near '@command'.

Msg 2812, Level 16, State 62, Line 1

  Could not find stored procedure 'Support.CleanIndiciesAndShrinkDatabase'.

Any suggestions on fixing this?

答:
You can try this:</p>

```<code>Create PROC PROC_NAME
AS
BEGIN
DECLARE @name nvarchar(50)
declare @cursor cursor
set @cursor = CURSOR FAST_FORWARD FOR select name from sys.databases where database_id > 4

open @cursor

FETCH NEXT FROM @cursor INTO @name

WHILE @@FETCH_STATUS = 0

BEGIN

DECLARE @use nvarchar(50) = 'USE '

SET @use = @use + @name

Declare @query nvarchar(max) = @use + ' exec Your_PROC'

EXEC sp_executesql  @query

FETCH NEXT FROM @cursor INTO @name

END

CLOSE @cursor

DEALLOCATE @cursor

END
</code>```

Body:
I'm trying to loop through all non system databases and run a stored procedure. This stored procedure exists in all of the user databases.

This is what I have found so far:

DECLARE @command varchar(1000)
SELECT @command = 'USE ? SELECT name FROM sysobjects WHERE xtype = ''U'' ORDER BY name'

USE @command;
GO

EXECUTE Support.CleanIndiciesAndShrinkDatabase;
GO

I get an error this error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near '@command'.

Msg 2812, Level 16, State 62, Line 1

  Could not find stored procedure 'Support.CleanIndiciesAndShrinkDatabase'.

Any suggestions on fixing this?

Body:
You can try this:

Create PROC PROC_NAME
AS
BEGIN
DECLARE @name nvarchar(50)
declare @cursor cursor
set @cursor = CURSOR FAST_FORWARD FOR select name from sys.databases where database_id > 4

open @cursor

FETCH NEXT FROM @cursor INTO @name

WHILE @@FETCH_STATUS = 0

BEGIN

DECLARE @use nvarchar(50) = 'USE '

SET @use = @use + @name

Declare @query nvarchar(max) = @use + ' exec Your_PROC'

EXEC sp_executesql  @query

FETCH NEXT FROM @cursor INTO @name

END

CLOSE @cursor

DEALLOCATE @cursor

END


问:
How to get key value from a nested hash with escape characters
I'm trying to get some key/values from a hash but haven't figured out the best way to do it. Also, I then need to put the results in a table with the keys as column headers.

I tried map, select and dig but I just get various errors.

```<code>require 'json'

json_hash = {:results=>["{\"resourceId\":\"i-5ee33\",\"configuration\":{\"instanceType\":\"m4.2xlarge\"},\"tags\":[{\"tag\":\"aws:au\\u003db\",\"value\":\"b-1a\",\"key\":\"awsss\"},{\"tag\":\"Kernluster\\ulues\",\"value\":\"blu\",\"key\":\"Kster\"},{\"tag\":\"Kuole\\udter\",\"value\":\"master\",\"key\":\"Kule\"},{\"tag\":\"Name\\uwest-1a\",\"value\":\"st-1a\",\"key\":\"Name\"}]}"], :query_info=>{:select_fields=>[{:name=>"[FILTERED]"}, {:name=>"[FILTERED]"}, {:name=>"[FILTERED]"}]}, :next_token=>"YwutZrD0Ow9Qh3HoYbiC"}

keys_to_extract = ['resourceId', 'instanceType', 'tags']
x = json_hash.map do |w|
  w.select { |k,_| keys_to_extract.include? k }
end

puts x
</code>```

No error results shown.

答:
Most of the contents are still in a JSON string. You need to parse them in order for Ruby to access them:

```<code>json_hash[:results].map! { |str| JSON.parse(str) }
</code>```

Though I hope you have a typo there because the JSON is invalid. A \u is supposed to be followed by 4 hexadecimal digits, but you have

```<code>{"tag":"Name\uwest-1a","value":"st-1a","key":"Name"}
</code>```

which is gibberish.

Body:
I'm trying to get some key/values from a hash but haven't figured out the best way to do it. Also, I then need to put the results in a table with the keys as column headers.

I tried map, select and dig but I just get various errors.

require 'json'

json_hash = {:results=>["{\"resourceId\":\"i-5ee33\",\"configuration\":{\"instanceType\":\"m4.2xlarge\"},\"tags\":[{\"tag\":\"aws:au\\u003db\",\"value\":\"b-1a\",\"key\":\"awsss\"},{\"tag\":\"Kernluster\\ulues\",\"value\":\"blu\",\"key\":\"Kster\"},{\"tag\":\"Kuole\\udter\",\"value\":\"master\",\"key\":\"Kule\"},{\"tag\":\"Name\\uwest-1a\",\"value\":\"st-1a\",\"key\":\"Name\"}]}"], :query_info=>{:select_fields=>[{:name=>"[FILTERED]"}, {:name=>"[FILTERED]"}, {:name=>"[FILTERED]"}]}, :next_token=>"YwutZrD0Ow9Qh3HoYbiC"}

keys_to_extract = ['resourceId', 'instanceType', 'tags']
x = json_hash.map do |w|
  w.select { |k,_| keys_to_extract.include? k }
end

puts x

No error results shown.

Body:
Most of the contents are still in a JSON string. You need to parse them in order for Ruby to access them:

json_hash[:results].map! { |str| JSON.parse(str) }

Though I hope you have a typo there because the JSON is invalid. A \u is supposed to be followed by 4 hexadecimal digits, but you have

{"tag":"Name\uwest-1a","value":"st-1a","key":"Name"}

which is gibberish.


问:
If I install a package with pip in a Python 3 environment is that package guaranteed to be Python 3 compatible?
I have a Python 3 environment, everything is working correctly and as expected, i.e.:

```<code>$ python --version
Python 3.6.8

$ pip --version
pip 18.1 from /Users/user/.pyenv/versions/3.6.8/envs/myenv/lib/python3.6/site-packages/pip (python 3.6)
</code>```

I am porting a Python 2 project to Python 3. I have the requirements.txt file from my Python 2 project - if I install these dependences in my Python 3 environment, e.g.

```<code>$ pip install -r my_python2_requirements.txt
</code>```

And that completes successfully am I guaranteede that all of my dependencies are Python 3 compatible?

Or to put it another way: Is it possible to install a Python 2 only package with Python 3/pip (i.e. a package that will not work).

答:
I'm not entirely certain about this, so I ran the following test.

I selected a random module from PyPi which was marked 'Python 2 only' and tried to install it on both versions. For my test I used patchit.

The pip command hit the same URL, and the pip3 call even detected and used the cached tar.gz file. So it would seem that pip does not offer the protection you wish for. (Of course for packages that support both 2 and 3, it should install the corresponding version)

From the official transition guide:

Use caniusepython3 to find out which of your dependencies are blocking your use of Python 3 (pip install caniusepython3)

That should help determine things and modify the requirements.txt as needed.

Body:
I have a Python 3 environment, everything is working correctly and as expected, i.e.:

$ python --version
Python 3.6.8

$ pip --version
pip 18.1 from /Users/user/.pyenv/versions/3.6.8/envs/myenv/lib/python3.6/site-packages/pip (python 3.6)

I am porting a Python 2 project to Python 3. I have the requirements.txt file from my Python 2 project - if I install these dependences in my Python 3 environment, e.g.

$ pip install -r my_python2_requirements.txt

And that completes successfully am I guaranteede that all of my dependencies are Python 3 compatible?

Or to put it another way: Is it possible to install a Python 2 only package with Python 3/pip (i.e. a package that will not work).


问:
How to use current exchange and queue name of rabbitmq with spring cloud stream rabbitmq
I'm switching legacy spring application to spring boot.

There is an issue with migrating rabbitmq code using spring cloud stream rabbitmq.

In the legacy system, rabbitmq queue is set up by giving exchange, routingKey and queue name.

For instance,

```<code>exchange name = mq-test.topic
routingKey = mq-test
queueName = aa.mq-test
</code>```

So in rabbitmq management view I can see that
exchange is mq-test.topic, queue is aa.mq-test.

But with spring cloud stream, queue name is dotted with destination like

mq-test.topic.aa.mq-test

My properties for spring cloud stream is like this.

```<code>spring.cloud.stream.bindings.channelName.destination=mq-test.topic
spring.cloud.stream.bindings.channelName.producer.bindingRoutingKey=mq-test
spring.cloud.stream.bindings.channelName.producer.requiredGroups=aa.mq-test
</code>```

I also used routingKeyExpression property on behalf of bindingRoutingKey but the result is the same.

There are legacy applications consuming the data via the queue names and my new application is only producing so I can't change the exchange and queue name policy.

How can I keep the exchange/queue naming with spring cloud stream?

any help is appreciated.

答:
See the RabbitMQ Binder documentation Using Existing Queues/Exchanges.

By default, the binder will automatically provision a topic exchange with the name being derived from the value of the destination binding property . The destination defaults to the binding name, if not provided. When binding a consumer, a queue will automatically be provisioned with the name . (if a group binding property is specified), or an anonymous, auto-delete queue when there is no group. The queue will be bound to the exchange with the "match-all" wildcard routing key (#) for a non-partitioned binding or - for a partitioned binding. The prefix is an empty String by default. If an output binding is specified with requiredGroups, a queue/binding will be provisioned for each group.

There are a number of rabbit-specific binding properties that allow you to modify this default behavior.

If you have an existing exchange/queue that you wish to use, you can completely disable automatic provisioning as follows, assuming the exchange is named myExchange and the queue is named myQueue:

spring.cloud.stream.binding.<binding name>.destination=myExhange

spring.cloud.stream.binding.<binding name>.group=myQueue

spring.cloud.stream.rabbit.bindings.<binding name>.consumer.bindQueue=false

spring.cloud.stream.rabbit.bindings.<binding name>.consumer.declareExchange=false

spring.cloud.stream.rabbit.bindings.<binding name>.consumer.queueNameGroupOnly=true

...

Body:
I'm switching legacy spring application to spring boot.

There is an issue with migrating rabbitmq code using spring cloud stream rabbitmq.

In the legacy system, rabbitmq queue is set up by giving exchange, routingKey and queue name.

For instance,

exchange name = mq-test.topic
routingKey = mq-test
queueName = aa.mq-test

So in rabbitmq management view I can see that
exchange is mq-test.topic, queue is aa.mq-test.

But with spring cloud stream, queue name is dotted with destination like

mq-test.topic.aa.mq-test

My properties for spring cloud stream is like this.

spring.cloud.stream.bindings.channelName.destination=mq-test.topic
spring.cloud.stream.bindings.channelName.producer.bindingRoutingKey=mq-test
spring.cloud.stream.bindings.channelName.producer.requiredGroups=aa.mq-test

I also used routingKeyExpression property on behalf of bindingRoutingKey but the result is the same.

There are legacy applications consuming the data via the queue names and my new application is only producing so I can't change the exchange and queue name policy.

How can I keep the exchange/queue naming with spring cloud stream?

any help is appreciated.


问:
How to Generate Matching MD5 Hash: SQL Server nvarchar Field vs. ColdFusion
I am trying to figure out how to generate a matching MD 5 hash value between SQL Server and ColdFusion. The root cause appears to be that the SQL Server field is an nvarchar datatype, which seems to mean I need to do something with the encoding of the string I would hash in ColdFusion or Java to make it match, but I am unable to figure it out. To be clear if this was a SQL Server varchar field, everything works.

Here's the code I'm trying:

```<code><cfset stringToHash = "Hello world!">

<cfquery name="sqlserver" datasource="#mySqlServerDSN#">
    SELECT RIGHT(
    master.dbo.fn_varbintohexstr(
        HashBytes(
            'MD5',
            CAST(<cfqueryparam value="#stringToHash#" cfsqltype="cf_sql_varchar">  AS nvarchar(max))
        )
    )
   , 32) AS HASHED
</cfquery>

<cfoutput>
```
CF UFT-8:   #hash(stringToHash, 'MD5', 'UTF-8')#
CF UFT-16:  #hash(stringToHash, 'MD5', 'UTF-16')#
SQL Server: #sqlserver.hashed#
```
</cfoutput>
</code>```

Produces

```<code>CF UTF-8:   86FB269D190D2C85F6E0468CECA42A20
CF UTF-16:  0C89A9720D83539E3723BB99C07D069F
SQL Server: f9a6119c6ec37ce652960382f8b59f2c
</code>```

So I'm guessing I need to change the final argument I'm passing to hash() to be a different encoding, but I can't figure it out. I've also tagged this question as Java too, because I'm more than happy to take an answer in that language as well.

答:
By default SQL Server uses the UTF-16 in little-endian byte order character set for nvarchar fields.
In ColdFusion you must use the 'UTF-16LE' character set.</p>

```<code><cfscript>
    helloWorld = "Hello, World!";
    utf8HashCF = lcase(hash(helloWorld, 'MD5', 'UTF-16LE'));
</cfscript>
<cfoutput>
    #utf8HashCF# <br />
</cfoutput>
</code>```

Body:
I am trying to figure out how to generate a matching MD 5 hash value between SQL Server and ColdFusion. The root cause appears to be that the SQL Server field is an nvarchar datatype, which seems to mean I need to do something with the encoding of the string I would hash in ColdFusion or Java to make it match, but I am unable to figure it out. To be clear if this was a SQL Server varchar field, everything works.

Here's the code I'm trying:

<cfset stringToHash = "Hello world!">

<cfquery name="sqlserver" datasource="#mySqlServerDSN#">
    SELECT RIGHT(
    master.dbo.fn_varbintohexstr(
        HashBytes(
            'MD5',
            CAST(<cfqueryparam value="#stringToHash#" cfsqltype="cf_sql_varchar">  AS nvarchar(max))
        )
    )
   , 32) AS HASHED
</cfquery>

<cfoutput>

CF UFT-8:   #hash(stringToHash, 'MD5', 'UTF-8')#
CF UFT-16:  #hash(stringToHash, 'MD5', 'UTF-16')#
SQL Server: #sqlserver.hashed#

</cfoutput>

Produces

CF UTF-8:   86FB269D190D2C85F6E0468CECA42A20
CF UTF-16:  0C89A9720D83539E3723BB99C07D069F
SQL Server: f9a6119c6ec37ce652960382f8b59f2c

So I'm guessing I need to change the final argument I'm passing to hash() to be a different encoding, but I can't figure it out. I've also tagged this question as Java too, because I'm more than happy to take an answer in that language as well.

Body:
By default SQL Server uses the UTF-16 in little-endian byte order character set for nvarchar fields.
In ColdFusion you must use the 'UTF-16LE' character set.

<cfscript>
    helloWorld = "Hello, World!";
    utf8HashCF = lcase(hash(helloWorld, 'MD5', 'UTF-16LE'));
</cfscript>
<cfoutput>
    #utf8HashCF# <br />
</cfoutput>


问:
How to run geth without console?
I need run geth on server without console. How to do this? just not add argument console?

And can I attach to geth running without console, when I want to stop geth, or open console.

答: If you append an '&' at the end of your geth <args> & command, it will run the command as a separate process in the background. Then you should be able to connect to it with geth attach from a separate console to stop or modify it.

Title: How to run geth without console?


问:
How to get label text from web table
I'm facing the problem with finding label text from table
I'm new to Selenium, help me understand what I'm doing wrong.
Thanks in advance

WebElement services = driver.findElement(By.xpath("//tr[@id='mr_2']/label"));
String strServices = services.getText();
System.out.println(strServices);
```

```

Menu Selection
Poor
<input id="element_2_1" name="element_2" type="radio" value="1">

```

答:
Try changing the below line </p>

```<code>String strServices = services.getText();
</code>```

<p>to </p>

```<code>String strServices = services.getAttribute("textContent");
</code>```

Title: How to get label text from web table

Body:
I'm facing the problem with finding label text from table
I'm new to Selenium, help me understand what I'm doing wrong.
Thanks in advance

WebElement services = driver.findElement(By.xpath("//tr[@id='mr_2']/label"));
String strServices = services.getText();
System.out.println(strServices);

Menu Selection
Poor
<input id="element_2_1" name="element_2" type="radio" value="1">

Body:
Try changing the below line

String strServices = services.getText();

to

String strServices = services.getAttribute("textContent");


问:
Laravel "universal to" in development vs production
I'm working with a Laravel 5.2 application.  In my development and staging environments, I'd like to make use of the "Universal To" mail config option described in the docs.  A universal to in development environments ensures all emails go to that address, instead of out to real customers/clients/whatever.

I can't work out how to specify this differently in production though.  In production there should be no universal to - emails should go out to real addresses.

The standard approach of using different env() values does not seem to work.  For example:

config/mail.php:

```<code>'to' => [
    'address'   => env('UNIVERSAL_TO', false)
],
</code>```

development .env:

```<code>UNIVERSAL_TO=my-testing-address@somewhere.com
</code>```

This works fine - all emails go to the specified UNIVERSAL_TO, as expected.  But if I change that to what I will want in production, eg:

production .env

```<code>UNIVERSAL_TO=
</code>```

(or ='', or =false, or simply omitting this completely), sending any mail fails with (in storage/laravel.log):

local.ERROR: exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [] does not comply with RFC 2822, 3.6.2.' in path/to/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php:348

config/mail.php is just returning an array, so I suppose I could instead set it as a variable and then depending on environment append the 'to' to it, like so:

```<code>$return = [ ... normal mail config array ... ];

if (!\App::environment('production')) {
    $return['to'] => [
        'address' => 'my-testing-address@somewhere.com'
    ];
}

return $return;
</code>```

But this seems a little ... hacky.  Is there a better way?

答:
I stumbled on this issue when googling for this behaviour. Since the answers aren't perfect, I decided to add my results.

If it ever was broken, it seems this has been fixed now. When omitting the UNIVERSAL_TO in your .env file, the Mail will just be sent to the designated recipient.

Perhaps the issue was that you didn't have a null value, but false as default.

config/mail.php

    'to' => [
        'address' => env('MAIL_GLOBAL_RECIPIENT'), // when not found, defaults to null
        'name' => 'Developer'
    ],
```

<p>local .env</p>

```MAIL_GLOBAL_RECIPIENT=my@email.com
```

production .env doesn't even have that variable

Body:
I'm working with a Laravel 5.2 application.  In my development and staging environments, I'd like to make use of the "Universal To" mail config option described in the docs.  A universal to in development environments ensures all emails go to that address, instead of out to real customers/clients/whatever.

I can't work out how to specify this differently in production though.  In production there should be no universal to - emails should go out to real addresses.

The standard approach of using different env() values does not seem to work.  For example:

config/mail.php:

'to' => [
    'address'   => env('UNIVERSAL_TO', false)
],

development .env:

UNIVERSAL_TO=my-testing-address@somewhere.com

This works fine - all emails go to the specified UNIVERSAL_TO, as expected.  But if I change that to what I will want in production, eg:

production .env

UNIVERSAL_TO=

(or ='', or =false, or simply omitting this completely), sending any mail fails with (in storage/laravel.log):

local.ERROR: exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [] does not comply with RFC 2822, 3.6.2.' in path/to/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php:348

config/mail.php is just returning an array, so I suppose I could instead set it as a variable and then depending on environment append the 'to' to it, like so:

$return = [ ... normal mail config array ... ];

if (!\App::environment('production')) {
    $return['to'] => [
        'address' => 'my-testing-address@somewhere.com'
    ];
}

return $return;

But this seems a little ... hacky.  Is there a better way?

Body:
I stumbled on this issue when googling for this behaviour. Since the answers aren't perfect, I decided to add my results.

If it ever was broken, it seems this has been fixed now. When omitting the UNIVERSAL_TO in your .env file, the Mail will just be sent to the designated recipient.

Perhaps the issue was that you didn't have a null value, but false as default.

config/mail.php

    'to' => [
        'address' => env('MAIL_GLOBAL_RECIPIENT'), // when not found, defaults to null
        'name' => 'Developer'
    ],

local .env

MAIL_GLOBAL_RECIPIENT=my@email.com

production .env doesn't even have that variable


问:
Flutter StreamBuilder vs FutureBuilder
What is the main difference between StreamBuilder and FutureBuilder.

What to use and when to use?

What are the tasks they are intended to perform?

How each of them listens to changes in a dynamic list?

答:
FutureBuilder is used for one time response, like taking an image from Camera, getting data once from native platform (like fetching device battery), getting file reference, making an http request etc.

On the other hand, StreamBuilder is used for fetching some data more than once, like listening for location update, playing a music, stopwatch, etc.

Here is full example mentioning both cases.

FutureBuilder solves a square value and returns the result after 5 seconds, till then we show progress indicator to the user.

StreamBuilder shows a stopwatch, incrementing _count value by 1 every second.

```<code>void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _count = 0; // used by StreamBuilder

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _buildFutureBuilder(),
          SizedBox(height: 24),
          _buildStreamBuilder(),
        ],
      ),
    );
  }

  // constructing FutureBuilder
  Widget _buildFutureBuilder() {
    return Center(
      child: FutureBuilder<int>(
        future: _calculateSquare(10),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done)
            return Text("Square = ${snapshot.data}");

          return CircularProgressIndicator();
        },
      ),
    );
  }

  // used by FutureBuilder
  Future<int> _calculateSquare(int num) async {
    await Future.delayed(Duration(seconds: 5));
    return num * num;
  }

  // constructing StreamBuilder
  Widget _buildStreamBuilder() {
    return Center(
      child: StreamBuilder<int>(
        stream: _stopwatch(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active)
            return Text("Stopwatch = ${snapshot.data}");

          return CircularProgressIndicator();
        },
      ),
    );
  }

  // used by StreamBuilder
  Stream<int> _stopwatch() async* {
    while (true) {
      await Future.delayed(Duration(seconds: 1));
      yield _count++;
    }
  }
}
</code>```

Title: Flutter StreamBuilder vs FutureBuilder

Body:
FutureBuilder is used for one time response, like taking an image from Camera, getting data once from native platform (like fetching device battery), getting file reference, making an http request etc.

On the other hand, StreamBuilder is used for fetching some data more than once, like listening for location update, playing a music, stopwatch, etc.

Here is full example mentioning both cases.

FutureBuilder solves a square value and returns the result after 5 seconds, till then we show progress indicator to the user.

StreamBuilder shows a stopwatch, incrementing _count value by 1 every second.

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _count = 0; // used by StreamBuilder

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _buildFutureBuilder(),
          SizedBox(height: 24),
          _buildStreamBuilder(),
        ],
      ),
    );
  }

  // constructing FutureBuilder
  Widget _buildFutureBuilder() {
    return Center(
      child: FutureBuilder<int>(
        future: _calculateSquare(10),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done)
            return Text("Square = ${snapshot.data}");

          return CircularProgressIndicator();
        },
      ),
    );
  }

  // used by FutureBuilder
  Future<int> _calculateSquare(int num) async {
    await Future.delayed(Duration(seconds: 5));
    return num * num;
  }

  // constructing StreamBuilder
  Widget _buildStreamBuilder() {
    return Center(
      child: StreamBuilder<int>(
        stream: _stopwatch(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active)
            return Text("Stopwatch = ${snapshot.data}");

          return CircularProgressIndicator();
        },
      ),
    );
  }

  // used by StreamBuilder
  Stream<int> _stopwatch() async* {
    while (true) {
      await Future.delayed(Duration(seconds: 1));
      yield _count++;
    }
  }
}


问:
why is my pam_userdb.so missing?
I want to use vsftpd to create a guest user , so I appended these to /etc/pam.d/vsftpd:

```<code>auth    required /lib64/security/pam_userdb.so db=/etc/vsftpd_virtual_accounts
account required /lib64/security/pam_userdb.so db=/etc/vsftpd_virtual_accounts
</code>```

But I can't find the pam_userdb.so file in /lib64/security and /lib/security.

And find / pam_userdb.so shows "no such file or directory".

How can I get the pam_userdb.so file?

答:
You don't need to specify the path; this is sufficient:

```<code>auth required pam_userdb.so db=/etc/vsftpd_virtual_accounts
</code>```

Your find command is incorrect; you need find / -name pam_userdb.so. Add -print -quit to stop on the first match.

On my system it's /lib/x86_64-linux-gnu/security/pam_userdb.so.

Title: why is my pam_userdb.so missing?

Body:
I want to use vsftpd to create a guest user , so I appended these to /etc/pam.d/vsftpd:

auth    required /lib64/security/pam_userdb.so db=/etc/vsftpd_virtual_accounts
account required /lib64/security/pam_userdb.so db=/etc/vsftpd_virtual_accounts

But I can't find the pam_userdb.so file in /lib64/security and /lib/security.

And find / pam_userdb.so shows "no such file or directory".

How can I get the pam_userdb.so file?

Body:
You don't need to specify the path; this is sufficient:

auth required pam_userdb.so db=/etc/vsftpd_virtual_accounts

Your find command is incorrect; you need find / -name pam_userdb.so. Add -print -quit to stop on the first match.

On my system it's /lib/x86_64-linux-gnu/security/pam_userdb.so.


问:
User connecting to Azure from On-Premise
Current Infrastructure Setup:

Site-to-Site connectivity between On premise and Azure using the Secured VPN Tunnel.

Implementing Azure ADFS for AD Solution.

Data accumulated on a specific location on on-premise which will be pushed to ADLS using ADF.

PowerBI reporting on top of ADLS.

Question:

Trying to understand on the user perspective, if the user is at On Premise location and trying to access the Data Lake and PowerBI report, how does the connection happens?

It is like this: users traffic from on-premise goes through VPN tunnel, then hits the Azure Gateway and it is forwarded to Data Lake and Power BI report is generated and the response travels back again in the same path.

If so then a question comes on scalability of the tunnel.

Can someone help me here?

答:
If the power BI got a external endpoint facing internet, All traffic from user will go through internet.

If your network team has added a rule if all the traffic has to go via VPN then it uses VPN tunnel.

"3. Data accumulated on a specific location on on-premise which will be pushed to ADLS using ADF." - It will uses the VPN tunnel for sure but for the user it may be via internet


问:
Swapping assemblies to implement DBMS-specific functionality
(continuation of my question here, but thought it was different enough to start a new thread)

I want to write an application that will allow the eventual customers to use their preferred DBMS (SQLServer, Oracle, etc) for the backend.

I could have the main app call a "Factory" object, located in a separate assembly, that will return a DBMS-specific object that implements a common interface containing all the calls required for DB access. However, this means having the compiled code for all possible DBMS systems deployed with every installation. The factory just chooses the configured assembly.

Could someone comment on this alternative method? : I could create separate assemblies for each DBMS that all use the same namespace e.g. MyDBMS, and implement the same interface. Upon installation, we'd only deploy the assembly for the customer's chosen DBMS. By changing the build configuration so that the assemblies all get the same name, COM ID, etc. then the main app wouldn't know the difference. I've tested this and it seems to work very well.

Just wondering about the pros/cons of this? The main benefit is that we could supply additional/updated DBMS DLLs without any other redeployment.

Thanks

答:
Ideally, and I suggested it in passing in your previous thread, go for something like nHibernate, an ORM tool.  In most situations where the database design does not deviate from the norm too much, this will work fine.  On some large-scale applications, basically ones with performance improvements in things like stored procedures, ORM tools will start to impose limitations.

You could look the other way and say that I support multiple databases by only using behaviour common across them all.

ADO.NET provides a series of interfaces that most major providers use: IDbCommand, IDbConnection, IDbTransaction.  The downside here is you usually cannot take advantage of provider-specific functionality or improvements.

The Data Access Application Block in Enterprise Library does this.  You could go this route, and if you encounter the need to have something specific, you could then change the EntLib code to support your application's specific requirement.

This way, you get the bulk of the logic done for you.  If you then hit problems (you might not) you then have access to the source code in order to address it.


问:
Why do my pods not fulfill the resource quota limits if the number match?
After applying the following ResourceQuota compute-resources to my GKE Cluster

```<code>apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-resources
spec:
  hard:
    limits.cpu: "1"
    limits.memory: 1Gi
</code>```

and updating a Deployment to

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-service
spec:
  selector:
    matchLabels:
      app: my-service
      tier: backend
      track: stable
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 50%
  template:
    metadata:
      labels:
        app: my-service
        tier: backend
        track: stable
    spec:
      containers:
        - name: my-service
          image: registry/namespace/my-service:latest
          ports:
            - name: http
              containerPort: 8080
          resources:
            requests:
              memory: "128Mi"
              cpu: "125m"
            limits:
              memory: "256Mi"
              cpu: "125m"
</code>```

the scheduling fails 100% of tries due to pods "my-service-5bc4c68df6-4z8wp" is forbidden: failed quota: compute-resources: must specify limits.cpu,limits.memory. Since limits and requests are specified and they fulfill the limit, I don't see a reason why the pods should be forbidden.

How pod limits resource on kubernetes enforced when the pod exceed limits after pods is created ? is a different question.

I upgraded my cluster to  1.13.6-gke.0.

答:
I was about to suggest to test within separate namespace, but see that you already tried.

As another workaround try to setup default limits by enabling LimitRanger admission controller and setting it up e.g.

```<code>apiVersion: v1
kind: LimitRange
metadata:
  name: cpu-limit-range
spec:
  limits:
  - default:
      memory: 256Mi
      cpu: 125m
    defaultRequest:
      cpu: 125m
      memory: 128Mi
    type: Container
</code>```

Now if a Container is created in the default namespace, and the Container does not specify its own values for CPU request and CPU limit, the Container is given a default CPU limits of 125m and a default memory limit of 256Mi

Also, after setting up LimitRange, make sure you removed your deployment and there are no pods stuck in failed state.

Body:
After applying the following ResourceQuota compute-resources to my GKE Cluster

apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-resources
spec:
  hard:
    limits.cpu: "1"
    limits.memory: 1Gi

and updating a Deployment to

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-service
spec:
  selector:
    matchLabels:
      app: my-service
      tier: backend
      track: stable
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 50%
  template:
    metadata:
      labels:
        app: my-service
        tier: backend
        track: stable
    spec:
      containers:
        - name: my-service
          image: registry/namespace/my-service:latest
          ports:
            - name: http
              containerPort: 8080
          resources:
            requests:
              memory: "128Mi"
              cpu: "125m"
            limits:
              memory: "256Mi"
              cpu: "125m"

the scheduling fails 100% of tries due to pods "my-service-5bc4c68df6-4z8wp" is forbidden: failed quota: compute-resources: must specify limits.cpu,limits.memory. Since limits and requests are specified and they fulfill the limit, I don't see a reason why the pods should be forbidden.

How pod limits resource on kubernetes enforced when the pod exceed limits after pods is created ? is a different question.

I upgraded my cluster to  1.13.6-gke.0.

Body:
I was about to suggest to test within separate namespace, but see that you already tried.

As another workaround try to setup default limits by enabling LimitRanger admission controller and setting it up e.g.

apiVersion: v1
kind: LimitRange
metadata:
  name: cpu-limit-range
spec:
  limits:
  - default:
      memory: 256Mi
      cpu: 125m
    defaultRequest:
      cpu: 125m
      memory: 128Mi
    type: Container

Now if a Container is created in the default namespace, and the Container does not specify its own values for CPU request and CPU limit, the Container is given a default CPU limits of 125m and a default memory limit of 256Mi

Also, after setting up LimitRange, make sure you removed your deployment and there are no pods stuck in failed state.


问:
Request from Firebase Hosting to Firebase Function blocked by CORS
I'm trying to send push notifications between two devices for a tiny prototype. Both of them are Vue.js apps with firebase SDK integrated, so to implement a push notification flow I deployed a firebase function, but when I call it from any of devices, a CORS error is received as a response.

Both devices (mobile and desktop) have the same client code and knows the token of each other (storage into a firebase real-time database).
The function only uses firebase messaging to send the push notification.

Firebase function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });

admin.initializeApp();

exports.notification = functions.https.onRequest((req, res) => {
    return cors(req, res, () => {
        if (req.method === "POST") {
            return admin.messaging().send(notification)
                .then(result => {
                    console.log(result);
                    res.status(200).send("ok")
                })
                .catch(err => res.status(500).send(err));
        } else {
            return res.status(400).send("Method not allowed");
        }
    });
});
```

<p>Client code:</p>

<pre class="lang-js prettyprint-override"><code>send(notification, token) {
    return fetch("https://[zone]-[project].cloudfunctions.net/notifications", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, notification })
    });
}

</code>```

And the error is:

```<code>Access to fetch at 'https://[zone]-[project].cloudfunctions.net/notifications' from origin 'https://[project].web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
</code>```

答:
Could you use The functions.https.onCall trigger?

See https://firebase.google.com/docs/functions/callable .

The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app.

Body:
I'm trying to send push notifications between two devices for a tiny prototype. Both of them are Vue.js apps with firebase SDK integrated, so to implement a push notification flow I deployed a firebase function, but when I call it from any of devices, a CORS error is received as a response.

Both devices (mobile and desktop) have the same client code and knows the token of each other (storage into a firebase real-time database).
The function only uses firebase messaging to send the push notification.

Firebase function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });

admin.initializeApp();

exports.notification = functions.https.onRequest((req, res) => {
    return cors(req, res, () => {
        if (req.method === "POST") {
            return admin.messaging().send(notification)
                .then(result => {
                    console.log(result);
                    res.status(200).send("ok")
                })
                .catch(err => res.status(500).send(err));
        } else {
            return res.status(400).send("Method not allowed");
        }
    });
});

Client code:

send(notification, token) {
    return fetch("https://[zone]-[project].cloudfunctions.net/notifications", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, notification })
    });
}

And the error is:

Access to fetch at 'https://[zone]-[project].cloudfunctions.net/notifications' from origin 'https://[project].web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.


问:
Swift class add "@objc" for why
Here's a link to a Swift tutorial.

I read the protocol section,i know if protocol is marked with the @objc:

```<code>@objc protocol CounterDataSource {
    optional func incrementForCount(count: Int) -> Int
    optional var fixedIncrement: Int { get }
}
</code>```

this mean this protocol in order to specify optional requirements and can be adopted only by classes

but tutorial didn't say why the class need to marked with the @objc too??

```<code>@objc class Counter {
    var count = 0
    var dataSource: CounterDataSource?
    func increment() {
      if let amount = dataSource?.incrementForCount?(count) {
        count += amount
      } else if let amount = dataSource?.fixedIncrement? {
        count += amount
      }
    }
}
</code>```

if i remove @objc from class , compiler didn't show error message too

so what different between add @objc to class or not?

答:
For example #selector is owned by Obj-c,

In swift, we'll use  #selector in .addTarget or in .target of an object. There we should prefix @objc for targeting method.

Example:

```<code>@objc func dummy(_ sender: UIButton) {
    print("xxx")
}
</code>```

above method will be using in a UIButton's target like

```<code>dummyButton.addTarget(self, action: #selector(self. dummy(_:)), for: .touchUpInside)
</code>```

this is why we are using @objc as prefix in swift.

Title: Swift class add "@objc" for why

Body:
Here's a link to a Swift tutorial.

I read the protocol section,i know if protocol is marked with the @objc:

@objc protocol CounterDataSource {
    optional func incrementForCount(count: Int) -> Int
    optional var fixedIncrement: Int { get }
}

this mean this protocol in order to specify optional requirements and can be adopted only by classes

but tutorial didn't say why the class need to marked with the @objc too??

@objc class Counter {
    var count = 0
    var dataSource: CounterDataSource?
    func increment() {
      if let amount = dataSource?.incrementForCount?(count) {
        count += amount
      } else if let amount = dataSource?.fixedIncrement? {
        count += amount
      }
    }
}

if i remove @objc from class , compiler didn't show error message too

so what different between add @objc to class or not?

Body:
For example #selector is owned by Obj-c,

In swift, we'll use  #selector in .addTarget or in .target of an object. There we should prefix @objc for targeting method.

Example:

@objc func dummy(_ sender: UIButton) {
    print("xxx")
}

above method will be using in a UIButton's target like

dummyButton.addTarget(self, action: #selector(self. dummy(_:)), for: .touchUpInside)

this is why we are using @objc as prefix in swift.


问:
Specifying one of base class template parameters by derived class template parameter. How to use base class's using declarations
For example, I have the next code:

```<code>template<typename T, typename T2>
class a
{
public:
    using myfl_t = float;

    a(myfl_t fl, double db) {}

    virtual void f()
    {
        std::cout << "a::f()\n";
    }
};

template<typename T>
class b : public a<T, int>
{
    using base_t = a<T, int>;
    using myfl_t = typename base_t::myfl_t;
public:
    b(myfl_t fl, double db)
        : base_t(fl, db) {}

    void f() override
    {
        std::cout << "b::f()\n";
    }
};
</code>```

It seems that I can reuse the base class's  myfl_t declaration only by duplicating using in the derived class.
Is there an easier way to do it?

答:
You can drop the using in b and use this in the constructor:

```<code>b(typename a<T, int>::myfl_t fl, double db)
</code>```

In any event, your current code seems fine to me. You aren't really duplicating anything here. Duplicating would be if you had to specify float again, which is not the case here, so it's fine.

See this for the reason why:

Why is the keyword "typename" needed before qualified dependent names, and not before qualified independent names?

Body:
For example, I have the next code:

template<typename T, typename T2>
class a
{
public:
    using myfl_t = float;

    a(myfl_t fl, double db) {}

    virtual void f()
    {
        std::cout << "a::f()\n";
    }
};

template<typename T>
class b : public a<T, int>
{
    using base_t = a<T, int>;
    using myfl_t = typename base_t::myfl_t;
public:
    b(myfl_t fl, double db)
        : base_t(fl, db) {}

    void f() override
    {
        std::cout << "b::f()\n";
    }
};

It seems that I can reuse the base class's  myfl_t declaration only by duplicating using in the derived class.
Is there an easier way to do it?

Body:
You can drop the using in b and use this in the constructor:

b(typename a<T, int>::myfl_t fl, double db)

In any event, your current code seems fine to me. You aren't really duplicating anything here. Duplicating would be if you had to specify float again, which is not the case here, so it's fine.

See this for the reason why:

Why is the keyword "typename" needed before qualified dependent names, and not before qualified independent names?


问:
Split a string that holds characters in different sizes
I have an input string that holds characters in different sizes, for example const char * input = "aadđ€€¢¢".
The strlen gave result 15, which mean while 'aad' only took 3 bytes, the other special characters took 2 bytes or more each.

How can I cut characters that fit into 6 bytes from the start of that string? Which mean in this case only 'aadđ' will be taken because aadđ€ would occupy 8 bytes.

I tried normal split character methods but none worked so far. Edit: Because a wide character might get split in the middle and therefore I will get some garbage or a different character instead.

答:
You need to understand the difference between "bytes" and "characters".

A byte is the smallest unit of computer storage, holds 8 bits of information. A character (a Unicode code point to be exact) is a number from 0 to 0x10FFFF that is represented by one or more bytes, depending on the encoding in use. A character is associated with some "glyph", a picture that's part of various fonts.

The characters with codes 0 through 127 (usually called "ASCII characters", but technically called "C0 Controls and Basic Latin" block) are encoded in one byte. Those include English letters, numbers and some punctuation. The rest of the characters are encoded in multiple bytes. Please look up UTF-8 and UTF-16 for some examples of how the encoding is done.

To answer your question, given the string in your example, you can cut 6 bytes at the beginning of the string, but the last bytes may not represent a valid character. In UTF-8, it will be a "prefix" byte that will be followed by one to three bytes to form a complete code point.


问:
Data replacement of data A using data B and comes out data B
The teacher table has elements of teacher's name , position, userid and password. I want to replace the userid with teacher's name in the another table named Subject so that it is easier to refer. So how can I do it using PHP coding ?

```<code><?php
    include ('connection.php');
    $data1 = mysqli_query($connect,"SELECT * FROM teacher");

    while ($info1=mysqli_fetch_array($data1))
    {
        echo "<option hidden selected> -- Your Option -- </option>";
        echo "<option value=$info1[userid]>$info1[name]</option>";
    }
</code>```

I expect to have the teacher's name as an option but it came out $info1[name]

答:
I usually prefer a much clearer syntax, which helps me in checking I refer to all in a correct manner:

```<code>while ($info1=mysqli_fetch_array($data1))
{
    echo "<option hidden selected> -- Your Option -- </option>";
    echo "<option value=\"".$info1["userid"]."\">".$info1["name"]."</option>";
}
</code>```

With that syntax you can always be sure, by simply looking at the code, that PHP will recognize and insert proper values...

Also, check that field names in the table do match exactly (even in uppercase/lowercase, not all db configurations are case insensitive) the names you use: "userid", "name", etc.

Body:
The teacher table has elements of teacher's name , position, userid and password. I want to replace the userid with teacher's name in the another table named Subject so that it is easier to refer. So how can I do it using PHP coding ?

<?php
    include ('connection.php');
    $data1 = mysqli_query($connect,"SELECT * FROM teacher");

    while ($info1=mysqli_fetch_array($data1))
    {
        echo "<option hidden selected> -- Your Option -- </option>";
        echo "<option value=$info1[userid]>$info1[name]</option>";
    }

I expect to have the teacher's name as an option but it came out $info1[name]

Body:
I usually prefer a much clearer syntax, which helps me in checking I refer to all in a correct manner:

while ($info1=mysqli_fetch_array($data1))
{
    echo "<option hidden selected> -- Your Option -- </option>";
    echo "<option value=\"".$info1["userid"]."\">".$info1["name"]."</option>";
}

With that syntax you can always be sure, by simply looking at the code, that PHP will recognize and insert proper values...

Also, check that field names in the table do match exactly (even in uppercase/lowercase, not all db configurations are case insensitive) the names you use: "userid", "name", etc.