问:
Disable CTRL+C on JTable (after duoble click on a cell)
I've been asked to edit a java desktop application developed by others. I've never worked on Java desktop application before.

There's a JTable and I have to prevent the user from doing CTRL+C and copy the value of a cell. I did it.

The problem is that when the user double clicks a cell and the cursor appears (as you can see from the pic)

I'm not able to prevent the user to do CTRL+C. How can I do it?

答:
The problem is that when the user double clicks a cell and the cursor appears

Focus is no longer on the JTable. It is on the editor of the cell which happens to be a JTextField. So you need to remove the copy functionality of the text field.

You do this by removing the Key Binding for the "Control C" on the text field:

```<code>DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Object.class);
JTextField textField = (JTextField)editor.getComponent();
InputMap im = textField.getInputMap();
im.put(KeyStroke.getKeyStroke("control C"), "none");
</code>```

You will need to do this for each editor type you have in your table. For example if you have Integer values then you would need to get the editor for the Integer.class and remove its key binding as well.

Note, the same approach can be used for the table, except you use the following InputMap for the table:

```<code>InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
</code>```

Body:
The problem is that when the user double clicks a cell and the cursor appears

Focus is no longer on the JTable. It is on the editor of the cell which happens to be a JTextField. So you need to remove the copy functionality of the text field.

You do this by removing the Key Binding for the "Control C" on the text field:

DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Object.class);
JTextField textField = (JTextField)editor.getComponent();
InputMap im = textField.getInputMap();
im.put(KeyStroke.getKeyStroke("control C"), "none");

You will need to do this for each editor type you have in your table. For example if you have Integer values then you would need to get the editor for the Integer.class and remove its key binding as well.

Note, the same approach can be used for the table, except you use the following InputMap for the table:

InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);


来源: stackexchange

问:
Variables in Kubernetes ConfigMaps
I'm currently working with some configmaps and I've noticed, that there are some documents in the configmap having redundant values/ referencing the same value e.g.

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
  labels:
    app: my-app
data:
  some_file: |-
     ...
     foo1=bar
     ...
  some_other_file: |-
     ...
     foo2=bar
     ...
</code>```

Is it somehow possible, to use a variable instead of writing bar two times?
This way I wouldn't have to search every config file if bar changes at some point.

答:
No, it's not possible.

If the problems gets worse, you can always start using kustomize or Helm, which allow you to create templates for your Kubernetes manifests, and use variables on those templates.

ContentLicense: CC BY-SA 4.0

Title: Variables in Kubernetes ConfigMaps

Body:
I'm currently working with some configmaps and I've noticed, that there are some documents in the configmap having redundant values/ referencing the same value e.g.

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
  labels:
    app: my-app
data:
  some_file: |-
     ...
     foo1=bar
     ...
  some_other_file: |-
     ...
     foo2=bar
     ...

Is it somehow possible, to use a variable instead of writing bar two times?
This way I wouldn't have to search every config file if bar changes at some point.


问:
How do I get the id of a element in a form?
I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.

```<code>var form = document.getElementById("myForm");
form.elements[i].value
</code>```

Those lines of code is what I tried but it doesn't seem to work.

Edit:

```<code>function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm").elements;

                for(var i = 0; i < 1 ; i++){
                    var id = form.elements[i].id;
                    sessionStorage.setItem(id,"false");
                }
            localStorage.setItem("run", true);
        }
    }
</code>```

So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.

Edit2:

```<code>function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm");
                var tot = document.getElementById("myForm").length;

                for(var i = 0; i < tot ; i++){
                    sessionStorage.setItem(form.elements[i].id,"false");
                }
            localStorage.setItem("run", true);
        }
    }
</code>```

This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.

```<code> function loader(){
        var form = document.getElementById("myForm");
        var tot = 5;

        for(var i = 0; i < 5 ; i++){
            if(sessionStorage.getItem(form.elements[i].id) === "true"){
                document.getElementById(form.elements[i].id).style.backgroundColor = "green";
                return ;
            }else{
                document.getElementById(form.elements[i].id).style.backgroundColor = "red";
                return false;
            }
        }
    }
</code>```

Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.

答:
It's available via the id property on the element:

```<code>var id = form.elements[i].id;
</code>```

More on MDN and in the spec.

Live Example:

var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="myForm">
<input type="text" id="theText">
</form></code>```

Body:
I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.

var form = document.getElementById("myForm");
form.elements[i].value

Those lines of code is what I tried but it doesn't seem to work.

Edit:

function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm").elements;

                for(var i = 0; i < 1 ; i++){
                    var id = form.elements[i].id;
                    sessionStorage.setItem(id,"false");
                }
            localStorage.setItem("run", true);
        }
    }

So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.

Edit2:

function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm");
                var tot = document.getElementById("myForm").length;

                for(var i = 0; i < tot ; i++){
                    sessionStorage.setItem(form.elements[i].id,"false");
                }
            localStorage.setItem("run", true);
        }
    }

This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.

 function loader(){
        var form = document.getElementById("myForm");
        var tot = 5;

        for(var i = 0; i < 5 ; i++){
            if(sessionStorage.getItem(form.elements[i].id) === "true"){
                document.getElementById(form.elements[i].id).style.backgroundColor = "green";
                return ;
            }else{
                document.getElementById(form.elements[i].id).style.backgroundColor = "red";
                return false;
            }
        }
    }

Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.

Body:
It's available via the id property on the element:

var id = form.elements[i].id;

More on MDN and in the spec.

Live Example:

var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);

<form id="myForm">
<input type="text" id="theText">
</form>


问:
C++ creating new operators and overloading the current ones
I am writing code for transposing a matrix as a part of learning C++. What I am doing is operator overloading. But, usually the notation for transposing a matrix is '.

Is ' even an operator? I understand if it is between ' ' you notate a character, and if you use " " you notate a string. But are these operators or not? Can I overload them as individual characters or even as whole?

Can I make new operators in C++ that only work on an object of a specific class? The trick I've used is overloading the known operators like +, -, ^, ... and then with #define I change how the preprocessor processes the text, but in the end I would still override an existing operator and I cannot use any of the special symbols but rather letters.

答:
You can only overload existing operators.

You can fake it a bit.

```<code>namespace my_operator {
  struct transpose_t {};
  constexpr tranpose_t transpose{};

  template<class Matrix>
  Matrix operator^( Matrix lhs, tranpose_t ) {
    lhs.Transpose();
    return lhs;
  }
}
</code>```

given that, and a matrix type that has a .Transpose() method that self-transposes, we get:

```<code>using my_operator::transpose;

MATRIX m = {/* whatever */};
MATRIX tm = m^transpose;
</code>```

and tm will be the transpose of m.

Body:
You can only overload existing operators.

You can fake it a bit.

namespace my_operator {
  struct transpose_t {};
  constexpr tranpose_t transpose{};

  template<class Matrix>
  Matrix operator^( Matrix lhs, tranpose_t ) {
    lhs.Transpose();
    return lhs;
  }
}

given that, and a matrix type that has a .Transpose() method that self-transposes, we get:

using my_operator::transpose;

MATRIX m = {/* whatever */};
MATRIX tm = m^transpose;

and tm will be the transpose of m.


问:
Codeigniter CSRF valid for only one time ajax request
I want to upload image on the server on change event of jQuery but using codeigniter csrf I am able to upload image only one time. How can I upload images using ajax for multiple requests.Please keep in mind when I set this

```<code>config['csrf_protection'] = FALSE;
</code>```

then I am able to send multiple request jQuery onchange event but when csrf_protection is going to be false then I think there is no advantage of csrf. so the question is how can I send multiple requests using ajax while csrf_protection is enable. My jquery code is following

```<code>$("#avatar").change(function(){
    var link = $("#avatar").val();
    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',"id":"hello","link":link},
        success : function(data)
        {
            alert(data);
        }
    });
});
</code>```

My controller:

```<code>public function test()
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = 500;
    $config['max_width'] = 260;
    $config['max_height'] = 260;
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('link')) {
        echo "error";
    } else {
        $data = array('upload_data' => $this->upload->data());
        $image_name = $data['upload_data']['file_name'];
        echo $image_name;
    }
}
</code>```

答:
$config['csrf_regenerate'] = TRUE;

keep auto generate to true it will be more safer.
In similar case when csrf is expired in first request. What i have implemented

```<code>$(document).ajaxComplete(function (event, xhr, settings) {
 let response = xhr.responseText,
 let obj = JSON.parse(response),
 let csrfData = obj.csrf;
 document.querySelector('input[name="' + csrfData.name + '"]').value = csrfData.hash;
}); //Also here you can update any other non input element
</code>```

In every ajax response we are passing csrf data in which latest csrf data will be replaced with current one

Sample response from request

```<code>{
csrf : {
  name : 'csrf_name',
  hash : 'qw76sd7s6f78sdfs8dfs9df8cx9'
 }
}
</code>```

I update csrf token in every ajax request. Also don't choose this method if you are working with multi tab environment

Body:
I want to upload image on the server on change event of jQuery but using codeigniter csrf I am able to upload image only one time. How can I upload images using ajax for multiple requests.Please keep in mind when I set this

config['csrf_protection'] = FALSE;

then I am able to send multiple request jQuery onchange event but when csrf_protection is going to be false then I think there is no advantage of csrf. so the question is how can I send multiple requests using ajax while csrf_protection is enable. My jquery code is following

$("#avatar").change(function(){
    var link = $("#avatar").val();
    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',"id":"hello","link":link},
        success : function(data)
        {
            alert(data);
        }
    });
});

My controller:

public function test()
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = 500;
    $config['max_width'] = 260;
    $config['max_height'] = 260;
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('link')) {
        echo "error";
    } else {
        $data = array('upload_data' => $this->upload->data());
        $image_name = $data['upload_data']['file_name'];
        echo $image_name;
    }
}

Body:
$config['csrf_regenerate'] = TRUE;

keep auto generate to true it will be more safer.
In similar case when csrf is expired in first request. What i have implemented

$(document).ajaxComplete(function (event, xhr, settings) {
 let response = xhr.responseText,
 let obj = JSON.parse(response),
 let csrfData = obj.csrf;
 document.querySelector('input[name="' + csrfData.name + '"]').value = csrfData.hash;
}); //Also here you can update any other non input element

In every ajax response we are passing csrf data in which latest csrf data will be replaced with current one

Sample response from request

{
csrf : {
  name : 'csrf_name',
  hash : 'qw76sd7s6f78sdfs8dfs9df8cx9'
 }
}

I update csrf token in every ajax request. Also don't choose this method if you are working with multi tab environment


问:
Excel IF statement to find specific actions against a record
The Excel consists of two columns 'Person Number' and 'Action Code'. There can be multiple occurrences of a 'Person Number' for first occurrence the 'Action Code' needs to be 'HIRE' rest occurrences needs to be 'ASG_CHANGE'.

Used below code to get the 'Expected Action Code' but got 'Invalid Code Output' instead.

=IF($A2:$A3=$A3,"HIRE","ASG_CHANGE")

答:
You need to test whether the value changed:</p>

```<code>=IF(A1<>A2,"HIRE","ASG_CHANGE")
</code>```

Body:
You need to test whether the value changed:

=IF(A1<>A2,"HIRE","ASG_CHANGE")


问:
How to make a loop that successively includes one more element of a numpy array in order to calculate the running variance?
I have numbers stored in an array like [1, 6, 12, 4...].  I want to do a calculation where each new iteration will use one more element of the array.

For example, the first iteration will use only the number 1.

The second iteration will use 1 and 6.

The third will use 1, 6, and 12, and so on.

More detail for anyone interested in statistics/variance in Python:

I want to calculate running variance on the data in the array. It seems straightforward to get variance on a whole array in Python. So I'll put my array up to element i inside the loop.  I will calculate variance on the array as looping progresses and the array "grows."  If anyone knows a better way to do this, I would be grateful to know.

答:
You can use slices:

>>>> seq = [1, 2, 3, 4]
>>>> for i in range(len(seq)):
....     print(sum(seq[:i+1]))
....
1
3
6
10
```

Hope it helps.

Body:
You can use slices:

>>>> seq = [1, 2, 3, 4]
>>>> for i in range(len(seq)):
....     print(sum(seq[:i+1]))
....
1
3
6
10

Hope it helps.


问:
Overload resolution in case of templates and inheritance in unique_ptr
I have two classes:

```<code>class Base {};
class Derived : public Base {};
</code>```

And two overloaded functions:

```<code>void call(std::unique_ptr<Base> op)
{
    std::cout << "First overloading" << std::endl;
}

template<class F>
void call(F f)
{
    std::cout << "Second overloading" << std::endl;
}
</code>```

Let's call it with unique_ptr of Derived

```<code>call(std::make_unique<Derived>());
</code>```

I expect calling first function, however second is called instead.
Why compiler choose generic function instead of specific one? Overload resolution does not support inheritance and polymorphism?
If so, how I can fix it and call first function?

答:
The problem is, the 2nd overload is an exact match when T being deduced as std::unique_ptr<Derived>; while the 1st overload requires an implicit conversion from std::unique_ptr<Derived> to std::unique_ptr<Base>. Then the 2nd one wins in overload resolution.

You can add apply SFINAE:

```<code>template<class F>
std::enable_if_t<!std::is_convertible_v<F, std::unique_ptr<Base>>> call(F f)
{
    std::cout << "Second overloading" << std::endl;
}
</code>```

LIVE

Body:
I have two classes:

class Base {};
class Derived : public Base {};

And two overloaded functions:

void call(std::unique_ptr<Base> op)
{
    std::cout << "First overloading" << std::endl;
}

template<class F>
void call(F f)
{
    std::cout << "Second overloading" << std::endl;
}

Let's call it with unique_ptr of Derived

call(std::make_unique<Derived>());

I expect calling first function, however second is called instead.
Why compiler choose generic function instead of specific one? Overload resolution does not support inheritance and polymorphism?
If so, how I can fix it and call first function?

Body:
The problem is, the 2nd overload is an exact match when T being deduced as std::unique_ptr<Derived>; while the 1st overload requires an implicit conversion from std::unique_ptr<Derived> to std::unique_ptr<Base>. Then the 2nd one wins in overload resolution.

You can add apply SFINAE:

template<class F>
std::enable_if_t<!std::is_convertible_v<F, std::unique_ptr<Base>>> call(F f)
{
    std::cout << "Second overloading" << std::endl;
}

LIVE


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
A few weeks ago I started development on a new project. I had complete control over the tools I could use. I started with db40 because I wanted to eliminate this question altogether; I just wanted to persist my objects directly, forget about ADO.NET or OR/M. But db40 had problems so I ha to abandon it.

My next choice was ADO.NET because I thought it would be fast and easy. But I had to write way too much code, use too much "string sql" and it was just a chore altogether. I mean, it was a royal PITA and after coding two repositories with it I wanted to cut my wrists.

My third choice was NHibernate. I have had previous problems with NHibernate in a situation where I needed to use disconnected objects (such was the case this time as well, hence why it took me three tries to get to it). But that was NHibernate 1.2. This time I got the 2.0 binaries and had zero problems with updating disconnected objects. I also had to write way fewer lines of code and it was super-simple when I needed to refactor things, which was probably most important since my design changed rapidly.

I'm sold on NHibernate now. It appears highly optimized as well. Honestly, I can't find a negative to it. And there's no stored procedures.

I know it's my OR/M of choice going forward and I'll never write straight ADO.NET again.

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: Chris Holmes


问:
How to get the result from API not only the response code
I am trying to get the result of foreign currency  exchange rate but on sending a Get request to the API "https://data.fixer.io/api/".." instead of getting a result, I am getting a response code 200  but no exchange rates are there

```<code>def main():
    res=requests.get("http://data.fixer.io/api/latest? access_key = YOUR_ACCESS_KEY& base = INR& symbols = USD")
    if res.status_code!=200:
        raise Exception("Error : APIdidn't work")
    print(res)

</code>```

Expected result:

```<code>{
  "success":true,
  "timestamp":1559223544,
  "base":"INR",
  "rates":{
    "USD":0.014,

  }
}
</code>```

Actual result :

```<code><Response [200]>
</code>```

答:
To use the data that you're pulling from the API - you need to convert it to readable json. DeepSpace is correct - you need to use res.json()

Append the data to a variable if you want to iterate through it or utilize it further.

data = res.json()

Body:
I am trying to get the result of foreign currency  exchange rate but on sending a Get request to the API "https://data.fixer.io/api/".." instead of getting a result, I am getting a response code 200  but no exchange rates are there

def main():
    res=requests.get("http://data.fixer.io/api/latest? access_key = YOUR_ACCESS_KEY& base = INR& symbols = USD")
    if res.status_code!=200:
        raise Exception("Error : APIdidn't work")
    print(res)

Expected result:

{
  "success":true,
  "timestamp":1559223544,
  "base":"INR",
  "rates":{
    "USD":0.014,

  }
}

Actual result :

<Response [200]>


问:
Input with tkinter?
Here's my principal script code

from colorama import init, Fore, Back, Style
import commands
import config
import sys

# Coloroma autoreset
init(autoreset=True)

def check_database():
        # Database Check.
        while True:
            db = input("Check for new databases? Y/N: ")
            if db.lower() == 'y':
                commands.db_download()
                break
            elif db.lower() == 'n':
                break
            else:
                continue

def client_use():
    # Decide which client to use.
    while True:
        client = input("JP or GLB? J/G: ")
        if client.lower() == 'j':
            config.client = 'japan'
            break
        elif client.lower() == 'g':
            config.client = 'global'
            break
        else:
            continue
```

<p>I want at the launch of the gui for example a button with "Launch bot" (that i managed to do) and right after my script above starts. Like it asks "Check for new db?" and i have two buttons "Yes" or "No" and depending on what i click, it sends an input with "y" or "n" and it continues the corresponding code lines.That point i didnt manage to do.</p>

<p>And here's what i managed to do for now, which isn't much at all</p>

<pre class="lang-py prettyprint-override"><code>import tkinter
import questions

top = tkinter.Tk()

Lancement = tkinter.Button(top, text ="Lancer", command = questions)
Lancement.pack()

top.mainloop()
</code>```

How could i manage to do that plz?

答:
Tkinter comes with some additional dialog boxes for asking questions (see https://pythonspot.com/tkinter-askquestion-dialog/)

```<code>from tkinter import *
from tkinter import messagebox

def launch():
    response = messagebox.askyesno("Server Connection", "Check for new db?")
    if response:
        print("You clicked yes")
    else:
        print("You clicked no")

root = Tk()
button = Button(root,text="Launch",command=launch)
button.grid()
root.mainloop()
</code>```

Clicking on the launch button will bring up a dialog with yes/no buttons.

You will need to re-structure your code to accept the responses from these dialogs rather than the command line text input functions.

Title: Input with tkinter?

Body:
Here's my principal script code

from colorama import init, Fore, Back, Style
import commands
import config
import sys

# Coloroma autoreset
init(autoreset=True)

def check_database():
        # Database Check.
        while True:
            db = input("Check for new databases? Y/N: ")
            if db.lower() == 'y':
                commands.db_download()
                break
            elif db.lower() == 'n':
                break
            else:
                continue

def client_use():
    # Decide which client to use.
    while True:
        client = input("JP or GLB? J/G: ")
        if client.lower() == 'j':
            config.client = 'japan'
            break
        elif client.lower() == 'g':
            config.client = 'global'
            break
        else:
            continue

I want at the launch of the gui for example a button with "Launch bot" (that i managed to do) and right after my script above starts. Like it asks "Check for new db?" and i have two buttons "Yes" or "No" and depending on what i click, it sends an input with "y" or "n" and it continues the corresponding code lines.That point i didnt manage to do.

And here's what i managed to do for now, which isn't much at all

import tkinter
import questions

top = tkinter.Tk()

Lancement = tkinter.Button(top, text ="Lancer", command = questions)
Lancement.pack()

top.mainloop()

How could i manage to do that plz?

Body:
Tkinter comes with some additional dialog boxes for asking questions (see https://pythonspot.com/tkinter-askquestion-dialog/)

from tkinter import *
from tkinter import messagebox

def launch():
    response = messagebox.askyesno("Server Connection", "Check for new db?")
    if response:
        print("You clicked yes")
    else:
        print("You clicked no")

root = Tk()
button = Button(root,text="Launch",command=launch)
button.grid()
root.mainloop()

Clicking on the launch button will bring up a dialog with yes/no buttons.

You will need to re-structure your code to accept the responses from these dialogs rather than the command line text input functions.


问:
How to implement bootstrap navbar as component in lit-html/lit-element
I would like to know how to implement bootstrap navbar in lit-element/lit-html

I have created navbar component in lit-element but navbar dropdown and toggling  are not working.

I have to implement fixed-top navbar as a lit-element component in html.
please check the code and got stuck.
If any alternatives, kindly provide solution.

```<code>// component.js
import { LitElement, html } from 'lit-element';

class MyElement extends LitElement {
  render(){
    return html`
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
      <div>
            <header>
    <nav class="navbar navbar-expand-md navbar-light bg-light fixed-top">
      <a class="navbar-brand"><img src="../images/send4x.svg" alt="" class="logoC mr-4"></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown mr-4">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownProvider" data-toggle="dropdown"
              aria-haspopup="true" aria-expanded="false">
              Providers
            </a>
            <div class="dropdown-menu mr-4" aria-labelledby="navbarDropdownProvider">
              <a class="dropdown-item"
                href="#">trans</a>
              <a class="dropdown-item"
                href="#">fund</a>
            </div>
          </li>
                  </ul>
      </div>
    </nav>
  </header>
      </div>
    `;
  }
}
customElements.define('my-element', MyElement);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

  <script src="/node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
  <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>

  <script type="module" src="./my-element.js"></script>
  <title>lit-element code sample</title>
</head>
<body>
  <my-element>  </my-element>
</body>
</html>

</code>```

答:
You may use Bootstrap with some 3rd parties imported to shadow dom classes, but I think the direct way may use lit-html like :

demo

```<code>import { html, render } from 'lit-html/lit-html.js';

const myTemplate = ()=>  html`

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
      <div>
            <header>
    <nav class="navbar navbar-expand-md navbar-light bg-light fixed-top">
      <a class="navbar-brand"><img src="../images/send4x.svg" alt="" class="logoC mr-4"></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown mr-4">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownProvider" data-toggle="dropdown"
              aria-haspopup="true" aria-expanded="false">
              Providers
            </a>
            <div class="dropdown-menu mr-4" aria-labelledby="navbarDropdownProvider">
              <a class="dropdown-item"
                href="#">trans</a>
              <a class="dropdown-item"
                href="#">fund</a>
            </div>
          </li>
                  </ul>
      </div>
    </nav>
  </header>
      </div>

    `;

render(myTemplate(), document.body);
</code>```

Body:
I would like to know how to implement bootstrap navbar in lit-element/lit-html

I have created navbar component in lit-element but navbar dropdown and toggling  are not working.

I have to implement fixed-top navbar as a lit-element component in html.
please check the code and got stuck.
If any alternatives, kindly provide solution.

// component.js
import { LitElement, html } from 'lit-element';

class MyElement extends LitElement {
  render(){
    return html`
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

      </button>

              Providers

              trans
              fund

    `;
  }
}
customElements.define('my-element', MyElement);

index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

  <title>lit-element code sample</title>

  <my-element>  </my-element>

Body:
You may use Bootstrap with some 3rd parties imported to shadow dom classes, but I think the direct way may use lit-html like :

demo

import { html, render } from 'lit-html/lit-html.js';

const myTemplate = ()=>  html`

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
      <div>
            <header>
    <nav class="navbar navbar-expand-md navbar-light bg-light fixed-top">
      <a class="navbar-brand"><img src="../images/send4x.svg" alt="" class="logoC mr-4"></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown mr-4">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownProvider" data-toggle="dropdown"
              aria-haspopup="true" aria-expanded="false">
              Providers
            </a>
            <div class="dropdown-menu mr-4" aria-labelledby="navbarDropdownProvider">
              <a class="dropdown-item"
                href="#">trans</a>
              <a class="dropdown-item"
                href="#">fund</a>
            </div>
          </li>
                  </ul>
      </div>
    </nav>
  </header>
      </div>

    `;

render(myTemplate(), document.body);


问:
TypeError: Cannot read property 'chat' of undefined, problem inline keyboard
I have this problem, I would like to create a keyboard for my telegram bot, here is my code, where I created the keys with online keyboard. It gives me this error and I can't connect it to my posts, where the word was posted to / news

```<code>const util = require('util');
const express = require('express');
const app = express();
// includiamo la libreria "axios"
const axios = require('axios');

// Includiamo la libreria "body-parser" per gestire le richieste in JSON.
const bodyparser = require('body-parser');
app.use(bodyparser.json());

app.get ('/', function (req, res) {
   res.status (200) .json ({status: 'ok'});
});

// Includiamo il modulo "request" per effettuare richieste HTTP
const https = require('https');

// Webhook per Telegram
 app.post('/', function (req, res)  {
  console.log("Richiesta: " + JSON.stringify(req.body));
  const chatid = req.body.message.chat.id;
  const text = req.body.message.text;
  const username = req.body.message.from.username

  console.log("Utente in chat " + chatid + " ha scritto '" + text + "'");

 const clientreq = https.request({
   method: 'POST',
   host: 'api.telegram.org',
   url: 'https://api.telegram.org/bot'+process.env.BOTTOKEN+'/setWebhook?
   url=https://viktecnews.glitch.me/',
   path: '/bot' + process.env.BOTTOKEN + '/getMe'
    },function(resp) {
   // Questa funzione viene richiamata a richiesta eseguita
   if(resp.statusCode != 200) {
   console.log("Richiesta HTTP fallita");
    return;
  }
 console.log("Richiesta HTTP riuscita");

   var body = '';
  resp.on('data', function(d) {
      body += d;
   });
    resp.on('end', function() {
  // Ora body contiene il contenuto (corpo) della risposta
  console.log("Risposta da API Telegram: " + body);

  const j = JSON.parse(body);
  // j è un oggetto JavaScript che contiene i dati della risposta
  // ...
    });
 });

  if (text.match(/start/))

  { axios.post ('https://api.telegram.org/bot'+
             process.env.BOTTOKEN+'/sendMessage'
,
               {
               chat_id: chatid,
               text: 'Benvenuto'+'\t'+ username +'\t' + 'in ViktecNews,
  scopri le ultime news sul mondo della tecnologia, guide e recensioni.
   Per qualsiasi cosa vai su info',
               reply_markup: JSON.stringify ({
                 inline_keyboard:[[
                   {
      text: 'news',
      callback_data: '/news'
    },{
      text: 'recensioni',
      callback_data: '/recensioni'
    },{
      text: 'guide',
      callback_data: '/guide'
    },{
      text: 'info',
      callback_data: '/info'
    }
                 ]]
               })
    }).then(response => {
    // Messaggio postato
     console.log('Message posted')
       console.log()
  res.end('ok')
})
.catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
    })
}
 else if (text.match(/info/)) {
     axios.post('https://api.telegram.org/bot'+
    process.env.BOTTOKEN+'/sendMessage'
  ,
                 {
               chat_id: chatid,
               text: 'ViktecNews è un bot programmato per riportarti le
   ultime dieci news, guide e recensioni. Per qualsiasi problema contatta
 @viktec'
               })
        .then(response => {
      // Messaggio postato
      console.log('Message posted')
     res.end('ok')
   })
   .catch(err => {
       // ...Messaggio non postato
      console.log('Error :', err)
       res.end('Error :' + err)
     })

     }

  else if (text.match (/news/)) {
       axios.get( URL ,{
        params: {
       categories: '8240'
        }
      })
  .then(response => {
        for(var i = 0; i < response.data.length; i++)
   axios.post('https://api.telegram.org/bot'+
   process.env.BOTTOKEN+'/sendMessage'
   ,
               {
                  chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
  response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
               })
      .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
   })
     .catch(err => {
    // ...Messaggio non postato
    console.log('Error :', err)
     res.end('Error :' + err)
  })
  console.log(response.data[0]);
  })
  .catch(error => {
   console.log(error);
  });

 }else if (text.match (/recensioni/)) {
    axios.get( URL ,{
     params: {
       categories: '8241'
     }
     })
  .then(response => {
       for(var i = 0; i < response.data.length; i++)
    axios.post('https://api.telegram.org/bot'+
    process.env.BOTTOKEN+'/sendMessage',
               {
               chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
  response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
               })
      .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
   })
  .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
   })
  console.log(response.data[0]);
  })
  .catch(error => {
  console.log(error);
  });

 } else if (text.match (/guide/)) {
   axios.get( URL ,{
     params: {
       categories: '8250'
     }
     })
 .then(response => {
     for(var i = 0; i < response.data.length; i++)

  axios.post('https://api.telegram.org/bot'+
  process.env.BOTTOKEN+'/sendMessage' ,
               {
               chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
 response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
                })
      .then(response => {
   // Messaggio postato
   console.log('Message posted')
   res.end('ok')
   })
   .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
   res.end('Error :' + err)
  })
  console.log(response.data[0]);
  })
 .catch(error => {
   console.log(error);
 });

   } else if (text.match (/games/)) {
      axios.get( URL ,{
     params: {
       categories: '8245'
     }
     })
   .then(response => {
      for(var i = 0; i < response.data.length; i++)

      axios.post('https://api.telegram.org/bot'+
    process.env.BOTTOKEN+'/sendMessage',
               {
               chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
     response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
               })
      .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
  })
   .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
   })
   console.log(response.data[0]);
 })
 .catch(error => {
  console.log(error);
 });

  }else

      {axios.post('https://api.telegram.org/bot'+
      process.env.BOTTOKEN+'/sendMessage
,
               {
                chat_id: chatid,
               text: "Carattere errato, utilizza i comandi!"
  })
 .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
    })
   .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
    })};
  clientreq.end(); // questa chiamata esegue la richiesta
 });

 const listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' +
listener.address().port);
 });`
</code>```

TypeError: Cannot read property 'chat' of undefined

at /app/server.js:22:35

```<code>at Layer.handle [as handle_request] (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/layer.js:95:5)

at next (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/route.js:137:13)

at Route.dispatch (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/route.js:112:3)

at Layer.handle [as handle_request] (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/layer.js:95:5)

at /rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/index.js:281:22

at Function.process_params (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/index.js:335:12)

at next (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/index.js:275:10)

at /rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/body-parser/1.19.0/node_modules/body-parser/lib/read.js:130:5

at invokeCallback (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/raw-body/2.4.0/node_modules/raw-body/index.js:224:16)
</code>```

答: This error is telling you that message is undefined.  Please make sure the client is providing message as part of the POST body.

Body:
I have this problem, I would like to create a keyboard for my telegram bot, here is my code, where I created the keys with online keyboard. It gives me this error and I can't connect it to my posts, where the word was posted to / news

const util = require('util');
const express = require('express');
const app = express();
// includiamo la libreria "axios"
const axios = require('axios');

// Includiamo la libreria "body-parser" per gestire le richieste in JSON.
const bodyparser = require('body-parser');
app.use(bodyparser.json());

app.get ('/', function (req, res) {
   res.status (200) .json ({status: 'ok'});
});

// Includiamo il modulo "request" per effettuare richieste HTTP
const https = require('https');

// Webhook per Telegram
 app.post('/', function (req, res)  {
  console.log("Richiesta: " + JSON.stringify(req.body));
  const chatid = req.body.message.chat.id;
  const text = req.body.message.text;
  const username = req.body.message.from.username

  console.log("Utente in chat " + chatid + " ha scritto '" + text + "'");

 const clientreq = https.request({
   method: 'POST',
   host: 'api.telegram.org',
   url: 'https://api.telegram.org/bot'+process.env.BOTTOKEN+'/setWebhook?
   url=https://viktecnews.glitch.me/',
   path: '/bot' + process.env.BOTTOKEN + '/getMe'
    },function(resp) {
   // Questa funzione viene richiamata a richiesta eseguita
   if(resp.statusCode != 200) {
   console.log("Richiesta HTTP fallita");
    return;
  }
 console.log("Richiesta HTTP riuscita");

   var body = '';
  resp.on('data', function(d) {
      body += d;
   });
    resp.on('end', function() {
  // Ora body contiene il contenuto (corpo) della risposta
  console.log("Risposta da API Telegram: " + body);

  const j = JSON.parse(body);
  // j è un oggetto JavaScript che contiene i dati della risposta
  // ...
    });
 });

  if (text.match(/start/))

  { axios.post ('https://api.telegram.org/bot'+
             process.env.BOTTOKEN+'/sendMessage'
,
               {
               chat_id: chatid,
               text: 'Benvenuto'+'\t'+ username +'\t' + 'in ViktecNews,
  scopri le ultime news sul mondo della tecnologia, guide e recensioni.
   Per qualsiasi cosa vai su info',
               reply_markup: JSON.stringify ({
                 inline_keyboard:[[
                   {
      text: 'news',
      callback_data: '/news'
    },{
      text: 'recensioni',
      callback_data: '/recensioni'
    },{
      text: 'guide',
      callback_data: '/guide'
    },{
      text: 'info',
      callback_data: '/info'
    }
                 ]]
               })
    }).then(response => {
    // Messaggio postato
     console.log('Message posted')
       console.log()
  res.end('ok')
})
.catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
    })
}
 else if (text.match(/info/)) {
     axios.post('https://api.telegram.org/bot'+
    process.env.BOTTOKEN+'/sendMessage'
  ,
                 {
               chat_id: chatid,
               text: 'ViktecNews è un bot programmato per riportarti le
   ultime dieci news, guide e recensioni. Per qualsiasi problema contatta
 @viktec'
               })
        .then(response => {
      // Messaggio postato
      console.log('Message posted')
     res.end('ok')
   })
   .catch(err => {
       // ...Messaggio non postato
      console.log('Error :', err)
       res.end('Error :' + err)
     })

     }

  else if (text.match (/news/)) {
       axios.get( URL ,{
        params: {
       categories: '8240'
        }
      })
  .then(response => {
        for(var i = 0; i < response.data.length; i++)
   axios.post('https://api.telegram.org/bot'+
   process.env.BOTTOKEN+'/sendMessage'
   ,
               {
                  chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
  response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
               })
      .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
   })
     .catch(err => {
    // ...Messaggio non postato
    console.log('Error :', err)
     res.end('Error :' + err)
  })
  console.log(response.data[0]);
  })
  .catch(error => {
   console.log(error);
  });

 }else if (text.match (/recensioni/)) {
    axios.get( URL ,{
     params: {
       categories: '8241'
     }
     })
  .then(response => {
       for(var i = 0; i < response.data.length; i++)
    axios.post('https://api.telegram.org/bot'+
    process.env.BOTTOKEN+'/sendMessage',
               {
               chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
  response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
               })
      .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
   })
  .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
   })
  console.log(response.data[0]);
  })
  .catch(error => {
  console.log(error);
  });

 } else if (text.match (/guide/)) {
   axios.get( URL ,{
     params: {
       categories: '8250'
     }
     })
 .then(response => {
     for(var i = 0; i < response.data.length; i++)

  axios.post('https://api.telegram.org/bot'+
  process.env.BOTTOKEN+'/sendMessage' ,
               {
               chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
 response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
                })
      .then(response => {
   // Messaggio postato
   console.log('Message posted')
   res.end('ok')
   })
   .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
   res.end('Error :' + err)
  })
  console.log(response.data[0]);
  })
 .catch(error => {
   console.log(error);
 });

   } else if (text.match (/games/)) {
      axios.get( URL ,{
     params: {
       categories: '8245'
     }
     })
   .then(response => {
      for(var i = 0; i < response.data.length; i++)

      axios.post('https://api.telegram.org/bot'+
    process.env.BOTTOKEN+'/sendMessage',
               {
               chat_id: chatid,
               text: response.data[i].title.rendered +" \n\t"+
     response.data[i].link + " \n\t"+"Autore : "+response.data[i].author
               })
      .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
  })
   .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
   })
   console.log(response.data[0]);
 })
 .catch(error => {
  console.log(error);
 });

  }else

      {axios.post('https://api.telegram.org/bot'+
      process.env.BOTTOKEN+'/sendMessage
,
               {
                chat_id: chatid,
               text: "Carattere errato, utilizza i comandi!"
  })
 .then(response => {
  // Messaggio postato
  console.log('Message posted')
  res.end('ok')
    })
   .catch(err => {
  // ...Messaggio non postato
  console.log('Error :', err)
  res.end('Error :' + err)
    })};
  clientreq.end(); // questa chiamata esegue la richiesta
 });

 const listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' +
listener.address().port);
 });`

TypeError: Cannot read property 'chat' of undefined

at /app/server.js:22:35

at Layer.handle [as handle_request] (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/layer.js:95:5)

at next (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/route.js:137:13)

at Route.dispatch (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/route.js:112:3)

at Layer.handle [as handle_request] (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/layer.js:95:5)

at /rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/index.js:281:22

at Function.process_params (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/index.js:335:12)

at next (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/express/4.16.4/node_modules/express/lib/router/index.js:275:10)

at /rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/body-parser/1.19.0/node_modules/body-parser/lib/read.js:130:5

at invokeCallback (/rbd/pnpm-volume/f9d011c8-bafe-411e-a616-958a5a1a748d/node_modules/.registry.npmjs.org/raw-body/2.4.0/node_modules/raw-body/index.js:224:16)


问:
Can I run a VBA macro to run SQL queries I have saved in a MS Access database?
I spent alot of time to create 24 different separate MS Access queries that I have saved in the MS Access database.  They have to be run in a specific order.

I want to run a macro that will just execute them one after another.

I know I can do this using VBA but I have copy all the SQL into VBA one at a time.

is there a way I can just have VBA run the saved queries in the MS Access database without copying them into VBA?

I am very good with SQL. 15+ years doing Oracle work,  Code writing, DB Tuning, Data DBA work.

I am new to using SQL and VBA to run against MS Access DB.

答:
To clear a few terminologies:

MS Access GUI comprises of five main object types: tables, queries, forms, macros, and modules. Technically, there is no such thing as VBA macros in MS Access. This is a terminology from MS Excel where each subroutine is defined as a macro.

In MS Access there is a physical object known as a macro which is divorced from VBA (though can call VBA code). Coded routines which includes all functions and subroutines in MS Access are encapsulated in the module (object) usually behind forms, reports, or standalone modules.

Do remember each Microsoft Office application maintains its own object library and should not be conflated with one another. VBA itself is a separate component installed by default (see Tools \ References in IDE). Any language (Java, PHP, Python, etc.) that can run COM-interfacing can connect and run each Office app's object library. VBA is simply one type that does this.

MS Access maintains stored queries (as another object) which can be actions queries (UPDATE, INSERT even CREATE TABLE or ALTER TABLE) or recordset queries (SELECT). You do not have to copy all of SQL code inside VBA to run these saved query objects. In fact, stored queries run more efficiently than string queries called in code since the MS Access engine compiles the best execution plan with stored queries.

Having said that, consider a macro calling multiple OpenQuery actions or coded subroutine inside a module calling multiple DoCmd.OpenQuery commands

Macro

OpenQuery
   QueryName: myfirstActionQuery
        View: Datasheet
   Data Mode: Edit

OpenQuery
   QueryName: mySecondActionQuery
        View: Datasheet
   Data Mode: Edit

OpenQuery
   QueryName: myThirdActionQuery
        View: Datasheet
   Data Mode: Edit

...
```

<p>For action queries you do not have to close the query as <code>OpenQuery</code> runs process without physically opening anything to screen. You may want to incorporate the <code>SetWarnings</code> to <code>False</code> action in order to avoid the message prompt of how much records will be updated or inserted which is a default setting in Access. Because this is a potentially hazardous action, click <code>Show All Actions</code> to see this specific action.</p>

<p><strong>Module</strong></p>

<pre class="lang-vb prettyprint-override"><code>Public Sub RunQueries()
     DoCmd.SetWarnings False

     DoCmd.OpenQuery "myfirstSavedQuery"
     DoCmd.OpenQuery "mySecondSavedQuery"
     DoCmd.OpenQuery "myThirdSavedQuery"
     ...

     DoCmd.SetWarnings True
End Sub
</code>```

Similar to macros, you do not have to close action queries and can call the DoCmd.SetWarnings to suppress the message prompts with each update, insert, or make-table action.

The alternative to turning SetWarnings off and on is @LeeMac's solution which runs queries using the DAO's Database.Execute() command. In fact, because DAO is part of the MS Access object library, the above method can be run outside VBA as mentioned above.

Python

import os
import win32com.client

access_file = r'C:\Path\To\MyDatabase.accdb'

try:
    oApp = win32com.client.Dispatch("Access.Application")
    oApp.OpenCurrentDatabase(access_file)

    db = oApp.Currentdb()
    db.Execute("myFirstSavedQuery")
    db.Execute("mySecondSavedQuery")
    db.Execute("myThirdSavedQuery")
    ...

except Exception as e:
    print(e)

finally:
    oApp.Quit()
    db = None; oApp = None
    del db; del oApp
```

Body:
To clear a few terminologies:

MS Access GUI comprises of five main object types: tables, queries, forms, macros, and modules. Technically, there is no such thing as VBA macros in MS Access. This is a terminology from MS Excel where each subroutine is defined as a macro.

In MS Access there is a physical object known as a macro which is divorced from VBA (though can call VBA code). Coded routines which includes all functions and subroutines in MS Access are encapsulated in the module (object) usually behind forms, reports, or standalone modules.

Do remember each Microsoft Office application maintains its own object library and should not be conflated with one another. VBA itself is a separate component installed by default (see Tools \ References in IDE). Any language (Java, PHP, Python, etc.) that can run COM-interfacing can connect and run each Office app's object library. VBA is simply one type that does this.

MS Access maintains stored queries (as another object) which can be actions queries (UPDATE, INSERT even CREATE TABLE or ALTER TABLE) or recordset queries (SELECT). You do not have to copy all of SQL code inside VBA to run these saved query objects. In fact, stored queries run more efficiently than string queries called in code since the MS Access engine compiles the best execution plan with stored queries.

Having said that, consider a macro calling multiple OpenQuery actions or coded subroutine inside a module calling multiple DoCmd.OpenQuery commands

Macro

OpenQuery
   QueryName: myfirstActionQuery
        View: Datasheet
   Data Mode: Edit

OpenQuery
   QueryName: mySecondActionQuery
        View: Datasheet
   Data Mode: Edit

OpenQuery
   QueryName: myThirdActionQuery
        View: Datasheet
   Data Mode: Edit

...

For action queries you do not have to close the query as OpenQuery runs process without physically opening anything to screen. You may want to incorporate the SetWarnings to False action in order to avoid the message prompt of how much records will be updated or inserted which is a default setting in Access. Because this is a potentially hazardous action, click Show All Actions to see this specific action.

Module

Public Sub RunQueries()
     DoCmd.SetWarnings False

     DoCmd.OpenQuery "myfirstSavedQuery"
     DoCmd.OpenQuery "mySecondSavedQuery"
     DoCmd.OpenQuery "myThirdSavedQuery"
     ...

     DoCmd.SetWarnings True
End Sub

Similar to macros, you do not have to close action queries and can call the DoCmd.SetWarnings to suppress the message prompts with each update, insert, or make-table action.

The alternative to turning SetWarnings off and on is @LeeMac's solution which runs queries using the DAO's Database.Execute() command. In fact, because DAO is part of the MS Access object library, the above method can be run outside VBA as mentioned above.

Python

import os
import win32com.client

access_file = r'C:\Path\To\MyDatabase.accdb'

try:
    oApp = win32com.client.Dispatch("Access.Application")
    oApp.OpenCurrentDatabase(access_file)

    db = oApp.Currentdb()
    db.Execute("myFirstSavedQuery")
    db.Execute("mySecondSavedQuery")
    db.Execute("myThirdSavedQuery")
    ...

except Exception as e:
    print(e)

finally:
    oApp.Quit()
    db = None; oApp = None
    del db; del oApp


问:
could not find implicit value for parameter encoder: io.circe.Encoder[com.sweetsoft.SapHealth]
I have the following code, that does not compile:

```<code>import java.time.Instant

import io.circe.{Decoder, Encoder}
import io.circe.generic.auto._
import io.circe.syntax._

trait SapHealth {}

case class SapHealthRejected(reason: String) extends SapHealth

case class SapHealthAccepted(sapId: String, requestedAt: Long) extends SapHealth

object SapHealth {

  private val build: SapHealth = SapHealthAccepted(SapmockActor.system.name, Instant.now().getEpochSecond)

  val create: String = build.asJson.noSpaces

  implicit val encodeFieldType: Encoder[SapHealthAccepted] =
    Encoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.unapply(_).get)

  implicit val decodeFieldType: Decoder[SapHealthAccepted] =
    Decoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.apply)

}
</code>```

The compiler complains:

```<code>could not find implicit value for parameter encoder: io.circe.Encoder[com.sweetsoft.SapHealth]
[error]   val create: String = build.asJson.noSpaces
</code>```

What am I missing?

答:
You've specifically up-cast build to SapHealth, but you don't provide an Encoder instance for SapHealth (only SapHealthAccepted), and circe-generic can't derive one because you haven't sealed the trait hierarchy.

The most straightforward solution would be to add sealed:

```<code>import io.circe.{Decoder, Encoder}
import io.circe.generic.auto._
import io.circe.syntax._

sealed trait SapHealth {}
case class SapHealthRejected(reason: String) extends SapHealth
case class SapHealthAccepted(sapId: String, requestedAt: Long) extends SapHealth

object SapHealth {
  implicit val encodeFieldType: Encoder[SapHealthAccepted] =
    Encoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.unapply(_).get)

  implicit val decodeFieldType: Decoder[SapHealthAccepted] =
    Decoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.apply)

  private val build: SapHealth = SapHealthAccepted("foo", 123L)

  val create: String = build.asJson.noSpaces
}
</code>```

Note that you also need to rearrange the definitions to avoid running into null-pointer exceptions because of initialization order (if you put create before encodeFieldType, the derived SapHealth encoder will try to use encodeFieldType before it's initialized). With the rearrangement above, this works just fine:

```<code>scala> SapHealth.create
res2: String = {"SapHealthAccepted":{"sap-id":"foo","requested_at":123}}
</code>```

Note that the derived SapHealth encoder is using your custom SapHealthAccepted encoder, which I assume is what you want.

Body:
I have the following code, that does not compile:

import java.time.Instant

import io.circe.{Decoder, Encoder}
import io.circe.generic.auto._
import io.circe.syntax._

trait SapHealth {}

case class SapHealthRejected(reason: String) extends SapHealth

case class SapHealthAccepted(sapId: String, requestedAt: Long) extends SapHealth

object SapHealth {

  private val build: SapHealth = SapHealthAccepted(SapmockActor.system.name, Instant.now().getEpochSecond)

  val create: String = build.asJson.noSpaces

  implicit val encodeFieldType: Encoder[SapHealthAccepted] =
    Encoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.unapply(_).get)

  implicit val decodeFieldType: Decoder[SapHealthAccepted] =
    Decoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.apply)

}

The compiler complains:

could not find implicit value for parameter encoder: io.circe.Encoder[com.sweetsoft.SapHealth]
[error]   val create: String = build.asJson.noSpaces

What am I missing?

Body:
You've specifically up-cast build to SapHealth, but you don't provide an Encoder instance for SapHealth (only SapHealthAccepted), and circe-generic can't derive one because you haven't sealed the trait hierarchy.

The most straightforward solution would be to add sealed:

import io.circe.{Decoder, Encoder}
import io.circe.generic.auto._
import io.circe.syntax._

sealed trait SapHealth {}
case class SapHealthRejected(reason: String) extends SapHealth
case class SapHealthAccepted(sapId: String, requestedAt: Long) extends SapHealth

object SapHealth {
  implicit val encodeFieldType: Encoder[SapHealthAccepted] =
    Encoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.unapply(_).get)

  implicit val decodeFieldType: Decoder[SapHealthAccepted] =
    Decoder.forProduct2("sap-id", "requested_at")(SapHealthAccepted.apply)

  private val build: SapHealth = SapHealthAccepted("foo", 123L)

  val create: String = build.asJson.noSpaces
}

Note that you also need to rearrange the definitions to avoid running into null-pointer exceptions because of initialization order (if you put create before encodeFieldType, the derived SapHealth encoder will try to use encodeFieldType before it's initialized). With the rearrangement above, this works just fine:

scala> SapHealth.create
res2: String = {"SapHealthAccepted":{"sap-id":"foo","requested_at":123}}

Note that the derived SapHealth encoder is using your custom SapHealthAccepted encoder, which I assume is what you want.


问:
Need help changing Text of label in TS Code
On my html I have a label that shows a number of amount of images I have submitted to the server for the specific instance. My problem now is that when I upload images it does not refresh the image count, I have to close the Mobile application and open in up again to see image counter going up/.

I have tried to change the variable in the Typescript code after the images are uploaded successfully but the String does not change

```<code><StackLayout class="m-10">
   <Label [text]="imagesCount + ' Photos Uploaded'" verticalAlignment="center" class="lbl-info" horizontalAlignment="center" textWrap="true"></Label>
</StackLayout>
</code>```

```<code>get imagesCount() {
    this._imagesCount = workAttachments.length;

    return this._imagesCount;
}
</code>```

I expect the Image Label to go from 0 Photos Uploaded to 1 Photos Uploaded

-- Edit --

This is how I upload my images

```<code>doFileUpload(file: any) {
        let actualFile = fs.File.fromPath(file);
        let base64 = android.util.Base64.encodeToString(actualFile.readSync(), android.util.Base64.NO_WRAP);
        let workOrderAttachment = new WorkOrderAttachment(new Attachment(base64, file.replace(/^.*[\/]/, ''), 0), WorkOrderAttachmentType.PHOTO, '');

        this._service.workOrderAttachment(this.job.id, workOrderAttachment, ['id']).subscribe(result => {
            if (result == null) {
                UserInterfaceUtil.showError("Error Uploading images.", "");
            } else {
                UserInterfaceUtil.showInfo("Photos uploaded successfully.", "");
                this._imagesCount += 1;
            }
        }, error => {
            UserInterfaceUtil.handleError(error);
            console.log(error);
        });
    }
</code>```

答: The only way I could get this done correctly was adding a button on the Form to refresh the Label. It is not the best way of doing what I need, but it is done.</p>

Body:
On my html I have a label that shows a number of amount of images I have submitted to the server for the specific instance. My problem now is that when I upload images it does not refresh the image count, I have to close the Mobile application and open in up again to see image counter going up/.

I have tried to change the variable in the Typescript code after the images are uploaded successfully but the String does not change

<StackLayout class="m-10">

</StackLayout>

get imagesCount() {
    this._imagesCount = workAttachments.length;

    return this._imagesCount;
}

I expect the Image Label to go from 0 Photos Uploaded to 1 Photos Uploaded

-- Edit --

This is how I upload my images

doFileUpload(file: any) {
        let actualFile = fs.File.fromPath(file);
        let base64 = android.util.Base64.encodeToString(actualFile.readSync(), android.util.Base64.NO_WRAP);
        let workOrderAttachment = new WorkOrderAttachment(new Attachment(base64, file.replace(/^.*[\/]/, ''), 0), WorkOrderAttachmentType.PHOTO, '');

        this._service.workOrderAttachment(this.job.id, workOrderAttachment, ['id']).subscribe(result => {
            if (result == null) {
                UserInterfaceUtil.showError("Error Uploading images.", "");
            } else {
                UserInterfaceUtil.showInfo("Photos uploaded successfully.", "");
                this._imagesCount += 1;
            }
        }, error => {
            UserInterfaceUtil.handleError(error);
            console.log(error);
        });
    }


问:
problem with 512x512 app icon in iTunes Connect
I'm uploading my app to App Store and I created it in iTunes Connect.

I just uploaded my 512x512px icon and then I opened Version Summary page to verify my information...

I've got a set of icon that just have gloss effect. In Version Summary page I see my 512x512px icon with automatic gloss added.

Is there a way to prevent this? My large app icon mustn't have gloss...

In my info.plist I added the line "Icon already includes gloss effects" and I checked the box near it...

Can anyone help me?

答: According to 512x512 image for AppStore (iTunes Connect), will Apple do corner rounding like they do on the phone?, Apple does in fact check the app for the UIPrerenderedIcon flag.  Once the app is uploaded, the 512x512 large icon will pick up the correct setting.</p>

ContentLicense: CC BY-SA 3.0


问:
restdocs SnippetException due to HAL "_links" elements from spring-data-rest
My app is using spring-data-rest and spring-restdocs.
My setup is really standard; copied from the docs almost entirely, but I've included the samples below in case I'm missing something.
When my mvc test runs, it fails with:

```<code>org.springframework.restdocs.snippet.SnippetException: The following parts of the payload were not documented:
{
  "_links" : {
    "self" : {
      "href" : "https://my-api/item/10"
    },
    "item" : {
      "href" : "https://my-api/item/10"
    }
  }
}
</code>```

This is my test code:

```<code>@Rule
public JUnitRestDocumentation restDocs = new JUnitRestDocumentation("target/generated-snippets");
// ...
mockMvc = webAppContextSetup(wac) //WebApplicationContext
        .apply(documentationConfiguration(restDocs)
                       .uris()
                       .withHost("my-api")
                       .withPort(443)
                       .withScheme("https"))
        .build();
// ....
mockMvc.perform(get("/items/{id}", "10"))
               .andDo(documentation)
</code>```

Here's the stack:

```<code>at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:176)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:100)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:196)
at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:55)
at org.springframework.test.web.servlet.MockMvc$1.andDo(MockMvc.java:177)
at com.example.my.api.domain.MyRepositoryRestTest.findOne(MyRepositoryRestTest.java:36)
</code>```

How do I get spring-restdocs and spring-data-rest to play nice?

EDIT(S):

My documentation instance is defined as follows:

```<code>ResultHandler documentation = document("items/findOne",
                                       preprocessRequest(prettyPrint(), maskLinks()),
                                       preprocessResponse(prettyPrint()),
                                       responseFields(
                                            fieldWithPath("name").description("Item name.")
                                            // Bunch more
                                       ));
</code>```

As @meistermeier indicated, (and following the restdocs docs for ignoring links, I can add

```<code>links(linkWithRel("self").ignored(),
      linkWithRel("_self").ignored().optional()) // docs suggest this. /shrug
</code>```

But that still leaves me with:

```SnippetException: Links with the following relations were not documented: [item]```

Seems like the _links are always going to have that self-reference back to the same entity, right?
How do I cleanly handle this without ignoring an entity-specific link for every test, like:

```<code>links(linkWithRel("item").ignored())
</code>```

Even if I do add the above line (so that all fields self _self curies and item are all ignored() and/or optional()), the result of the test returns to the original error at the top of this question.

答:
canonical way seems to be using things from restdocs documentation. Approach is in line with approach from https://stackoverflow.com/users/2650436/meistermeier solution.

Documentation can be found on https://docs.spring.io/spring-restdocs/docs/current/reference/html5/#documenting-your-api-hypermedia-link-formats

Sample code:

```<code>.consumeWith(document("items",
       links(
               halLinks(), // <- this shorten things a bit
               linkWithRel("self").ignored(),
               linkWithRel("profile").ignored()
       ),
</code>```

Body:
My app is using spring-data-rest and spring-restdocs.
My setup is really standard; copied from the docs almost entirely, but I've included the samples below in case I'm missing something.
When my mvc test runs, it fails with:

org.springframework.restdocs.snippet.SnippetException: The following parts of the payload were not documented:
{
  "_links" : {
    "self" : {
      "href" : "https://my-api/item/10"
    },
    "item" : {
      "href" : "https://my-api/item/10"
    }
  }
}

This is my test code:

@Rule
public JUnitRestDocumentation restDocs = new JUnitRestDocumentation("target/generated-snippets");
// ...
mockMvc = webAppContextSetup(wac) //WebApplicationContext
        .apply(documentationConfiguration(restDocs)
                       .uris()
                       .withHost("my-api")
                       .withPort(443)
                       .withScheme("https"))
        .build();
// ....
mockMvc.perform(get("/items/{id}", "10"))
               .andDo(documentation)

Here's the stack:

at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:176)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:100)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:196)
at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:55)
at org.springframework.test.web.servlet.MockMvc$1.andDo(MockMvc.java:177)
at com.example.my.api.domain.MyRepositoryRestTest.findOne(MyRepositoryRestTest.java:36)

How do I get spring-restdocs and spring-data-rest to play nice?

EDIT(S):

My documentation instance is defined as follows:

ResultHandler documentation = document("items/findOne",
                                       preprocessRequest(prettyPrint(), maskLinks()),
                                       preprocessResponse(prettyPrint()),
                                       responseFields(
                                            fieldWithPath("name").description("Item name.")
                                            // Bunch more
                                       ));

As @meistermeier indicated, (and following the restdocs docs for ignoring links, I can add

links(linkWithRel("self").ignored(),
      linkWithRel("_self").ignored().optional()) // docs suggest this. /shrug

But that still leaves me with:

SnippetException: Links with the following relations were not documented: [item]

Seems like the _links are always going to have that self-reference back to the same entity, right?
How do I cleanly handle this without ignoring an entity-specific link for every test, like:

links(linkWithRel("item").ignored())

Even if I do add the above line (so that all fields self _self curies and item are all ignored() and/or optional()), the result of the test returns to the original error at the top of this question.

Body:
canonical way seems to be using things from restdocs documentation. Approach is in line with approach from https://stackoverflow.com/users/2650436/meistermeier solution.

Documentation can be found on https://docs.spring.io/spring-restdocs/docs/current/reference/html5/#documenting-your-api-hypermedia-link-formats

Sample code:

.consumeWith(document("items",
       links(
               halLinks(), // <- this shorten things a bit
               linkWithRel("self").ignored(),
               linkWithRel("profile").ignored()
       ),


问:
Expand Variadic Template Pack by Pairs
I'm creating a generic collection of Nodes. Each Node has a Start and End type. And the End type of one must match the Start type of the next.

If I were to list each of the types in the collection the constructor would look like this (for four types):

```<code>template <typename Start, typename End>
class Node {
};

template <typename A, typename B, typename C, typename D>
class Collection
{
public:
    Collection(Node<A, B> n1, Node<B, C> n2, Node<C, D> n3) { }
};
</code>```

But when I try to write constuctor as a variadic template to support any number of types, I am stumped.

答:
Based on max66's answer:

This cleans up the unnecessary tag structure and simplifies the index_sequence to direct recursion (similar to the definition of tuple).

```<code>template <typename Owner, typename Value>
class Node {
};

struct A {};
struct B {};
struct C {};
struct D {};

template <typename First, typename...Rest>
std::tuple<First, Rest...> tuple_push_front(std::tuple<Rest...>);

template <typename T1, typename T2, typename...T>
struct NodeCollector {
private:
    using nodeRest = NodeCollector<T2, T...>;
public:
    using tplOwners = decltype(tuple_push_front<T1>(std::declval<typename nodeRest::tplOwners>()));
    using tplValues = decltype(tuple_push_front<T2>(std::declval<typename nodeRest::tplValues>()));
};
template <typename T1, typename T2>
struct NodeCollector<T1, T2> {
public:
    using tplOwners = std::tuple<T1>;
    using tplValues = std::tuple<T2>;
};

template <typename...Ts>
class Collection
{
    static_assert( sizeof...(Ts) > 1u, "Collection requires at least two types.");
private:
    using nodeCollector = NodeCollector<Ts...>;
public:
    template <typename...OTs, typename...VTs, typename=std::enable_if_t<
        (std::is_same_v<typename nodeCollector::tplOwners, std::tuple<OTs...>> &&
         std::is_same_v<typename nodeCollector::tplValues, std::tuple<VTs...>>)> >
    Collection(Node<OTs, VTs>...) { }
};

int main()
{
    Collection<A, B, C, D> c{Node<A, B>{}, Node<B, C>{}, Node<C, D>{}};
    std::cout << demangle(typeid(c).name()) << std::endl;
}
</code>```

Title: Expand Variadic Template Pack by Pairs

Body:
I'm creating a generic collection of Nodes. Each Node has a Start and End type. And the End type of one must match the Start type of the next.

If I were to list each of the types in the collection the constructor would look like this (for four types):

template <typename Start, typename End>
class Node {
};

template <typename A, typename B, typename C, typename D>
class Collection
{
public:
    Collection(Node n1, Node n2, Node<C, D> n3) { }
};

But when I try to write constuctor as a variadic template to support any number of types, I am stumped.

Body:
Based on max66's answer:

This cleans up the unnecessary tag structure and simplifies the index_sequence to direct recursion (similar to the definition of tuple).

template <typename Owner, typename Value>
class Node {
};

struct A {};
struct B {};
struct C {};
struct D {};

template <typename First, typename...Rest>
std::tuple<First, Rest...> tuple_push_front(std::tuple<Rest...>);

template <typename T1, typename T2, typename...T>
struct NodeCollector {
private:
    using nodeRest = NodeCollector<T2, T...>;
public:
    using tplOwners = decltype(tuple_push_front<T1>(std::declval<typename nodeRest::tplOwners>()));
    using tplValues = decltype(tuple_push_front<T2>(std::declval<typename nodeRest::tplValues>()));
};
template <typename T1, typename T2>
struct NodeCollector<T1, T2> {
public:
    using tplOwners = std::tuple<T1>;
    using tplValues = std::tuple<T2>;
};

template <typename...Ts>
class Collection
{
    static_assert( sizeof...(Ts) > 1u, "Collection requires at least two types.");
private:
    using nodeCollector = NodeCollector<Ts...>;
public:
    template <typename...OTs, typename...VTs, typename=std::enable_if_t<
        (std::is_same_v<typename nodeCollector::tplOwners, std::tuple<OTs...>> &&
         std::is_same_v<typename nodeCollector::tplValues, std::tuple<VTs...>>)> >
    Collection(Node<OTs, VTs>...) { }
};

int main()
{
    Collection<A, B, C, D> c{Node<A, B>{}, Node<B, C>{}, Node<C, D>{}};
    std::cout << demangle(typeid(c).name()) << std::endl;
}


问:
x64 build: error MSB8013: This project doesn't contain the Configuration and Platform combination of Debug|Win32
I'm trying to get a pure x64 build running for a complex build with many solutions (some for CI, some for devs) and hundreds of project and have run into "error MSB8013: This project doesn't contain the Configuration and Platform combination of Debug|Win32"

I've reduced it to a simple configuration:

Solution A contains Project X & Project Y. Project X has a project
reference to Project Y.

Solution B contains also contains Project X.

None of the projects or solutions contain a Win32 platform - it's been deleted.

When I build solution B (as x64), I receive

error MSB8013: This project doesn't contain the Configuration and
  Platform combination of Debug|Win32

The error message sometimes contains additional information:

This error may also appear if some other project is trying to follow a
  project-to-project reference to this project, this project has been
  unloaded or is not included in the solution, and the referencing
  project does not build using the same or an equivalent Configuration
  or Platform.

The problem is the referencing project does "build using the same or an equivalent Configuration or Platform."

Looking at the msbuild diagnostic, project Y is being built because project X contains a project reference to it. But the configuration and platform properties are being deleted just before project Y is built:

```<code>1>Task "MSBuild" (TaskId:28)
1>  Removing Properties: (TaskId:28)
1>    Configuration (TaskId:28)
1>    Platform (TaskId:28)
</code>```

As a result Microsoft.Cpp.Default.props kicks in and sets these to Debug|Win32:

```<code>1>Task "Message" (TaskId:11)
1>  Configuration=Debug (TaskId:11)
1>Done executing task "Message". (TaskId:11)
1>Task "Message" (TaskId:12)
1>  Platform=Win32 (TaskId:12)
1>Done executing task "Message". (TaskId:12)
</code>```

How can I prevent this and make msbuild pass the chosen configuration & platform?

(I understand the ultimate solution to use NuGet to manage package dependencies, but that isn't feasible in the short term)

答: I couldn't add a comment because of lack of rep, but in the same vein of user1825216's answer, I'm running MSBuild from a command line so I resolved this error by adding -p:Platform=x64 to the build command instead of modifying the .vcxproj.

Body:
I'm trying to get a pure x64 build running for a complex build with many solutions (some for CI, some for devs) and hundreds of project and have run into "error MSB8013: This project doesn't contain the Configuration and Platform combination of Debug|Win32"

I've reduced it to a simple configuration:

Solution A contains Project X & Project Y. Project X has a project
reference to Project Y.

Solution B contains also contains Project X.

None of the projects or solutions contain a Win32 platform - it's been deleted.

When I build solution B (as x64), I receive

error MSB8013: This project doesn't contain the Configuration and
  Platform combination of Debug|Win32

The error message sometimes contains additional information:

This error may also appear if some other project is trying to follow a
  project-to-project reference to this project, this project has been
  unloaded or is not included in the solution, and the referencing
  project does not build using the same or an equivalent Configuration
  or Platform.

The problem is the referencing project does "build using the same or an equivalent Configuration or Platform."

Looking at the msbuild diagnostic, project Y is being built because project X contains a project reference to it. But the configuration and platform properties are being deleted just before project Y is built:

1>Task "MSBuild" (TaskId:28)
1>  Removing Properties: (TaskId:28)
1>    Configuration (TaskId:28)
1>    Platform (TaskId:28)

As a result Microsoft.Cpp.Default.props kicks in and sets these to Debug|Win32:

1>Task "Message" (TaskId:11)
1>  Configuration=Debug (TaskId:11)
1>Done executing task "Message". (TaskId:11)
1>Task "Message" (TaskId:12)
1>  Platform=Win32 (TaskId:12)
1>Done executing task "Message". (TaskId:12)

How can I prevent this and make msbuild pass the chosen configuration & platform?

(I understand the ultimate solution to use NuGet to manage package dependencies, but that isn't feasible in the short term)


问:
connecting to aws elastic search with nodejs aws sdk
what is the best approach in using aws elastic search with nodejs? I am using aws ecs ec2 instance for running my docker containers and is using  the IAM role to accessing the other aws resource like S3 bucket and dynamodb from nodejs.

Can we use the same procedure for accessing the aws elastic search endpoint too?

I added an inline policy with the existing role and added the elastic search end point arn. but the nodejs sdk is not able to connect to the ES. when the aws key and id is added as environment variable in task definition it starts working. But I dont need to use that method as it will conflict with the other aws resource. (looks like the dev team is configured the program such that it looks for env)

答:
It for sure is not the best method but you can also use a ip based restriction. We currently use this and it works fine. Just set an elastic ip on your ec2 instance (if you haven't already) and set the ip address in the access policy like this:</p>

```<code>"Condition": {
        "IpAddress": {
          "aws:SourceIp": [
            "XXX.XXX.XXX.XXX",
          ]
        }
      }
</code>```

Body:
It for sure is not the best method but you can also use a ip based restriction. We currently use this and it works fine. Just set an elastic ip on your ec2 instance (if you haven't already) and set the ip address in the access policy like this:

"Condition": {
        "IpAddress": {
          "aws:SourceIp": [
            "XXX.XXX.XXX.XXX",
          ]
        }
      }


问:
Selecting a QListWidgetItem when adding it
I have a QListWidget in a Form with a QListWidgetItem displaying "Add new". When I click on it, I'd like a serie of things to happen:

A QInputDialog::getText asks for the content of the new item.

A new item is added to the list with the given text.

The list is sorted, except for the "Add new" that stays at the end (this is done by removing the "Add new" item, sorting, and adding the removed item again).

The new item is selected.

That last part is the one I'm having trouble. I've tried many different approaches, all leading to the same result: the item I want selected has a dashed border and it understood as selected (by ui->list->selectedItems() for example), but the selection color stays on the last item before the "Add new".

What I tried

item->setSelected(true);

ui->list->setCurrentItem(item);

ui->list->setCurrentRow(ui->list->row(item);

What I noticed

When the debugger is on with a breakpoint that slowly goes through those steps, I notice everything seems to work nicely, but the UI isn't updated before the function I'm calling is done.

Also, when I want to select a given item from the list from a slot called by another button click, it works correctly with item->setSelected(true); (and the others too).

My guess: I can't select the item in the same function I add it because I can't graphically select something that isn't there yet.

Any guess on how to achieve this?

Note

If you're experiencing the same problem, please read the comment on the selected answer, it was actually a signal problem!

答:
Did you try to select added item and after that set current row to row index of added item. This works in my example.

Example: mainwindow.cpp

```<code>#include <QInputDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->listWidget->addItem("Add New");
    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(slot_itemClicked(QListWidgetItem *)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slot_itemClicked(QListWidgetItem *item)
{
    if (item && (item->text() == "Add New"))
    {
        QString text = QInputDialog::getText(this, "Input item text", "Text: ");
        QListWidgetItem *newItem = new QListWidgetItem(text);

        // Add new item and sort list
        ui->listWidget->addItem(newItem);
        ui->listWidget->sortItems();

        // Move "Add New" item to list end
        item = ui->listWidget->takeItem(ui->listWidget->row(item));
        ui->listWidget->addItem(item);

        // Select new item
        // Set current row to index of new item row
        newItem->setSelected(true);
        ui->listWidget->setCurrentRow(ui->listWidget->row(newItem));
    }
}
</code>```

Body:
Did you try to select added item and after that set current row to row index of added item. This works in my example.

Example: mainwindow.cpp

#include <QInputDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->listWidget->addItem("Add New");
    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(slot_itemClicked(QListWidgetItem *)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slot_itemClicked(QListWidgetItem *item)
{
    if (item && (item->text() == "Add New"))
    {
        QString text = QInputDialog::getText(this, "Input item text", "Text: ");
        QListWidgetItem *newItem = new QListWidgetItem(text);

        // Add new item and sort list
        ui->listWidget->addItem(newItem);
        ui->listWidget->sortItems();

        // Move "Add New" item to list end
        item = ui->listWidget->takeItem(ui->listWidget->row(item));
        ui->listWidget->addItem(item);

        // Select new item
        // Set current row to index of new item row
        newItem->setSelected(true);
        ui->listWidget->setCurrentRow(ui->listWidget->row(newItem));
    }
}