问:
Letter guessing game Java
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

```<code>Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');
</code>```

Any help would be greatly appreciated! And i can display my code if it is needed

```<code>public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}
</code>```

答:
use arrays of characters </p>

```<code>char[] chars = ['A','B','C'...];
</code>```

<p>and use the random numbers to map to each character </p>

```<code>char targetLetter = chars[r.nextInt(26)];
</code>```

Title: Letter guessing game Java

Body:
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');

Any help would be greatly appreciated! And i can display my code if it is needed

public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}

Body:
use arrays of characters

char[] chars = ['A','B','C'...];

and use the random numbers to map to each character

char targetLetter = chars[r.nextInt(26)];


来源: stackexchange

问:
PuppetDB configurtion not working
I'm trying to configure puppetDB on the same puppet master server. I followed the puppet documentation, installed the database and configured the puppet to use database.

when I run puppet agent --test command its giving below error message.

I didn't see any process running in port 8081, I see puppet java process running on port 8140.

How can I resolve this error?

```<code>Warning: Unable to fetch my node definition, but the agent run will continue:
Warning: Error 500 on SERVER: Server Error: Could not retrieve facts for webserver: Failed to find facts from PuppetDB at puppet:8140: Failed to execute '/pdb/query/v4/nodes/webserver/facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Info: Retrieving pluginfacts
Info: Retrieving plugin
Warning: Error connecting to puppetdb on 8081 at route /pdb/query/v4/nodes/webserver/facts, error message received was 'Connection refused - connect(2) for "puppetdb" port 8081'. Failing over to the next PuppetDB server_url in the 'server_urls' list
Error: Cached facts for webserver failed: Failed to find facts from PuppetDB at puppet:8140: Failed to execute '/pdb/query/v4/nodes/webserver/facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Info: Loading facts
Info: Caching facts for webserver
Warning: Error connecting to puppetdb on 8081 at route /pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts, error message received was 'Connection refused - connect(2) for "puppetdb" port 8081'. Failing over to the next PuppetDB server_url in the 'server_urls' list
Error: Failed to execute '/pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Error: Could not retrieve local facts: Failed to execute '/pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Error: Failed to apply catalog: Could not retrieve local facts: Failed to execute '/pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
</code>```

答:
For some reason puppetdb process went down that's why no process running on port 8081. I have restarted puppetdb process, then agent -test command stated connecting to the webserver.

Here is the output of puppetdb service in centos 7.

```<code># systemctl status puppetdb
● puppetdb.service - puppetdb Service
   Loaded: loaded (/usr/lib/systemd/system/puppetdb.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2017-03-28 18:26:58 EDT; 1h 20min ago
 Main PID: 5503 (java)
   CGroup: /system.slice/puppetdb.service
           └─5503 /usr/bin/java -Xmx192m -Djava.security.egd=/dev/urandom -XX:OnOutOfMemoryError=kill -9 %p -cp /opt/puppetlabs/...
</code>```

ContentLicense: CC BY-SA 3.0

Title: PuppetDB configurtion not working

Body:
I'm trying to configure puppetDB on the same puppet master server. I followed the puppet documentation, installed the database and configured the puppet to use database.

when I run puppet agent --test command its giving below error message.

I didn't see any process running in port 8081, I see puppet java process running on port 8140.

How can I resolve this error?

Warning: Unable to fetch my node definition, but the agent run will continue:
Warning: Error 500 on SERVER: Server Error: Could not retrieve facts for webserver: Failed to find facts from PuppetDB at puppet:8140: Failed to execute '/pdb/query/v4/nodes/webserver/facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Info: Retrieving pluginfacts
Info: Retrieving plugin
Warning: Error connecting to puppetdb on 8081 at route /pdb/query/v4/nodes/webserver/facts, error message received was 'Connection refused - connect(2) for "puppetdb" port 8081'. Failing over to the next PuppetDB server_url in the 'server_urls' list
Error: Cached facts for webserver failed: Failed to find facts from PuppetDB at puppet:8140: Failed to execute '/pdb/query/v4/nodes/webserver/facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Info: Loading facts
Info: Caching facts for webserver
Warning: Error connecting to puppetdb on 8081 at route /pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts, error message received was 'Connection refused - connect(2) for "puppetdb" port 8081'. Failing over to the next PuppetDB server_url in the 'server_urls' list
Error: Failed to execute '/pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Error: Could not retrieve local facts: Failed to execute '/pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts' on at least 1 of the following 'server_urls': https://puppetdb:8081
Error: Failed to apply catalog: Could not retrieve local facts: Failed to execute '/pdb/cmd/v1?checksum=039e22c7bf98e9cbf2f08169047d288c9b451c73&version=5&certname=webserver&command=replace_facts' on at least 1 of the following 'server_urls': https://puppetdb:8081

Body:
For some reason puppetdb process went down that's why no process running on port 8081. I have restarted puppetdb process, then agent -test command stated connecting to the webserver.

Here is the output of puppetdb service in centos 7.

# systemctl status puppetdb
● puppetdb.service - puppetdb Service
   Loaded: loaded (/usr/lib/systemd/system/puppetdb.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2017-03-28 18:26:58 EDT; 1h 20min ago
 Main PID: 5503 (java)
   CGroup: /system.slice/puppetdb.service
           └─5503 /usr/bin/java -Xmx192m -Djava.security.egd=/dev/urandom -XX:OnOutOfMemoryError=kill -9 %p -cp /opt/puppetlabs/...


问:
Determine the process pid  listening on a certain port
As the title says, I'm running multiple game servers, and every of them has the same name but different PID and the port number. I would like to match the PID of the server which is listening on certain port, and then I would like to kill this process. I need that in order to complete my bash script.

Is that even possible? Because it didn't find yet any solutions on the web.

答:
I wanted to programmatically -- using only Bash -- kill the process listening on a given port.

Let's say the port is 8089, then here is how I did it:

```<code>badPid=$(netstat --listening --program --numeric --tcp | grep "::8089" | awk '{print $7}' | awk -F/ '{print $1}' | head -1)
kill -9 $badPid
</code>```

I hope this helps someone else! I know it is going to help my team.

Body:
I wanted to programmatically -- using only Bash -- kill the process listening on a given port.

Let's say the port is 8089, then here is how I did it:

badPid=$(netstat --listening --program --numeric --tcp | grep "::8089" | awk '{print $7}' | awk -F/ '{print $1}' | head -1)
kill -9 $badPid

I hope this helps someone else! I know it is going to help my team.


问:
ActiveMQ: starting consumer without broker
I am writing a JMS client that consumes from a Queue. My broker is activemq, if it matters.

One requirement is that the client should start even if the broker is down. In that case it should behave as if there where no messages in the Queue, and once the broker is up and messages start coming behave accordingly.

The problem is that in my code:

```<code>connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start()
</code>```

If the broker is down, then it gets stuck in connection.start(). While what I would like to have is connection.start() to return silently and to continue to try to connect in the background and consume messages while it can and be silent when it can't.

How can I achieve this.

答:
There are two ways to work around this type of scenario, one of which is described in AMQ-2114:

By using the broker URI that was suggested in AMQ-2114. By using the broker URI that is suggested in AMQ-2114, an embedded broker is created with a network connection to a remote broker. However, as was pointed out, that broker URI does not use the failover connector.

By using an embedded broker that is manually configured to use a network of brokers. I have used this in the past where an ActiveMQ broker instance is embedded inside your Java app and it is configured with a network connection to a remote broker. This will allow your client to connect to the embedded broker without hanging and will send messages to the embedded broker. Messages will flow from the embedded broker to the remote broker, but only when there is consumer demand for the messages on the remote broker (i.e., consumer connects to the remote broker and requests messages). The connection to the embedded broker can use the failover transport and the network connection to the remote broker can also use the failover transport.

The example I give for this solution is a use case is a Java app on a sales person's laptop. Such an app needs to continue working even if the sales person is not connected to their office network. The solution here is to embed a broker in the Java app so that the app will not hang when sending messages, even if it is not connected to the office network. When the app is again connected to the office network, it will automatically connect to another broker and the messages will flow.

Bruce

ContentLicense: CC BY-SA 2.5

Body:
I am writing a JMS client that consumes from a Queue. My broker is activemq, if it matters.

One requirement is that the client should start even if the broker is down. In that case it should behave as if there where no messages in the Queue, and once the broker is up and messages start coming behave accordingly.

The problem is that in my code:

connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start()

If the broker is down, then it gets stuck in connection.start(). While what I would like to have is connection.start() to return silently and to continue to try to connect in the background and consume messages while it can and be silent when it can't.

How can I achieve this.


问:
How to layout widgets in tkinter while using the Zoomed state + frames
How would i go on about placeing widgets on a frame, which is in the zoomed state, that cannot be resized while using .grid()?

I want to be able to place the buttons on the right most of the screen while placing a treeview on the left of the screen, with say an instance of 'whitespace' in the middle. I'm not sure if it can be done personally, and in my experience with tkinter i have only used smaller windows which are not 'Zoomed' or 'fullscreen' making .grid() placement really easy to use without this problem. Ive looked across the web for a solution but not yet found one.

I would like to be able to layout my tkinter window in the layout provided down below.

答:
The frustrating thing about questions like this is a) there are at least half a dozen ways to accomplish what you want, and b) the best way depends on variables that you haven't defined. For example, how do you decide the proportions of each section -- are you hard-coding them, do you want tkinter to compute them based on what's inside? What behavior do you want if the user resizes the window? And so on.

Getting Started

Let's start with the import statements and the root window. I hate full screen windows so I'm going with a smaller fixed size. The layout will work no matter what size, you can resize it to whatever you want.

```<code>import tkinter as tk

root = tk.Tk()
root.geometry("900x600")
</code>```

Add frames for each section

Next, lets create a frame for each section. Each frame will use the colors from your image to make it easier to visualize. I could use any widget, but frames are the most common widget to use as a container for other widgets (for example, a treeview or text widget with a scrollbar, a graph possibly with buttons, etc)

```<code>treeview_frame = tk.Frame(root, background="#FFF0C1", bd=1, relief="sunken")
graph_frame = tk.Frame(root, background="#D2E2FB", bd=1, relief="sunken")
text_frame = tk.Frame(root, background="#CCE4CA", bd=1, relief="sunken")
button_frame = tk.Frame(root, background="#F5C2C1", bd=1, relief="sunken")
</code>```

Designing your layout

With that out of the way, we can lay the widgets out. We could use pack for this pretty easily, but grid can be a bit easier to understand when you're learning.

When I look at your image, it's pretty clear to me that you have two rows and three columns. It looks like the first column (column 0) is a smidge wider than the other columns. Similarly, the first row (row 0) looks to be a smidge taller than the other row. We'll use that information in a bit.

Laying out the widgets with grid

First, let's put everything in their respective rows and columns. It should be pretty obvious, so I'll let the code do the explaining.

```<code>treeview_frame.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
graph_frame.grid(row=1, column=0, sticky="nsew", padx=2, pady=2)
text_frame.grid(row=0, column=1, rowspan=2, sticky="nsew", padx=2, pady=2)
button_frame.grid(row=0, column=2, rowspan=2, sticky="nsew", padx=2, pady=2)
</code>```

Configuring the grid as a whole

Next comes a very important step that almost all beginners forget: you need to give each row and column a weight. The weight determines how grid allocates extra space. Since you said you want a zoomed window, you'll probably have a bunch of extra space after adding in your actual widgets.

Here's where the relative widths and heights come in. The weight attribute is a value that specifies how extra space is allocated. For example, if you have a column with a weight of 1 (one), and another with a weight of 2, the one with the weight of 2 will get two times the extra space of the other. In For example, if tkinter calculates that there's 100 extra pixels it needs to fill, it will give 66 or 67 pixels to one, and 33 or 34 to the other.

Something to keep in mind is that rows and columns have a weight of 0 (zero). That means that they are not given any extra space.

A rule of thumb says that most of the weight should be given to the "main" widget on the screen. For a text editor that would be a text widget, for a drawing app it might be a canvas. For a reporting app it might be a treeview. Since you have all of that, I don't know exactly how you want the space allocated.

Configuring the rows

I'm going to guess, and say that row 0 where the treeview is should take up a little more than half the height. I'm going to give it a weight of 3 and the other a weight of 2. If you want both the treeview and graph to be the same size you would give them each a weight of 1. If the graph is a fixed size but the treeview should be as big as possible, give the graph a weight of 0 (zero) and the tree a weight of 1.

```<code>root.grid_rowconfigure(0, weight=3)
root.grid_rowconfigure(1, weight=2)
</code>```

Configuring the columns

Now we need to go through the same exercise with the columns. It looks like the first column, column zero, takes up just a bit more room than the other columns. So, I'm going to give it a weight of 3 and the others a weight of 2. Like with the rows, you can put all the weight in one column, distribute it equally, or do it however you wish.

```<code>root.grid_columnconfigure(0, weight=3)
root.grid_columnconfigure(1, weight=2)
root.grid_columnconfigure(2, weight=2)
</code>```

Final steps

That's it, for a basic layout.

If you call a call to root.mainloop() at the end of all that code you'll have a window that looks almost exactly like the picture you provided. Notice that it all scales beautifully as you resize the window.

Adding more widgets

Now you can start to add widgets to each frame, without having to worry too much about how they affect the rest of the window. Not only that, but you can use pack for some, and grid or place for others. For example, if you wanted the treeview to have a scrollbar, you might create it like this:

```<code>tree = ttk.Treeview(treeview_frame)
sb = ttk.Scrollbar(treeview_frame)
sb.pack(side="right", fill="y")
tree.pack(side="left", fill="both", expand=True)
</code>```

The only thing that might surprise you is that if you put in a very large widget, it may mess up the proportions. The simplest solution is usually to set the width and  height to something small, and let it grow to fit. If you make it large, it will want to be large, pushing other widgets away.

Body:
The frustrating thing about questions like this is a) there are at least half a dozen ways to accomplish what you want, and b) the best way depends on variables that you haven't defined. For example, how do you decide the proportions of each section -- are you hard-coding them, do you want tkinter to compute them based on what's inside? What behavior do you want if the user resizes the window? And so on.

Getting Started

Let's start with the import statements and the root window. I hate full screen windows so I'm going with a smaller fixed size. The layout will work no matter what size, you can resize it to whatever you want.

import tkinter as tk

root = tk.Tk()
root.geometry("900x600")

Add frames for each section

Next, lets create a frame for each section. Each frame will use the colors from your image to make it easier to visualize. I could use any widget, but frames are the most common widget to use as a container for other widgets (for example, a treeview or text widget with a scrollbar, a graph possibly with buttons, etc)

treeview_frame = tk.Frame(root, background="#FFF0C1", bd=1, relief="sunken")
graph_frame = tk.Frame(root, background="#D2E2FB", bd=1, relief="sunken")
text_frame = tk.Frame(root, background="#CCE4CA", bd=1, relief="sunken")
button_frame = tk.Frame(root, background="#F5C2C1", bd=1, relief="sunken")

Designing your layout

With that out of the way, we can lay the widgets out. We could use pack for this pretty easily, but grid can be a bit easier to understand when you're learning.

When I look at your image, it's pretty clear to me that you have two rows and three columns. It looks like the first column (column 0) is a smidge wider than the other columns. Similarly, the first row (row 0) looks to be a smidge taller than the other row. We'll use that information in a bit.

Laying out the widgets with grid

First, let's put everything in their respective rows and columns. It should be pretty obvious, so I'll let the code do the explaining.

treeview_frame.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
graph_frame.grid(row=1, column=0, sticky="nsew", padx=2, pady=2)
text_frame.grid(row=0, column=1, rowspan=2, sticky="nsew", padx=2, pady=2)
button_frame.grid(row=0, column=2, rowspan=2, sticky="nsew", padx=2, pady=2)

Configuring the grid as a whole

Next comes a very important step that almost all beginners forget: you need to give each row and column a weight. The weight determines how grid allocates extra space. Since you said you want a zoomed window, you'll probably have a bunch of extra space after adding in your actual widgets.

Here's where the relative widths and heights come in. The weight attribute is a value that specifies how extra space is allocated. For example, if you have a column with a weight of 1 (one), and another with a weight of 2, the one with the weight of 2 will get two times the extra space of the other. In For example, if tkinter calculates that there's 100 extra pixels it needs to fill, it will give 66 or 67 pixels to one, and 33 or 34 to the other.

Something to keep in mind is that rows and columns have a weight of 0 (zero). That means that they are not given any extra space.

A rule of thumb says that most of the weight should be given to the "main" widget on the screen. For a text editor that would be a text widget, for a drawing app it might be a canvas. For a reporting app it might be a treeview. Since you have all of that, I don't know exactly how you want the space allocated.

Configuring the rows

I'm going to guess, and say that row 0 where the treeview is should take up a little more than half the height. I'm going to give it a weight of 3 and the other a weight of 2. If you want both the treeview and graph to be the same size you would give them each a weight of 1. If the graph is a fixed size but the treeview should be as big as possible, give the graph a weight of 0 (zero) and the tree a weight of 1.

root.grid_rowconfigure(0, weight=3)
root.grid_rowconfigure(1, weight=2)

Configuring the columns

Now we need to go through the same exercise with the columns. It looks like the first column, column zero, takes up just a bit more room than the other columns. So, I'm going to give it a weight of 3 and the others a weight of 2. Like with the rows, you can put all the weight in one column, distribute it equally, or do it however you wish.

root.grid_columnconfigure(0, weight=3)
root.grid_columnconfigure(1, weight=2)
root.grid_columnconfigure(2, weight=2)

Final steps

That's it, for a basic layout.

If you call a call to root.mainloop() at the end of all that code you'll have a window that looks almost exactly like the picture you provided. Notice that it all scales beautifully as you resize the window.

Adding more widgets

Now you can start to add widgets to each frame, without having to worry too much about how they affect the rest of the window. Not only that, but you can use pack for some, and grid or place for others. For example, if you wanted the treeview to have a scrollbar, you might create it like this:

tree = ttk.Treeview(treeview_frame)
sb = ttk.Scrollbar(treeview_frame)
sb.pack(side="right", fill="y")
tree.pack(side="left", fill="both", expand=True)

The only thing that might surprise you is that if you put in a very large widget, it may mess up the proportions. The simplest solution is usually to set the width and  height to something small, and let it grow to fit. If you make it large, it will want to be large, pushing other widgets away.


问:
Updating table with business day and calendar day
I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in.  The date rule already has values but the expected date column is what is updated manually.  If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month.  If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth.  Is it possible to write an update query where it would loop through the values and update automatically?  I'm having trouble figuring out to update to the correct business day.

```
date rule  | March expected date | April expected date |
--------------------------------------------------------
| BD1      | 3/1/2017            | 4/3/2017            |
| BD2      | 3/2/2017            |                     |
| BD3      | 3/3/2017            |                     |
| BD4      | 3/6/2017            |                     |
| BD5      |                     |                     |
| BD6      |                     |                     |
| CD1      | 3/1/2017            |                     |
| CD2      | 3/2/2017            |                     |
| CD3      | 3/3/2017            |                     |
| CD4      | 3/4/2017            |                     |
| CD5      | 3/5/2017            |                     |
| CD6      | 3/6/2017            |                     |

```

I was using the following code to calculate the first business day

```<code>SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
</code>```

)

but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday.  i'm getting stumped in how to tackle this.  I'm thinking a loop update query would be best

答:
you can use this logic.. where will find the next business day skipping the weekends.</p>

```<code>declare @datetoday date = '2017-04-01'

select iif(datepart(dw,@datetoday)=1, dateadd(day,1,@datetoday),iif(datepart(dw,@datetoday)=7,dateadd(day,2,@datetoday),@datetoday))
</code>```

Body:
I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in.  The date rule already has values but the expected date column is what is updated manually.  If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month.  If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth.  Is it possible to write an update query where it would loop through the values and update automatically?  I'm having trouble figuring out to update to the correct business day.

date rule  | March expected date | April expected date |
--------------------------------------------------------
| BD1      | 3/1/2017            | 4/3/2017            |
| BD2      | 3/2/2017            |                     |
| BD3      | 3/3/2017            |                     |
| BD4      | 3/6/2017            |                     |
| BD5      |                     |                     |
| BD6      |                     |                     |
| CD1      | 3/1/2017            |                     |
| CD2      | 3/2/2017            |                     |
| CD3      | 3/3/2017            |                     |
| CD4      | 3/4/2017            |                     |
| CD5      | 3/5/2017            |                     |
| CD6      | 3/6/2017            |                     |

I was using the following code to calculate the first business day

SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)

)

but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday.  i'm getting stumped in how to tackle this.  I'm thinking a loop update query would be best

Body:
you can use this logic.. where will find the next business day skipping the weekends.

declare @datetoday date = '2017-04-01'

select iif(datepart(dw,@datetoday)=1, dateadd(day,1,@datetoday),iif(datepart(dw,@datetoday)=7,dateadd(day,2,@datetoday),@datetoday))


问:
object(car) detection in opencv python
I am working on one of my college project i.e object(car) detection in opencv python ,i am using opencv 3 and python 3.4. I have a code for it but when i run the code the output is not displayed. It shows that the code is error free but still unable to get the output. I am new to image processing ,so it will be a great help if someone tries to sort out my problem. The code is given below`</p>

```<code>import cv2
import numpy as np
import argparse
ap = argparse.ArgumentParser()
ap.add_agrument("-v","--video",
help = "path to the (optional) video file")
args = vars(ap.parse_agrs())
camera = cv2.VideoCapture(agrs["video"])
car_cascade = cv2.CascadeClassifier("cars.xml")
while true:
ret,frames = camera.read(),cv2.rectangle()
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectionMultiScale(gray, 1.1,1)
for (x,y,w,h) in cars:
cv2.rectangular()frames,(x,y),(x+w,y+h), (0,0,255),2)
cv2.imshow ('video',frames)
cv2.waitkey(0)
</code>```

答:
Let's make the code even a bit more perfect by running the video at approximately it's original speed (25 frames/second), taking out what is not necessary and drawing all the rectangles first, then showing the frame: </p>

```<code>import cv2

camera = cv2.VideoCapture("video.avi")
car_cascade = cv2.CascadeClassifier('cars.xml')

# Get frames per second from video file. Syntax depends on OpenCV version:
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver)  < 3 :
    fps = camera.get(cv2.cv.CV_CAP_PROP_FPS)
else :
    fps = camera.get(cv2.CAP_PROP_FPS)
#:if
intTimeToNextFrame=int(1000.0/fps)-12 # '-12' estimation of time for processing
while True:
    (grabbed,frame) = camera.read()
    grayvideo = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cars = car_cascade.detectMultiScale(grayvideo, 1.1, 1)
    for (x,y,w,h) in cars:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,255),1)
    cv2.imshow("video",frame)
    if cv2.waitKey(intTimeToNextFrame)== ord('q'):
        break
camera.release()
cv2.destroyAllWindows()
</code>```

Title: object(car) detection in opencv python

Body:
I am working on one of my college project i.e object(car) detection in opencv python ,i am using opencv 3 and python 3.4. I have a code for it but when i run the code the output is not displayed. It shows that the code is error free but still unable to get the output. I am new to image processing ,so it will be a great help if someone tries to sort out my problem. The code is given below`

import cv2
import numpy as np
import argparse
ap = argparse.ArgumentParser()
ap.add_agrument("-v","--video",
help = "path to the (optional) video file")
args = vars(ap.parse_agrs())
camera = cv2.VideoCapture(agrs["video"])
car_cascade = cv2.CascadeClassifier("cars.xml")
while true:
ret,frames = camera.read(),cv2.rectangle()
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectionMultiScale(gray, 1.1,1)
for (x,y,w,h) in cars:
cv2.rectangular()frames,(x,y),(x+w,y+h), (0,0,255),2)
cv2.imshow ('video',frames)
cv2.waitkey(0)

Body:
Let's make the code even a bit more perfect by running the video at approximately it's original speed (25 frames/second), taking out what is not necessary and drawing all the rectangles first, then showing the frame:

import cv2

camera = cv2.VideoCapture("video.avi")
car_cascade = cv2.CascadeClassifier('cars.xml')

# Get frames per second from video file. Syntax depends on OpenCV version:
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver)  < 3 :
    fps = camera.get(cv2.cv.CV_CAP_PROP_FPS)
else :
    fps = camera.get(cv2.CAP_PROP_FPS)
#:if
intTimeToNextFrame=int(1000.0/fps)-12 # '-12' estimation of time for processing
while True:
    (grabbed,frame) = camera.read()
    grayvideo = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cars = car_cascade.detectMultiScale(grayvideo, 1.1, 1)
    for (x,y,w,h) in cars:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,255),1)
    cv2.imshow("video",frame)
    if cv2.waitKey(intTimeToNextFrame)== ord('q'):
        break
camera.release()
cv2.destroyAllWindows()


问:
Twitter Scanner w tweepy - Python
I was just wondering if it's possible to make a scanner with tweepy - for instance, a while loop that is constantly searching for certain words. I'm a trader and would find it very useful in case there is any breaking news.

Example:

I want to set my scanner to constantly return tweets that have '$DB' in them. Furthermore, I only want to return tweets of users that have > 5k followers.

Any advice or pointers would be helpful! Thanks.

答:
Edit/Update: As discussed by asongtoruin and qorka, the question asks for new tweets, not existing tweets. Previous edit used api.search method which finds only existing messages. The StreamListener reads new messages.

```<code>import tweepy
from tweepy import OAuthHandler

access_token='your_api_token'
access_secret='your_api_access_secret'
consumer_key = 'your_api_key'
consumer_secret = 'your_consumer_key'

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

class MyListener(StreamListener):
    def on_status(self, status):
        try:
            if status.user.followers_count > 5000:
                print '%s (%s at %s, followers: %d)' % (status.text, status.user.screen_name, status.created_at, status.user.followers_count)
                return True
        except BaseException as e:
            print("Error on_status: %s" % str(e))
        return True

    def on_error(self, status):
        print(status)
        return True

twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track=['$DB','$MS','$C'])
</code>```

Title: Twitter Scanner w tweepy - Python

Body:
Edit/Update: As discussed by asongtoruin and qorka, the question asks for new tweets, not existing tweets. Previous edit used api.search method which finds only existing messages. The StreamListener reads new messages.

import tweepy
from tweepy import OAuthHandler

access_token='your_api_token'
access_secret='your_api_access_secret'
consumer_key = 'your_api_key'
consumer_secret = 'your_consumer_key'

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

class MyListener(StreamListener):
    def on_status(self, status):
        try:
            if status.user.followers_count > 5000:
                print '%s (%s at %s, followers: %d)' % (status.text, status.user.screen_name, status.created_at, status.user.followers_count)
                return True
        except BaseException as e:
            print("Error on_status: %s" % str(e))
        return True

    def on_error(self, status):
        print(status)
        return True

twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track=['$DB','$MS','$C'])


问:
Using declarative services in Karaf 4.1.0
I'm trying to develop a Karaf 4.1.0 application using NetBeans 8.2, Maven 3.3.9 and declarative services. Really simple services work, but as soon as I try to do something vaguely useful I get the dreaded osgi.component missing requirement error.

The following illustrates the sort of problem I'm having:

```<code>package net.winnall.enocean.bridge.sass.impl;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.winnall.enocean.bridge.sass.SASS;
import org.osgi.service.http.HttpService;

@Component(
        service = SASS.class
)
public class SASSImpl implements SASS {

    @Reference
    HttpService httpService;

    @Activate
    protected void activate() {
    }

    @Deactivate
    }
}
</code>```

If I comment out the @Reference the component is loaded into the generated Karaf assembly without any problems. But as the component stands here (WITH the @Reference) I get the following error:

Failed to execute goal org.apache.karaf.tooling:karaf-maven-plugin:4.1.0:assembly (default-assembly) on project EnOceanBridgeAdmin: Unable to build assembly: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=EnOceanBridgeSASSFeature; type=karaf.feature; version=0.99.99; filter:="(&(osgi.identity=EnOceanBridgeSASSFeature)(type=karaf.feature)(version>=0.99.99))" [caused by: Unable to resolve EnOceanBridgeSASSFeature/0.99.99: missing requirement [EnOceanBridgeSASSFeature/0.99.99] osgi.identity; osgi.identity=EnOceanBridgeSASS.Impl; type=osgi.bundle; version="[0.99.99,0.99.99]"; resolution:=mandatory [caused by: Unable to resolve EnOceanBridgeSASS.Impl/0.99.99: missing requirement [EnOceanBridgeSASS.Impl/0.99.99] osgi.extender; filter:="(&(osgi.extender=osgi.component)(version>=1.3.0)(!(version>=2.0.0)))"]] -> [Help 1]

This question suggests installing scr:

```<code>feature:install scr
</code>```

so I tried adding <feature>scr</feature to karat-maven-plugin's <bootFeatures>, but it makes no difference.

The following is an extract from the effective POM for this component:

```<code>  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.configadmin</artifactId>
        <version>1.8.14</version>
      </dependency>

      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
        <version>1.2.8</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-service</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-api</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-log4j2</artifactId>
        <version>1.9.1</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>framework</artifactId>
      <version>4.1.0</version>
      <type>kar</type>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>standard</artifactId>
      <version>4.1.0</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.karaf.tooling</groupId>
          <artifactId>karaf-maven-plugin</artifactId>
          <version>4.1.0</version>
          <extensions>true</extensions>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.apache.karaf.tooling</groupId>
        <artifactId>karaf-maven-plugin</artifactId>
        <version>4.1.0</version>
        <extensions>true</extensions>
        <configuration>
          <installedFeatures></installedFeatures>
          <startupFeatures></startupFeatures>
          <bootFeatures>
            <feature>minimal</feature>
            <feature>scr</feature>
          </bootFeatures>
          <javase>1.8</javase>
        </configuration>
      </plugin>
</code>```

The feature I use to make it known to the Karaf assembly is:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="EnOceanBridgeSASS.Impl">
    <feature name="EnOceanBridgeSASS.Impl" description="EnOceanBridge SASS Impl" version="0.99.99">
        <details>Karaf :: Declarative Services :: Service :: EnOceanBridge SASS Implementation</details>
        <bundle start-level="80">mvn:net.winnall.enocean.service.api/EnOceanBridgeSASS.API/0.99.99</bundle>
        <bundle start-level="80">mvn:org.apache.felix/org.apache.felix.configadmin/1.8.14</bundle>
        <bundle start-level="80">mvn:org.ops4j.pax.logging/pax-logging-api/1.9.1</bundle>
        <bundle start-level="80">mvn:org.ops4j.pax.logging/pax-logging-service/1.9.1</bundle>
    </feature>
</features>
</code>```

And the Karaf assembly's effective POM contains this:

```<code>  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.configadmin</artifactId>
        <version>1.8.14</version>
      </dependency>

      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
        <version>1.2.8</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-service</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-api</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-log4j2</artifactId>
        <version>1.9.1</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>net.winnall.enocean.feature</groupId>
      <artifactId>EnOceanBridgeSettingsFeature</artifactId>
      <version>0.99.99</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>net.winnall.enocean.feature</groupId>
      <artifactId>EnOceanBridgeSASSFeature</artifactId>
      <version>0.99.99</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>net.winnall.enocean.feature</groupId>
      <artifactId>EnOceanBridgePersistenceFeature</artifactId>
      <version>0.99.99</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>framework</artifactId>
      <version>4.1.0</version>
      <type>kar</type>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>standard</artifactId>
      <version>4.1.0</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.karaf.tooling</groupId>
          <artifactId>karaf-maven-plugin</artifactId>
          <version>4.1.0</version>
          <extensions>true</extensions>
        </plugin>

        <plugin>
          <artifactId>maven-archetype-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>

        <plugin>
          <groupId>com.github.ferstl</groupId>
          <artifactId>depgraph-maven-plugin</artifactId>
          <version>2.1.0</version>
        </plugin>

        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>1.6.0</version>
        </plugin>

        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>license-maven-plugin</artifactId>
          <version>1.12</version>
        </plugin>

        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.8</version>
        </plugin>

        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>

        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.1</version>
        </plugin>

        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.0</version>
        </plugin>

        <plugin>
          <groupId>org.apache.felix</groupId>
          <artifactId>maven-bundle-plugin</artifactId>
          <version>3.3.0</version>
        </plugin>

        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>com.github.ferstl</groupId>
        <artifactId>depgraph-maven-plugin</artifactId>
        <version>2.1.0</version>
      </plugin>

      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.0.2</version>
        <executions>
          <execution>
            <id>default-resources</id>
            <phase>process-resources</phase>
            <goals>
              <goal>resources</goal>
            </goals>
          </execution>
          <execution>
            <id>process-resources</id>
            <goals>
              <goal>resources</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.karaf.tooling</groupId>
        <artifactId>karaf-maven-plugin</artifactId>
        <version>4.1.0</version>
        <extensions>true</extensions>
        <executions>
          <execution>
            <id>default-archive</id>
            <phase>package</phase>
            <goals>
              <goal>archive</goal>
            </goals>
            <configuration>
              <installedFeatures></installedFeatures>
              <startupFeatures></startupFeatures>
              <bootFeatures>
                <feature>minimal</feature>
                <feature>scr</feature>
              </bootFeatures>
              <javase>1.8</javase>
            </configuration>
          </execution>

          <execution>
            <id>default-assembly</id>
            <phase>process-resources</phase>
            <goals>
              <goal>assembly</goal>
            </goals>
            <configuration>
              <installedFeatures></installedFeatures>
              <startupFeatures></startupFeatures>
              <bootFeatures>
                <feature>minimal</feature>
                <feature>scr</feature>
              </bootFeatures>
              <javase>1.8</javase>
            </configuration>
          </execution>
        </executions>

        <configuration>
          <installedFeatures></installedFeatures>
          <startupFeatures></startupFeatures>
          <bootFeatures>
            <feature>standard</feature>
            <feature>scr</feature>
          </bootFeatures>
          <javase>1.8</javase>
        </configuration>
      </plugin>
</code>```

I've spent all weekend googling this problem: it seems to me that there is hardly any current documentation in the Internet on using declarative services in Karaf.

Can anyone give me some tips about how to resolve my problem?

Steve

答:
I've finally got rid of the error, though – to be honest – I'm not sure what I did to fix it. The final edit that made the thing work was to remove something from the feature file listed above that wasn't in there at all when I reported the initial problem (it was a <repository /> and a <feature /> reference that I had added in a vain attempt to force the installation of HttpService...).

My current view of a better possible world (i.e. where I don't lose 4 days on problems like this) includes:

OSGi error messages that help the programmer to isolate errors;

A way of telling Google that I am really only interested in the latest incarnation of declarative services (i.e. annotation-based and not raw BND or XML files);

More clean annotation-based DS documentation without illustrations on how to do it in Eclipse, because I don't use Eclipse and don't want to;

More simple documentation on how to use DS in Karaf;

A Karaf IDE (is that what Karaf Boot is?).

I think Karaf and DS are both cool ways of working. I wish it were easier.

Body:
I'm trying to develop a Karaf 4.1.0 application using NetBeans 8.2, Maven 3.3.9 and declarative services. Really simple services work, but as soon as I try to do something vaguely useful I get the dreaded osgi.component missing requirement error.

The following illustrates the sort of problem I'm having:

package net.winnall.enocean.bridge.sass.impl;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.winnall.enocean.bridge.sass.SASS;
import org.osgi.service.http.HttpService;

@Component(
        service = SASS.class
)
public class SASSImpl implements SASS {

    @Reference
    HttpService httpService;

    @Activate
    protected void activate() {
    }

    @Deactivate
    }
}

If I comment out the @Reference the component is loaded into the generated Karaf assembly without any problems. But as the component stands here (WITH the @Reference) I get the following error:

Failed to execute goal org.apache.karaf.tooling:karaf-maven-plugin:4.1.0:assembly (default-assembly) on project EnOceanBridgeAdmin: Unable to build assembly: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=EnOceanBridgeSASSFeature; type=karaf.feature; version=0.99.99; filter:="(&(osgi.identity=EnOceanBridgeSASSFeature)(type=karaf.feature)(version>=0.99.99))" [caused by: Unable to resolve EnOceanBridgeSASSFeature/0.99.99: missing requirement [EnOceanBridgeSASSFeature/0.99.99] osgi.identity; osgi.identity=EnOceanBridgeSASS.Impl; type=osgi.bundle; version="[0.99.99,0.99.99]"; resolution:=mandatory [caused by: Unable to resolve EnOceanBridgeSASS.Impl/0.99.99: missing requirement [EnOceanBridgeSASS.Impl/0.99.99] osgi.extender; filter:="(&(osgi.extender=osgi.component)(version>=1.3.0)(!(version>=2.0.0)))"]] -> [Help 1]

This question suggests installing scr:

feature:install scr

so I tried adding <feature>scr</feature to karat-maven-plugin's <bootFeatures>, but it makes no difference.

The following is an extract from the effective POM for this component:

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.configadmin</artifactId>
        <version>1.8.14</version>
      </dependency>

      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
        <version>1.2.8</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-service</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-api</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-log4j2</artifactId>
        <version>1.9.1</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>framework</artifactId>
      <version>4.1.0</version>
      <type>kar</type>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>standard</artifactId>
      <version>4.1.0</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.karaf.tooling</groupId>
          <artifactId>karaf-maven-plugin</artifactId>
          <version>4.1.0</version>
          <extensions>true</extensions>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.apache.karaf.tooling</groupId>
        <artifactId>karaf-maven-plugin</artifactId>
        <version>4.1.0</version>
        <extensions>true</extensions>
        <configuration>
          <installedFeatures></installedFeatures>
          <startupFeatures></startupFeatures>
          <bootFeatures>
            <feature>minimal</feature>
            <feature>scr</feature>
          </bootFeatures>
          <javase>1.8</javase>
        </configuration>
      </plugin>

The feature I use to make it known to the Karaf assembly is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="EnOceanBridgeSASS.Impl">
    <feature name="EnOceanBridgeSASS.Impl" description="EnOceanBridge SASS Impl" version="0.99.99">
        Karaf :: Declarative Services :: Service :: EnOceanBridge SASS Implementation
        <bundle start-level="80">mvn:net.winnall.enocean.service.api/EnOceanBridgeSASS.API/0.99.99</bundle>
        <bundle start-level="80">mvn:org.apache.felix/org.apache.felix.configadmin/1.8.14</bundle>
        <bundle start-level="80">mvn:org.ops4j.pax.logging/pax-logging-api/1.9.1</bundle>
        <bundle start-level="80">mvn:org.ops4j.pax.logging/pax-logging-service/1.9.1</bundle>
    </feature>
</features>

And the Karaf assembly's effective POM contains this:

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.configadmin</artifactId>
        <version>1.8.14</version>
      </dependency>

      <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
        <version>1.2.8</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-service</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-api</artifactId>
        <version>1.9.1</version>
      </dependency>

      <dependency>
        <groupId>org.ops4j.pax.logging</groupId>
        <artifactId>pax-logging-log4j2</artifactId>
        <version>1.9.1</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>net.winnall.enocean.feature</groupId>
      <artifactId>EnOceanBridgeSettingsFeature</artifactId>
      <version>0.99.99</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>net.winnall.enocean.feature</groupId>
      <artifactId>EnOceanBridgeSASSFeature</artifactId>
      <version>0.99.99</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>net.winnall.enocean.feature</groupId>
      <artifactId>EnOceanBridgePersistenceFeature</artifactId>
      <version>0.99.99</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>framework</artifactId>
      <version>4.1.0</version>
      <type>kar</type>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.karaf.features</groupId>
      <artifactId>standard</artifactId>
      <version>4.1.0</version>
      <type>xml</type>
      <classifier>features</classifier>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.karaf.tooling</groupId>
          <artifactId>karaf-maven-plugin</artifactId>
          <version>4.1.0</version>
          <extensions>true</extensions>
        </plugin>

        <plugin>
          <artifactId>maven-archetype-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>

        <plugin>
          <groupId>com.github.ferstl</groupId>
          <artifactId>depgraph-maven-plugin</artifactId>
          <version>2.1.0</version>
        </plugin>

        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>1.6.0</version>
        </plugin>

        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>license-maven-plugin</artifactId>
          <version>1.12</version>
        </plugin>

        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.8</version>
        </plugin>

        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>

        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.1</version>
        </plugin>

        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.0</version>
        </plugin>

        <plugin>
          <groupId>org.apache.felix</groupId>
          <artifactId>maven-bundle-plugin</artifactId>
          <version>3.3.0</version>
        </plugin>

        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>com.github.ferstl</groupId>
        <artifactId>depgraph-maven-plugin</artifactId>
        <version>2.1.0</version>
      </plugin>

      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.0.2</version>
        <executions>
          <execution>
            <id>default-resources</id>
            <phase>process-resources</phase>
            <goals>
              <goal>resources</goal>
            </goals>
          </execution>
          <execution>
            <id>process-resources</id>
            <goals>
              <goal>resources</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.karaf.tooling</groupId>
        <artifactId>karaf-maven-plugin</artifactId>
        <version>4.1.0</version>
        <extensions>true</extensions>
        <executions>
          <execution>
            <id>default-archive</id>
            <phase>package</phase>
            <goals>
              <goal>archive</goal>
            </goals>
            <configuration>
              <installedFeatures></installedFeatures>
              <startupFeatures></startupFeatures>
              <bootFeatures>
                <feature>minimal</feature>
                <feature>scr</feature>
              </bootFeatures>
              <javase>1.8</javase>
            </configuration>
          </execution>

          <execution>
            <id>default-assembly</id>
            <phase>process-resources</phase>
            <goals>
              <goal>assembly</goal>
            </goals>
            <configuration>
              <installedFeatures></installedFeatures>
              <startupFeatures></startupFeatures>
              <bootFeatures>
                <feature>minimal</feature>
                <feature>scr</feature>
              </bootFeatures>
              <javase>1.8</javase>
            </configuration>
          </execution>
        </executions>

        <configuration>
          <installedFeatures></installedFeatures>
          <startupFeatures></startupFeatures>
          <bootFeatures>
            <feature>standard</feature>
            <feature>scr</feature>
          </bootFeatures>
          <javase>1.8</javase>
        </configuration>
      </plugin>

I've spent all weekend googling this problem: it seems to me that there is hardly any current documentation in the Internet on using declarative services in Karaf.

Can anyone give me some tips about how to resolve my problem?

Steve


问:
Modified Magento List Template does have all attributes nesssary to display product info anymore
I am trying to display all products of a specific category. So i created a copy of /theme/template/catalog/list.phtml, and i added these couple of lines at the top:

```<code>$cat_id = 10; // category_id for "specific category"
$_productCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter(Mage::getModel('catalog/category')->load($cat_id));
</code>```

Which replaced:

```<code>$_productCollection=$this->getLoadedProductCollection();
</code>```

Now im getting all the products, but certain attributes and methods of the product dont seem to be available anymore($_product->isSaleable(), $this->getPriceHtml($_product) ). so the template does not show the product price or image correctly.  It seems to me that certain helper functions are not available to me anymore since i referenced the model directly for the products, but i dont know enough about the Zend/Magento framework to know what method(s) to use instead.

I didnt paste the code for list.phtml, as this is just the default code for the base template on magento 1.3. Please let me know anyone needs this code for reference.

Thanks in advance!

答:
Presumably because you are not specifying a store id nor scope, the collection doesn't know which attributes to load along with the product models. You can include that and shorten your code by doing this:</p>

```<code>$cat_id = 10; // category_id for "specific category"
$_category = Mage::getModel('catalog/category')->load($cat_id);
$_productCollection = $_category->getProductCollection();
</code>```

Body:
I am trying to display all products of a specific category. So i created a copy of /theme/template/catalog/list.phtml, and i added these couple of lines at the top:

$cat_id = 10; // category_id for "specific category"
$_productCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter(Mage::getModel('catalog/category')->load($cat_id));

Which replaced:

$_productCollection=$this->getLoadedProductCollection();

Now im getting all the products, but certain attributes and methods of the product dont seem to be available anymore($_product->isSaleable(), $this->getPriceHtml($_product) ). so the template does not show the product price or image correctly.  It seems to me that certain helper functions are not available to me anymore since i referenced the model directly for the products, but i dont know enough about the Zend/Magento framework to know what method(s) to use instead.

I didnt paste the code for list.phtml, as this is just the default code for the base template on magento 1.3. Please let me know anyone needs this code for reference.

Thanks in advance!

Body:
Presumably because you are not specifying a store id nor scope, the collection doesn't know which attributes to load along with the product models. You can include that and shorten your code by doing this:

$cat_id = 10; // category_id for "specific category"
$_category = Mage::getModel('catalog/category')->load($cat_id);
$_productCollection = $_category->getProductCollection();


问:
Telegram bot: example json, inline_keyboard
Example json for show inline_keyboard in telegram bot

https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating

```<code>{
        "chat_id": "123456",
        "text": "Hi",
        "reply_markup": {
            "inline_keyboard": [[
                {
                    "text": "A",
                    "callback_data": "A1"
                },
                {
                    "text": "B",
                    "callback_data": "C1"
                }]
            ]
        }
    }
</code>```

答:
I just had a hard time trying to get it to work on my API and I've found the problem. You need to JSON.stringify() the contents of reply_markup that converts the keyboard object and contents into a string first.

Here's an example.

```<code>bot.onCommand = function (chat, from, message_id, text, command, commandData) {
    if (command === "test") {
        var keyboard = {
            "inline_keyboard": [
                [
                    {"text": "Yes", "url": "http://www.google.com/"},
                    {"text": "No", "url": "http://www.google.com/"}
                ]
            ]
        };

        var data = {
            "reply_to_message_id": message_id,
            "reply_markup": JSON.stringify(keyboard)
        };

        bot.sendText(chat.id, "test", data, function (isSuccess) {
            console.log(isSuccess);
        });

        return;
    }
}
</code>```

I wrote this to hopefully make it less confusing.

The output will be:

```<code>(test    )
[Yes] [No]
</code>```

The circler brackets is the message and the square brackets is the buttons. Both in this example opens a link to Google.

ContentLicense: CC BY-SA 4.0

Body:
Example json for show inline_keyboard in telegram bot

https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating

{
        "chat_id": "123456",
        "text": "Hi",
        "reply_markup": {
            "inline_keyboard": [[
                {
                    "text": "A",
                    "callback_data": "A1"
                },
                {
                    "text": "B",
                    "callback_data": "C1"
                }]
            ]
        }
    }

Body:
I just had a hard time trying to get it to work on my API and I've found the problem. You need to JSON.stringify() the contents of reply_markup that converts the keyboard object and contents into a string first.

Here's an example.

bot.onCommand = function (chat, from, message_id, text, command, commandData) {
    if (command === "test") {
        var keyboard = {
            "inline_keyboard": [
                [
                    {"text": "Yes", "url": "http://www.google.com/"},
                    {"text": "No", "url": "http://www.google.com/"}
                ]
            ]
        };

        var data = {
            "reply_to_message_id": message_id,
            "reply_markup": JSON.stringify(keyboard)
        };

        bot.sendText(chat.id, "test", data, function (isSuccess) {
            console.log(isSuccess);
        });

        return;
    }
}

I wrote this to hopefully make it less confusing.

The output will be:

(test    )
[Yes] [No]

The circler brackets is the message and the square brackets is the buttons. Both in this example opens a link to Google.


问:
R Create a new variable name by partially matching a string from other variable names
I have multiple variable names that I need to combine into a single variable based on a common string of text. My sample data are:

```<code>structure(list(And = c(10L, NA, 10L), and = c(20L, 10L, 10L),
andbc = c(1L, NA, NA), baNdc = c(4L, NA, 5L), ban = c(1L,
NA, 1L)), .Names = c("And", "and", "andbc", "baNdc", "ban"), class = "data.frame", row.names = c(NA, -3L))
</code>```

I would like to create a new variable x, the value of which would be a row sum of the values of the other variables that share the common text string "and" ignoring the case of any of the letters in that string.

I attempted creating the variable by specifying the permutations, which I'm hoping to avoid:

```<code>names1[, 1:5][is.na(names1[, 1:5])] <- 0
names1$x <- sum(names1[which(grepl("And|and|aNd", names(names1)))])
</code>```

The result I get for values of x is a sum total of all values for the variables that meet the text string criteria:

```<code>structure(list(And = c(10, 0, 10), and = c(20L, 10L, 10L), andbc = c(1, 0, 0), baNdc = c(4, 0, 5), ban = c(1, 0, 1), x = c(70, 70, 70)), .Names = c("And", "and", "andbc", "baNdc", "ban", "x"), row.names = c(NA, -3L), class ="data.frame"
</code>```

How can I obtain the row sums based on the text string criteria and avoid having to specify the permutations of upper or lower case?

答:
```<code>colnames(names1) <- tolower(colnames(names1))
</code>```

will rid you for the need for permutations

```<code>names1$x <- rowSums(names1[which(grepl('and', colnames(names1)))], na.rm = TRUE)
</code>```

Body:
I have multiple variable names that I need to combine into a single variable based on a common string of text. My sample data are:

structure(list(And = c(10L, NA, 10L), and = c(20L, 10L, 10L),
andbc = c(1L, NA, NA), baNdc = c(4L, NA, 5L), ban = c(1L,
NA, 1L)), .Names = c("And", "and", "andbc", "baNdc", "ban"), class = "data.frame", row.names = c(NA, -3L))

I would like to create a new variable x, the value of which would be a row sum of the values of the other variables that share the common text string "and" ignoring the case of any of the letters in that string.

I attempted creating the variable by specifying the permutations, which I'm hoping to avoid:

names1[, 1:5][is.na(names1[, 1:5])] <- 0
names1$x <- sum(names1[which(grepl("And|and|aNd", names(names1)))])

The result I get for values of x is a sum total of all values for the variables that meet the text string criteria:

structure(list(And = c(10, 0, 10), and = c(20L, 10L, 10L), andbc = c(1, 0, 0), baNdc = c(4, 0, 5), ban = c(1, 0, 1), x = c(70, 70, 70)), .Names = c("And", "and", "andbc", "baNdc", "ban", "x"), row.names = c(NA, -3L), class ="data.frame"

How can I obtain the row sums based on the text string criteria and avoid having to specify the permutations of upper or lower case?

Body:
colnames(names1) <- tolower(colnames(names1))

will rid you for the need for permutations

names1$x <- rowSums(names1[which(grepl('and', colnames(names1)))], na.rm = TRUE)


问:
Setting Stripe API key to test env for RSpec
How do you set a Stripe API key to the test environment for RSpec?

I am trying to test whether a user could bypass the Stripe charge in the following Custom Checkout action, effectively POSTing to the resource and writing to the database (e.g. using cURL or some other tool).

```<code>  def create

    customer = Stripe::Customer.create(
        :email        => params[:stripeEmail],
        :card         => params[:stripeToken],
    )
    charge = Stripe::Charge.create(
        :customer     => customer.id,
        :amount       => 1000,
    )

    if charge["paid"] == true
      @customer.create(email: params[:stripeEmail],
                       first_name: params[:first_name],
                       last_name:  params[:last_name],
                       agreed_to_terms: params[:agreed_to_terms],
                       )
      UserMailer.welcome_email(@customer).deliver_now
      redirect_to root_url
    else
      flash[:error] = "Something went wrong! Please try again."
      redirect_to error_url
    end

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to :back
  end
</code>```

But the spec requires me to provide an API key.

```<code>  describe 'POST #create' do

    context "with valid credentials" do
      it "but without Stripe, redirects to root_url" do
        @product = create(:valid_credentials)
        post :create, {first_name: "John", last_name: "Doe", stripeEmail: "john@doe.com", agreed_to_terms: true}
        expect(response).to redirect_to root_url
      end
    end
</code>```

as seen below

```<code>No API key provided. Set your API key using "Stripe.api_key = <API-KEY>". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.
</code>```

答:
In your config/secrets.yml add the stripe tokens

```<code>test:
    secret_key_base: <your_secret_key>
    stripe_publishable_key: <your_stripe_publishable_key>
    stripe_secret_key: <your_stripe_secret_key>
    stripe_client_id: <your_stripe_client_id>
</code>```

And in config/initializers/stripe.rb set your stripe_key

```<code>Stripe.api_key = Rails.application.secrets.stripe_secret_key
Stripe.api_version = '2015-04-07'
</code>```

You can get your Stripe API key in https://dashboard.stripe.com/account/apikeys
Remember to keep your keys safe, don't share and exclude your secrets.yml file from the version-control repository (github, bitbucket, etc)

Body:
How do you set a Stripe API key to the test environment for RSpec?

I am trying to test whether a user could bypass the Stripe charge in the following Custom Checkout action, effectively POSTing to the resource and writing to the database (e.g. using cURL or some other tool).

  def create

    customer = Stripe::Customer.create(
        :email        => params[:stripeEmail],
        :card         => params[:stripeToken],
    )
    charge = Stripe::Charge.create(
        :customer     => customer.id,
        :amount       => 1000,
    )

    if charge["paid"] == true
      @customer.create(email: params[:stripeEmail],
                       first_name: params[:first_name],
                       last_name:  params[:last_name],
                       agreed_to_terms: params[:agreed_to_terms],
                       )
      UserMailer.welcome_email(@customer).deliver_now
      redirect_to root_url
    else
      flash[:error] = "Something went wrong! Please try again."
      redirect_to error_url
    end

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to :back
  end

But the spec requires me to provide an API key.

  describe 'POST #create' do

    context "with valid credentials" do
      it "but without Stripe, redirects to root_url" do
        @product = create(:valid_credentials)
        post :create, {first_name: "John", last_name: "Doe", stripeEmail: "john@doe.com", agreed_to_terms: true}
        expect(response).to redirect_to root_url
      end
    end

as seen below

No API key provided. Set your API key using "Stripe.api_key = <API-KEY>". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.

Body:
In your config/secrets.yml add the stripe tokens

test:
    secret_key_base: <your_secret_key>
    stripe_publishable_key: <your_stripe_publishable_key>
    stripe_secret_key: <your_stripe_secret_key>
    stripe_client_id: <your_stripe_client_id>

And in config/initializers/stripe.rb set your stripe_key

Stripe.api_key = Rails.application.secrets.stripe_secret_key
Stripe.api_version = '2015-04-07'

You can get your Stripe API key in https://dashboard.stripe.com/account/apikeys
Remember to keep your keys safe, don't share and exclude your secrets.yml file from the version-control repository (github, bitbucket, etc)


问:
Set specific date with string to dateTimePicker
I'm trying to set specific date for dateTimePicker, but not sure how to do it properly. The goal is to load date and time of user previous load insert  from text document, each time user loads applications, and then to save new date as string for next using to load into dateTimePicker.

This way it does not sets and I'm not sure how to load string like "25/03/2017" to:

```<code>   dateTimePicker.Value = new DateTime(1978, 05, 22);
</code>```

to use it as string for further processing:

```<code>   string bd = dateTimePicker.Value.ToString("yyyy-M-d");
</code>```

答:
You can use DateTime.ParseExact to parse date string in the format which you have:

```<code>dateTimePicker.Value =
  DateTime.ParseExact("25/03/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
</code>```

Note that when you are getting date from DateTimePicker control you are converting same date to another format, and it will look like 2017-3-25.

Body:
I'm trying to set specific date for dateTimePicker, but not sure how to do it properly. The goal is to load date and time of user previous load insert  from text document, each time user loads applications, and then to save new date as string for next using to load into dateTimePicker.

This way it does not sets and I'm not sure how to load string like "25/03/2017" to:

   dateTimePicker.Value = new DateTime(1978, 05, 22);

to use it as string for further processing:

   string bd = dateTimePicker.Value.ToString("yyyy-M-d");

Body:
You can use DateTime.ParseExact to parse date string in the format which you have:

dateTimePicker.Value =
  DateTime.ParseExact("25/03/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Note that when you are getting date from DateTimePicker control you are converting same date to another format, and it will look like 2017-3-25.


问:
Firebase setup on WebStorm
I'm currently developing an app on React Native and, after trying Meteor as a backend, wanted to try Firebase.
I followed the Firebase setup instruction and had a first issue when I had to sync my Gradle file: I just can't via WebStorm.

Now, I don't know if this has an impact but my simple RN project which looks like this

```<code>import * as firebase from 'firebase';

const firebaseConfig = {
        apiKey: "***",
        authDomain: "**.firebaseapp.com",
        databaseURL: "https://**.firebaseio.com",
    };
const firebaseApp = firebase.initializeApp(firebaseConfig);

***

componentDidMount(){
        const rootRef = firebaseApp.database().ref().child('react');
        const speedRef = rootRef.child('speed');
        speedRef.on('value', snap => {
            this.setState({
                speed: snap.val(),
            });
        });
    }
</code>```

...doesn't get any data from Firebase (whereas, of course there is some) and I don't see any error message!
My app launches properly and display basic data.

Could you let me know if this already happened to you?
Is it possible to use only WebStorm for RN + Firebase?

PS: I setup Google services etc...as requested in the docs of course.

答:
Well...so:

the public database access was not enabled on Firebase, thus, because not authenticated in my test App, it was normal to see nothing --> now it is ok

I realized I don't need to setup an Android mobile app to make RN and Firebase work

So no problem anymore, if there are lost people like me out there I hope it helped!

Title: Firebase setup on WebStorm

Body:
I'm currently developing an app on React Native and, after trying Meteor as a backend, wanted to try Firebase.
I followed the Firebase setup instruction and had a first issue when I had to sync my Gradle file: I just can't via WebStorm.

Now, I don't know if this has an impact but my simple RN project which looks like this

import * as firebase from 'firebase';

const firebaseConfig = {
        apiKey: "***",
        authDomain: "**.firebaseapp.com",
        databaseURL: "https://**.firebaseio.com",
    };
const firebaseApp = firebase.initializeApp(firebaseConfig);

***

componentDidMount(){
        const rootRef = firebaseApp.database().ref().child('react');
        const speedRef = rootRef.child('speed');
        speedRef.on('value', snap => {
            this.setState({
                speed: snap.val(),
            });
        });
    }

...doesn't get any data from Firebase (whereas, of course there is some) and I don't see any error message!
My app launches properly and display basic data.

Could you let me know if this already happened to you?
Is it possible to use only WebStorm for RN + Firebase?

PS: I setup Google services etc...as requested in the docs of course.


问:
how to create empty file in python
I would like to create an empty file in Python. But I have difficulty creating one..Below is the Python code I used to create but it gives me error:

```<code>gdsfile  = "/home/hha/temp.gds"
if not (os.path.isfile(gdsfile)):
    os.system(touch gdsfile)
</code>```

Error I got:
 File "/home/hha/bin/test.py", line 29
    os.system(touch gdsfile)
                          ^
SyntaxError: invalid syntax

But from the command line, I am able to create new file using: touch

Thank you very much for your help
Howard

答:
First you have a syntax error because os.system() expects a string argument and you have not provided one. This will fix your code:

```<code>os.system('touch {}'.format(gdsfile))
</code>```

which constructs a string and passes it to os.system().

But a better way (in Python >= 3.3) is to simply open the file using the open() builtin:

```<code>gdsfile  = "/home/hha/temp.gds"
try:
   open(gdsfile, 'x')
except FileExistsError:
   pass
</code>```

This specifies mode x which means exclusive creation - the operation will fail if the file already exists, but create it if it does not.

This is safer than using os.path.isfile() followed by open() because it avoids the potential race condition where the file might be created by another process in between the check and the create.

If you are using Python 2, or an earlier version of Python 3, you can use os.open() to open the file with the exclusive flag.

```<code>import os
import errno

gdsfile  = "/home/hha/temp.gds"
try:
    os.close(os.open(gdsfile, os.O_CREAT|os.O_EXCL))
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise
</code>```

Title: how to create empty file in python

Body:
I would like to create an empty file in Python. But I have difficulty creating one..Below is the Python code I used to create but it gives me error:

gdsfile  = "/home/hha/temp.gds"
if not (os.path.isfile(gdsfile)):
    os.system(touch gdsfile)

Error I got:
 File "/home/hha/bin/test.py", line 29
    os.system(touch gdsfile)
                          ^
SyntaxError: invalid syntax

But from the command line, I am able to create new file using: touch

Thank you very much for your help
Howard

Body:
First you have a syntax error because os.system() expects a string argument and you have not provided one. This will fix your code:

os.system('touch {}'.format(gdsfile))

which constructs a string and passes it to os.system().

But a better way (in Python >= 3.3) is to simply open the file using the open() builtin:

gdsfile  = "/home/hha/temp.gds"
try:
   open(gdsfile, 'x')
except FileExistsError:
   pass

This specifies mode x which means exclusive creation - the operation will fail if the file already exists, but create it if it does not.

This is safer than using os.path.isfile() followed by open() because it avoids the potential race condition where the file might be created by another process in between the check and the create.

If you are using Python 2, or an earlier version of Python 3, you can use os.open() to open the file with the exclusive flag.

import os
import errno

gdsfile  = "/home/hha/temp.gds"
try:
    os.close(os.open(gdsfile, os.O_CREAT|os.O_EXCL))
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise


问:
gke cant disable Transparent Huge Pages... permission denied
I am trying to run a redis image in gke. It works except I get the dreaded "Transparent Huge Pages" warning:

```<code>WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
</code>```

Redis is currently too slow to be useful... So I tied turning off THP:

```<code>sheena@gke-projectwaxd-cluster-default-pool-23593a74-wxrv ~ $ cat  /sys/kernel/mm/transparent_hugepage/enabled
always [madvise] never
sheena@gke-projectwaxd-cluster-default-pool-23593a74-wxrv ~ $ echo never >  /sys/kernel/mm/transparent_hugepage/enabled
-bash: /sys/kernel/mm/transparent_hugepage/enabled: Permission denied
sheena@gke-projectwaxd-cluster-default-pool-23593a74-wxrv ~ $ sudo echo never >  /sys/kernel/mm/transparent_hugepage/enabled
-bash: /sys/kernel/mm/transparent_hugepage/enabled: Permission denied
</code>```

These permission errors are disconcerting. Redis wants THP off so it can work properly.

I did a little digging and found that google uses a special os image that makes /sys/ a read-only path. There's an alternative image that's based on Debian 7. It got me all excited but in the end I have exactly the same problem.

So how do I stop redis from being effected by THP on Google container engine?

It's not like I'm doing something unique here. Running databases in containers is pretty normal. And it's pretty normal for a database to malfunction when THP is enabled. So... what am I missing here?

答:
Your command is slightly incorrect: echo runs as root but the redirection itself (>) runs as user so it can't write /sys/.

The following command works fine both on container-vm (debian based) and gci (chromeos based):

```<code>sudo sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'
</code>```

Persisting this setting on container-vm

Add this kernel command line parameter into /etc/default/grub (don't forget to run sudo update-grub and sudo reboot afterwards):

```<code>GRUB_CMDLINE_LINUX="... transparent_hugepage=never"
</code>```

Persisting this setting on gci

First, using the cloud console copy the instance template that is in use by the node pool.

Second, under metadata change the value for userdata:

```<code>#cloud-config

write_files:
  - path: /etc/systemd/system/hugepage.service
    permissions: 0644
    owner: root
    content: |
      [Unit]
      Description=Disable THP

      [Service]
      Type=oneshot
      ExecStart=/bin/sh -c "echo never > /sys/kernel/mm/transparent_hugepage/enabled"

      [Install]
      WantedBy=kubernetes.target
...
runcmd:
 - ...
 - systemctl enable hugepage.service
 - systemctl start kubernetes.target
</code>```

Third, change the instance template to the newly created one:

```<code>gcloud compute instance-groups managed set-instance-template \
  gke-YOUCLUSTER-YOURPOOL-grp \
  --template=YOURNEWTEMPLATENAME \
  --zone=...
</code>```

Forth, recreate the instace(s):

```<code>gcloud compute instance-groups managed recreate-instances \
   gke-YOUCLUSTER-YOURPOOL-grp \
   --zone=... \
   --instances=...
</code>```

The instances will loose all data and come up with THP disabled. All new instances will have THP disabled as well (in this node pool).

Body:
I am trying to run a redis image in gke. It works except I get the dreaded "Transparent Huge Pages" warning:

WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.

Redis is currently too slow to be useful... So I tied turning off THP:

sheena@gke-projectwaxd-cluster-default-pool-23593a74-wxrv ~ $ cat  /sys/kernel/mm/transparent_hugepage/enabled
always [madvise] never
sheena@gke-projectwaxd-cluster-default-pool-23593a74-wxrv ~ $ echo never >  /sys/kernel/mm/transparent_hugepage/enabled
-bash: /sys/kernel/mm/transparent_hugepage/enabled: Permission denied
sheena@gke-projectwaxd-cluster-default-pool-23593a74-wxrv ~ $ sudo echo never >  /sys/kernel/mm/transparent_hugepage/enabled
-bash: /sys/kernel/mm/transparent_hugepage/enabled: Permission denied

These permission errors are disconcerting. Redis wants THP off so it can work properly.

I did a little digging and found that google uses a special os image that makes /sys/ a read-only path. There's an alternative image that's based on Debian 7. It got me all excited but in the end I have exactly the same problem.

So how do I stop redis from being effected by THP on Google container engine?

It's not like I'm doing something unique here. Running databases in containers is pretty normal. And it's pretty normal for a database to malfunction when THP is enabled. So... what am I missing here?

Body:
Your command is slightly incorrect: echo runs as root but the redirection itself (>) runs as user so it can't write /sys/.

The following command works fine both on container-vm (debian based) and gci (chromeos based):

sudo sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'

Persisting this setting on container-vm

Add this kernel command line parameter into /etc/default/grub (don't forget to run sudo update-grub and sudo reboot afterwards):

GRUB_CMDLINE_LINUX="... transparent_hugepage=never"

Persisting this setting on gci

First, using the cloud console copy the instance template that is in use by the node pool.

Second, under metadata change the value for userdata:

#cloud-config

write_files:
  - path: /etc/systemd/system/hugepage.service
    permissions: 0644
    owner: root
    content: |
      [Unit]
      Description=Disable THP

      [Service]
      Type=oneshot
      ExecStart=/bin/sh -c "echo never > /sys/kernel/mm/transparent_hugepage/enabled"

      [Install]
      WantedBy=kubernetes.target
...
runcmd:
 - ...
 - systemctl enable hugepage.service
 - systemctl start kubernetes.target

Third, change the instance template to the newly created one:

gcloud compute instance-groups managed set-instance-template \
  gke-YOUCLUSTER-YOURPOOL-grp \
  --template=YOURNEWTEMPLATENAME \
  --zone=...

Forth, recreate the instace(s):

gcloud compute instance-groups managed recreate-instances \
   gke-YOUCLUSTER-YOURPOOL-grp \
   --zone=... \
   --instances=...

The instances will loose all data and come up with THP disabled. All new instances will have THP disabled as well (in this node pool).