问:
How do you set Entry parameter 'show' in Tkinter to always show fixed number of asterisks in Entry field?
I set the 'show' parameter to '*' so that Entry field doesn't reveal what was typed in. The issue I am having is, it hints how long the word actually is. So, for example, if I type in word 'blue', it will show as '****' which hints it's a 4 characters long word. Also, the solution code needs to work with the random function filling in the above mentioned field

How do I solve this easy way?

EDIT: To put things into a context this is the code of the app I made.

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

def num_guess():
    try:
        int(num_input.get())

    except ValueError:
        Ans = "You must enter a number in your number field!\n"
        result_field.insert(INSERT, Ans)

    if int(num_input.get()) == int(hidden_num):
        Ans = "Congrats you guessed correctly!\n"
        result_field.insert(INSERT, Ans)
        secret_num.delete(0, END)
        secret_num.insert(END, hidden_num)

    elif int(num_input.get()) in range(int(hidden_num) - 2, int(hidden_num) + 3):
        Ans = "You are very close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 5, int(hidden_num) + 6):
        Ans = "You are close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 10, int(hidden_num) + 11):
        Ans = "You are relatively close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 15, int(hidden_num) + 16):
        Ans = "You are far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    else:
        Ans = "You are very far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

def start_new():
    global hidden_num
    result_field.delete('1.0', END)
    secret_num.delete(0, END)
    secret_num.insert(END, random.randint(1,100))
    hidden_num = secret_num.get()
    secret_num.delete(0, END)
    secret_num.insert(END, "***")
    result_field.insert(INSERT, "Now enter your number as a guess!\n")

def hide_num():
    global hidden_num

    try:
        int(secret_num.get())
        hidden_num = secret_num.get()
        secret_num.delete(0, END)
        secret_num.insert(END, "***")
        result_field.insert(INSERT, "Now enter your number as a guess!\n")

    except ValueError:
        Ans = "You must enter a number in secret number field!\n"
        result_field.insert(INSERT, Ans)

hidden_num = 0

window = Tk()
window.title('Guess the Number!')
Label(window, text = "").grid(row=0)
Label(window, text = "Secret number:").grid(row=7, column=1, padx=8)
Label(window, text = "Enter your number:").grid(row=8, column=1, padx=8)
Label(window, text = "").grid(row=10)

#find textbox code!
result_field = Text(window, width=54, height=18)
result_field.grid(row=1, column=1, columnspan=6, rowspan=6, padx=8)
result_field.insert(INSERT, "Click 'Start new' to start a new game!\n")

sb1 = Scrollbar(window)
sb1.grid(row=1, column=7, rowspan=6, sticky = 'NS')
result_field.configure(yscrollcommand=sb1.set)
sb1.configure(command = result_field.yview)

secret_num = Entry(window, width=6)
secret_num.grid(row=7, column=2)

num_input = Entry(window, width=6)
num_input.grid(row=8, column=2)

b1 = Button(window, text = "Take a guess!", command=num_guess, width=12)
b1.grid(row=9, column=1, pady=8, padx=8)
b2 = Button(window, text = "Start new", command=start_new, width=12)
b2.grid(row=9, column=2, pady=8, padx=8)
b3 = Button(window, text = "Quit", command=window.destroy, width=12)
b3.grid(row=9, column=3, pady=8, padx=8)
b4 = Button(window, text = "Hide number", command=hide_num, width=12)
b4.grid(row=7, column=3, sticky = 'W')

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

答:
Use this code:

from tkinter import *
root = Tk()

passwordInput = Entry(root, show = "      ")
passwordInput.pack()

root.mainloop()
```

Make sure to copy the code in the show = carefully. It will be not the same length as an empty space so to throw people off. Copy it here (between the quotes): "      "
Note that it is an iEmpty blank character

If you want, you can set the show to this:  (just a space key)

Body:
I set the 'show' parameter to '*' so that Entry field doesn't reveal what was typed in. The issue I am having is, it hints how long the word actually is. So, for example, if I type in word 'blue', it will show as '****' which hints it's a 4 characters long word. Also, the solution code needs to work with the random function filling in the above mentioned field

How do I solve this easy way?

EDIT: To put things into a context this is the code of the app I made.

import random
from tkinter import *

def num_guess():
    try:
        int(num_input.get())

    except ValueError:
        Ans = "You must enter a number in your number field!\n"
        result_field.insert(INSERT, Ans)

    if int(num_input.get()) == int(hidden_num):
        Ans = "Congrats you guessed correctly!\n"
        result_field.insert(INSERT, Ans)
        secret_num.delete(0, END)
        secret_num.insert(END, hidden_num)

    elif int(num_input.get()) in range(int(hidden_num) - 2, int(hidden_num) + 3):
        Ans = "You are very close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 5, int(hidden_num) + 6):
        Ans = "You are close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 10, int(hidden_num) + 11):
        Ans = "You are relatively close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 15, int(hidden_num) + 16):
        Ans = "You are far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    else:
        Ans = "You are very far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

def start_new():
    global hidden_num
    result_field.delete('1.0', END)
    secret_num.delete(0, END)
    secret_num.insert(END, random.randint(1,100))
    hidden_num = secret_num.get()
    secret_num.delete(0, END)
    secret_num.insert(END, "***")
    result_field.insert(INSERT, "Now enter your number as a guess!\n")

def hide_num():
    global hidden_num

    try:
        int(secret_num.get())
        hidden_num = secret_num.get()
        secret_num.delete(0, END)
        secret_num.insert(END, "***")
        result_field.insert(INSERT, "Now enter your number as a guess!\n")

    except ValueError:
        Ans = "You must enter a number in secret number field!\n"
        result_field.insert(INSERT, Ans)

hidden_num = 0

window = Tk()
window.title('Guess the Number!')
Label(window, text = "").grid(row=0)
Label(window, text = "Secret number:").grid(row=7, column=1, padx=8)
Label(window, text = "Enter your number:").grid(row=8, column=1, padx=8)
Label(window, text = "").grid(row=10)

#find textbox code!
result_field = Text(window, width=54, height=18)
result_field.grid(row=1, column=1, columnspan=6, rowspan=6, padx=8)
result_field.insert(INSERT, "Click 'Start new' to start a new game!\n")

sb1 = Scrollbar(window)
sb1.grid(row=1, column=7, rowspan=6, sticky = 'NS')
result_field.configure(yscrollcommand=sb1.set)
sb1.configure(command = result_field.yview)

secret_num = Entry(window, width=6)
secret_num.grid(row=7, column=2)

num_input = Entry(window, width=6)
num_input.grid(row=8, column=2)

b1 = Button(window, text = "Take a guess!", command=num_guess, width=12)
b1.grid(row=9, column=1, pady=8, padx=8)
b2 = Button(window, text = "Start new", command=start_new, width=12)
b2.grid(row=9, column=2, pady=8, padx=8)
b3 = Button(window, text = "Quit", command=window.destroy, width=12)
b3.grid(row=9, column=3, pady=8, padx=8)
b4 = Button(window, text = "Hide number", command=hide_num, width=12)
b4.grid(row=7, column=3, sticky = 'W')

window.mainloop()

Body:
Use this code:

from tkinter import *
root = Tk()

passwordInput = Entry(root, show = "      ")
passwordInput.pack()

root.mainloop()

Make sure to copy the code in the show = carefully. It will be not the same length as an empty space so to throw people off. Copy it here (between the quotes): "      "
Note that it is an iEmpty blank character

If you want, you can set the show to this:  (just a space key)


来源: stackexchange

问:
“Deleted” from array still exists
I am trying to delete some information from an array, however when I go to search for the deleted thing it still shows up.

I have tried this code:

```<code>function removeperson() {

    var search = prompt("Type in someone's name to remove them.");
    while(!found && i < people.names.length) {
        if(people.names[i] == search){
            found = true;
        } else {
            i++;
        }
    }
    if(found){
            people.names.splice[i, 1];
            people.emails.splice[i, 1];
            people.phonenums.splice[i, 1];
            alert("Person successfully removed!");
            found = false;
    } else {
            alert("That person is not here or has already been deleted.");
            found = false;
    }
    i = 0;

}
</code>```

However, when I use my search function to search for the deleted thing, it still appears. The full code is available here: https://js.do/nioiluc/321017

答:
splice method it's not being executed. Change to

```<code>people.names.splice(i,1)
</code>```

ContentLicense: CC BY-SA 4.0

Title: “Deleted” from array still exists

Body:
I am trying to delete some information from an array, however when I go to search for the deleted thing it still shows up.

I have tried this code:

function removeperson() {

    var search = prompt("Type in someone's name to remove them.");
    while(!found && i < people.names.length) {
        if(people.names[i] == search){
            found = true;
        } else {
            i++;
        }
    }
    if(found){
            people.names.splice[i, 1];
            people.emails.splice[i, 1];
            people.phonenums.splice[i, 1];
            alert("Person successfully removed!");
            found = false;
    } else {
            alert("That person is not here or has already been deleted.");
            found = false;
    }
    i = 0;

}

However, when I use my search function to search for the deleted thing, it still appears. The full code is available here: https://js.do/nioiluc/321017

Body:
splice method it's not being executed. Change to

people.names.splice(i,1)


问:
IEqualityComparer and singleton
I was wondering if there is possibility to use singleton as comparerObject in for example Distinct ??

Let's say that I have a list of element and I need to use distinct function on that list. Normally I would do that this way

```<code>var result  = list.Distinct(new ListElementComparer);
</code>```

ListElementComparer is a class which implements IEqualityComparer interface.
However let's assume that I will be using code mentioned above quite frequently for example that way .

```<code>List<List<Element>> elementList = new List<List<Elements>>();
List<List<Element>> resultList  new List<List<Element>>();

foreach(var element in elementList )
   resultList.AddRange(element.Distinct(new ListElementComparer() )  );
</code>```

So as You can object of ListElementComparer might be created quite a lot of times. In this case is there any point of using singletone insted of createing ListElementComparer in each iteration ? Will the distinct method work if I use singleton ??

答:
Yes, absolutely, it will work fine with a singleton:

```<code>public class ListElementComparer : IEqualityComparer<List<Element>>
{
    public static ListElementComparer Instance { get { return instance; } }

    private static readonly ListElementComparer instance =
        new ListElementComparer();

    private ListElementComparer() {}

    // Implement IEqualityComparer<List<Element>> here
}
</code>```

Then:

```<code>resultList.AddRange(element.Distinct(ListElementComparer.Instance);
</code>```

Note that your whole loop can be avoided somewhat:

```<code>var resultList = elementList
                     .SelectMany(x => x.Distinct(ListElementComparer.Instance))
                     .ToList();
</code>```

(This doesn't quite work with the originally-declared types, because your sample code doesn't quite work either... but something similar would.)

ContentLicense: CC BY-SA 3.0

Title: IEqualityComparer and singleton

Body:
I was wondering if there is possibility to use singleton as comparerObject in for example Distinct ??

Let's say that I have a list of element and I need to use distinct function on that list. Normally I would do that this way

var result  = list.Distinct(new ListElementComparer);

ListElementComparer is a class which implements IEqualityComparer interface.
However let's assume that I will be using code mentioned above quite frequently for example that way .

List<List<Element>> elementList = new List<List<Elements>>();
List<List<Element>> resultList  new List<List<Element>>();

foreach(var element in elementList )
   resultList.AddRange(element.Distinct(new ListElementComparer() )  );

So as You can object of ListElementComparer might be created quite a lot of times. In this case is there any point of using singletone insted of createing ListElementComparer in each iteration ? Will the distinct method work if I use singleton ??

Body:
Yes, absolutely, it will work fine with a singleton:

public class ListElementComparer : IEqualityComparer<List<Element>>
{
    public static ListElementComparer Instance { get { return instance; } }

    private static readonly ListElementComparer instance =
        new ListElementComparer();

    private ListElementComparer() {}

    // Implement IEqualityComparer<List<Element>> here
}

Then:

resultList.AddRange(element.Distinct(ListElementComparer.Instance);

Note that your whole loop can be avoided somewhat:

var resultList = elementList
                     .SelectMany(x => x.Distinct(ListElementComparer.Instance))
                     .ToList();

(This doesn't quite work with the originally-declared types, because your sample code doesn't quite work either... but something similar would.)


问:
How do I change the content of a column to pick from another column based on a criteria, leaving that column blank WHEN it does pick from it
I need to replace the value of a column(LastName) with values from another column('MiddleName') IF column "LastName" contains "." and column B contains non null values while deleting the content of column('MiddleName') only if the content has been moved to column ("LastName").

```<code>NIL

NIL
</code>```

That Column 'MiddleName' becomes blank if column "LastName" contained "." and the column 'MiddleName' (which had content) has now been moved to column "LastName".

For instance; if the columns contained;

```<code>MiddleName   LastName
john            .
james        phillips
Mary            .

The procedure should then make it:
MiddleName   LastName
             john
james        phillips
             Mary
</code>```

答:
This is easier to do with new custom columns rather than replacing the existing ones.</p>

```<code>Middle = if [LastName] = "." then null else [MiddleName]

Last   = if [LastName] = "." then [MiddleName] else [LastName]
</code>```

Body:
I need to replace the value of a column(LastName) with values from another column('MiddleName') IF column "LastName" contains "." and column B contains non null values while deleting the content of column('MiddleName') only if the content has been moved to column ("LastName").

NIL

NIL

That Column 'MiddleName' becomes blank if column "LastName" contained "." and the column 'MiddleName' (which had content) has now been moved to column "LastName".

For instance; if the columns contained;

MiddleName   LastName
john            .
james        phillips
Mary            .

The procedure should then make it:
MiddleName   LastName
             john
james        phillips
             Mary

Body:
This is easier to do with new custom columns rather than replacing the existing ones.

Middle = if [LastName] = "." then null else [MiddleName]

Last   = if [LastName] = "." then [MiddleName] else [LastName]


问:
Create and save a file with JavaScript
I have data that I want to write to a file, and open a file dialog for the user to choose where to save the file.  It would be great if it worked in all browsers, but it has to work in Chrome.  I want to do this all client-side.

Basically I want to know what to put in this function:

```<code>saveFile: function(data)
{
}
</code>```

Where the function takes in data, has the user select a location to save the file, and creates a file in that location with that data.

Using HTML is fine too, if that helps.

答:
StreamSaver is an alternative to save very large files without having to keep all data in the memory.
In fact it emulates everything the server dose when saving a file but all client side with service worker.

You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream

There is a few example showcasing:

How to save multiple files as a zip

piping a readableStream from eg Response or blob.stream() to StreamSaver

manually writing to the writable stream as you type something

or recoding a video/audio

Here is an example in it's simplest form:

```<code>const fileStream = streamSaver.createWriteStream('filename.txt')

new Response('StreamSaver is awesome').body
  .pipeTo(fileStream)
  .then(success, error)
</code>```

If you want to save a blob you would just convert that to a readableStream

```<code>new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference
</code>```

Title: Create and save a file with JavaScript

Body:
I have data that I want to write to a file, and open a file dialog for the user to choose where to save the file.  It would be great if it worked in all browsers, but it has to work in Chrome.  I want to do this all client-side.

Basically I want to know what to put in this function:

saveFile: function(data)
{
}

Where the function takes in data, has the user select a location to save the file, and creates a file in that location with that data.

Using HTML is fine too, if that helps.

Body:
StreamSaver is an alternative to save very large files without having to keep all data in the memory.
In fact it emulates everything the server dose when saving a file but all client side with service worker.

You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream

There is a few example showcasing:

How to save multiple files as a zip

piping a readableStream from eg Response or blob.stream() to StreamSaver

manually writing to the writable stream as you type something

or recoding a video/audio

Here is an example in it's simplest form:

const fileStream = streamSaver.createWriteStream('filename.txt')

new Response('StreamSaver is awesome').body
  .pipeTo(fileStream)
  .then(success, error)

If you want to save a blob you would just convert that to a readableStream

new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference


问:
How do I track down what went wrong when an email to AWS-SES goes missing?
I ran every step in
Getting Started Receiving Email with Amazon SES
and all went smoothly. I left the receipt rule
open so that any email address is accepted.
But when I send an email to joe@example.com (for my own example.com), no files are created in the S3 bucket.
The file AMAZON_SES_SETUP_NOTIFICATION is there all right, but nothing else.

How do I go about debugging this issue? Where does one track down what went wrong?

答:
I assume you have a rule for "domain.com" as a recipient which will match for all emails for this domain email addresses.
Couple of things you can check:

MX record for your domain should point to SES inbound endpoint (changing MX may break your incoming emails if you're using it somewhere else already)

Is the rule-set where you have created the rule active ? There can only be one rule-set active.

S3 permission, S3 bucket requires a bucket policy to allow put object from SES.

https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-permissions.html

To debug , check if you have received any bounce back.


问:
Android Studio Corrupted .java file after improper shutdown
I hibernated my laptop when Android Studio was running and found later that the laptop had been shut down. Now one of my source files is appearing empty in Android Studio and in Wordpad as well. When I open it in Notepad++, it shows NUL character. The file has the same size as it had before which means that the file content is not lost (hopefully).

How do I recover the actual content of this file? I need this as I didn't have a backup of this file.

答:
I'm not sure what makes it to happen and android studio is far the worst IDE i've worked with (how can a tool dare to edit and save the user files without even ask? the usability team of google deserve a nobel)

But this is what I do to manage solve it...

As soon as you identify an event like this happened close android studio, stop any build in progress and dont try to run the project...

it seams that sometimes the modifications aren't done in the real source file, but android studio is opening some intermediate files instead of the original sources and showing it to you when you open the source... some kind of symbolic link mess

So with android studio closed open the file explorer go to your workspace and create a copy of your project in another directory (as far of android studio as possible)

open your souce files with any text editor and check if they are still okay...

re-open android studio and copy/paste file by file, the contents of the copy project you made to the official project

It is super boring and may take a while depeding of your project size, but i managed to recover over 90% of my files like this


问:
Why does the C++ standard require the `Clock::now` function to be `static`?
With C++11, C++ has some timing facilities in the standard. One of these facilities is a standard interface for clocks, that basically allows getting the time at the call of the now function of the clock.

All is well up until this point but I fail to see the reason for requiring now to be a static function. On a hosted system, the standard clocks might be implementable purely with system calls or by reading the processor counters etc. However, this limits the implementation of custom clocks that needs to maintain some state. With this interface, one either cannot implement some clocks or has to use global state.

One issue I ran into was basically synchronizing a local clock to the time I got from an NTP server. The code simply looks like this:

class sntp_clock
{
public:
    sntp_clock()
        : local_time_at_ctor(read_some_cpu_counter())
        , sntp_time_at_ctor(read_sntp_time()) {}

    sntp_time_t now() const {
        return sntp_time_at_ctor + (read_some_cpu_counter() - local_time_at_ctor);
    }

    /* required types etc */

private:
    local_time_t local_time_at_ctor;
    sntp_time_t sntp_time_at_ctor;
};
```

Since I can't make now static without making the state static as well, this clock does not satisfy the requirements of a Clock in C++ standard. But each NTP server will have separate state.

Additionally, for efficiency reasons, I may not want to start the cpu counter a clock instance exists, but again, since now is static, I can't know exactly when to start to clock, or when to stop it.

My question is why do clocks have static now requirement?

Note: The current standard draft requires now to be static: http://eel.is/c++draft/time.clock.req#tab:time.clock

Boost.Chrono documentation has the same requirement: https://www.boost.org/doc/libs/1_63_0/doc/html/chrono/reference.html#chrono.reference.cpp0x.clock

答:
There were both theoretical and practical concerns that drove this decision.

The Theoretical

There's a joke that a person with a watch always knows what time it is, but a person with two watches never does.  There's just a little bit of truth in that joke, and it did influence the decision.  If an application needs to know the current time in two or more places, and if clocks are stateful, then there is an issue in ensuring that the same instance of the clock be used in all places to ensure that all parts of the code are dealing with the same definition of "current time."

By making clocks stateless, but allowing multiple clocks with different types, the type system can help the programmer ensure that a program uses the same definition of current time in different places of the program.  And yet in those cases where one needs multiple definitions of time, then that too is available, just as distinct types.

The Practical

As more of a practical consideration, the very first clients of the chrono::clock code was chrono itself.  We had to eat our own dog food.  Take for example an implementation of condition_variable::wait_until:

https://github.com/llvm-mirror/libcxx/blob/master/include/__mutex_base#L377-L385

```<code>template <class _Clock, class _Duration>
cv_status
condition_variable::wait_until(unique_lock<mutex>& __lk,
                               const chrono::time_point<_Clock, _Duration>& __t)
{
    using namespace chrono;
    wait_for(__lk, __t - _Clock::now());
    return _Clock::now() < __t ? cv_status::no_timeout : cv_status::timeout;
}
</code>```

Here a function is taking a single generic time_point, and the algorithm needs to find the current time associated with that time_point.  By packing the type of the Clock into the type of the time_point and by having a static now(), the code is very clean to write, and has a very clean interface.  Yet it is generic enough that this code will work with any user-written custom clock:  not just the std-specified clocks.

Had clocks been stateful, then either:

condition_variable::wait_until could not get the current time, or

The client would have to pass in the clock the time_point is measured against as well.

Neither of the above two choices seemed palatable to me.

Note that condition_variable::wait_until is not a special case, but just one example out of many such algorithms.  Indeed, I assumed that not only standards implementors would write such algorithms, but the general public would too.  Here's an example of the latter:

https://stackoverflow.com/a/35293183/576911

Yes, I have run into cases where people want stateful clocks.  The OP of this question offers such an example.  But since there is the option that "stateful clocks" can still be given static state, and if you need other state, use a different type;  And because of the advantages of stateless clocks stated above;  The choice was made that the advantage lay with the stateless clock design.

Update 1

I've been thinking more about the client that says:

So is my stateful clock not good code?

I think a stateful clock is fine as long as one realizes the limitations that are on it.  And unfortunately I believe this is an issue that is more complicated than needs be because of a minor bug in the standard.

From a practical standpoint, there's only one thing you can't do with a stateful clock that you can do with a stateless clock, and it goes back to the section above titled The Practical.

You can not instantiate an algorithm (std or otherwise) that requires a template parameter to be a ClockTM.

For example if you have a time_point based on a stateful clock, you can not use that time_point to call condition_variable::wait_until.  If you don't want to do that anyway, that doesn't mean your stateful clock is bad.  If your stateful clock serves your purposes, then that is fine.

In C++20, there's even an example of a clock that doesn't meet all of the C++11-17 clock requirements:

```<code>struct local_t {};
</code>```

Yes, that is (sort of) a clock.  But it doesn't do anything, almost.  It is used to create a family of time_points that have no associated now():

```<code>template<class Duration>
    using local_time  = time_point<local_t, Duration>;
</code>```

And this turns out to be really useful when distinguishing UTC time points from time points that are associated with an as-yet-unspecified time zone (think type safety).

So if creating a clock without a static now() is ok for the standard, why isn't it ok for you?!  And the only reason I can think of is that "minor bug" in the standard I reference above.

27.6 [time.point] in the C++20 spec says this about template<class Clock, class Duration> class time_point:

1 Clock shall either satisfy the Cpp17Clock requirements (27.3) or be the type local_t.

I now believe this is overly restrictive.  Programmers ought to be able to instantiate time_point with a stateful clock.  They just can't call condition_variable::wait_until (et al.) with that time_point.  But they can still get all of the algebraic benefits of using that time_point and the durations resulting from its differences.

There's no good reason for this restriction except for the standard saying so.  And the very existence of local_t which also doesn't meet the Cpp17Clock requirements pretty much proves the point.

1 Clock shall either satisfy the Cpp17Clock requirements (27.3) or be the type local_t have the nested type duration if the instantiation defaults the template parameter Duration.

Update 2

There is now a paper tracking this issue.

Update 3

The proposed changes are now in the working draft for the standard after C++20:

http://eel.is/c++draft/time.point.general

http://eel.is/c++draft/thread.req.paramname

Much thanks to Alexey Dmitriev for driving this work.

Body:
With C++11, C++ has some timing facilities in the standard. One of these facilities is a standard interface for clocks, that basically allows getting the time at the call of the now function of the clock.

All is well up until this point but I fail to see the reason for requiring now to be a static function. On a hosted system, the standard clocks might be implementable purely with system calls or by reading the processor counters etc. However, this limits the implementation of custom clocks that needs to maintain some state. With this interface, one either cannot implement some clocks or has to use global state.

One issue I ran into was basically synchronizing a local clock to the time I got from an NTP server. The code simply looks like this:

class sntp_clock
{
public:
    sntp_clock()
        : local_time_at_ctor(read_some_cpu_counter())
        , sntp_time_at_ctor(read_sntp_time()) {}

    sntp_time_t now() const {
        return sntp_time_at_ctor + (read_some_cpu_counter() - local_time_at_ctor);
    }

    /* required types etc */

private:
    local_time_t local_time_at_ctor;
    sntp_time_t sntp_time_at_ctor;
};

Since I can't make now static without making the state static as well, this clock does not satisfy the requirements of a Clock in C++ standard. But each NTP server will have separate state.

Additionally, for efficiency reasons, I may not want to start the cpu counter a clock instance exists, but again, since now is static, I can't know exactly when to start to clock, or when to stop it.

My question is why do clocks have static now requirement?

Note: The current standard draft requires now to be static: http://eel.is/c++draft/time.clock.req#tab:time.clock

Boost.Chrono documentation has the same requirement: https://www.boost.org/doc/libs/1_63_0/doc/html/chrono/reference.html#chrono.reference.cpp0x.clock

Body:
There were both theoretical and practical concerns that drove this decision.

The Theoretical

There's a joke that a person with a watch always knows what time it is, but a person with two watches never does.  There's just a little bit of truth in that joke, and it did influence the decision.  If an application needs to know the current time in two or more places, and if clocks are stateful, then there is an issue in ensuring that the same instance of the clock be used in all places to ensure that all parts of the code are dealing with the same definition of "current time."

By making clocks stateless, but allowing multiple clocks with different types, the type system can help the programmer ensure that a program uses the same definition of current time in different places of the program.  And yet in those cases where one needs multiple definitions of time, then that too is available, just as distinct types.

The Practical

As more of a practical consideration, the very first clients of the chrono::clock code was chrono itself.  We had to eat our own dog food.  Take for example an implementation of condition_variable::wait_until:

https://github.com/llvm-mirror/libcxx/blob/master/include/__mutex_base#L377-L385

template <class _Clock, class _Duration>
cv_status
condition_variable::wait_until(unique_lock<mutex>& __lk,
                               const chrono::time_point<_Clock, _Duration>& __t)
{
    using namespace chrono;
    wait_for(__lk, __t - _Clock::now());
    return _Clock::now() < __t ? cv_status::no_timeout : cv_status::timeout;
}

Here a function is taking a single generic time_point, and the algorithm needs to find the current time associated with that time_point.  By packing the type of the Clock into the type of the time_point and by having a static now(), the code is very clean to write, and has a very clean interface.  Yet it is generic enough that this code will work with any user-written custom clock:  not just the std-specified clocks.

Had clocks been stateful, then either:

condition_variable::wait_until could not get the current time, or

The client would have to pass in the clock the time_point is measured against as well.

Neither of the above two choices seemed palatable to me.

Note that condition_variable::wait_until is not a special case, but just one example out of many such algorithms.  Indeed, I assumed that not only standards implementors would write such algorithms, but the general public would too.  Here's an example of the latter:

https://stackoverflow.com/a/35293183/576911

Yes, I have run into cases where people want stateful clocks.  The OP of this question offers such an example.  But since there is the option that "stateful clocks" can still be given static state, and if you need other state, use a different type;  And because of the advantages of stateless clocks stated above;  The choice was made that the advantage lay with the stateless clock design.

Update 1

I've been thinking more about the client that says:

So is my stateful clock not good code?

I think a stateful clock is fine as long as one realizes the limitations that are on it.  And unfortunately I believe this is an issue that is more complicated than needs be because of a minor bug in the standard.

From a practical standpoint, there's only one thing you can't do with a stateful clock that you can do with a stateless clock, and it goes back to the section above titled The Practical.

You can not instantiate an algorithm (std or otherwise) that requires a template parameter to be a ClockTM.

For example if you have a time_point based on a stateful clock, you can not use that time_point to call condition_variable::wait_until.  If you don't want to do that anyway, that doesn't mean your stateful clock is bad.  If your stateful clock serves your purposes, then that is fine.

In C++20, there's even an example of a clock that doesn't meet all of the C++11-17 clock requirements:

struct local_t {};

Yes, that is (sort of) a clock.  But it doesn't do anything, almost.  It is used to create a family of time_points that have no associated now():

template<class Duration>
    using local_time  = time_point<local_t, Duration>;

And this turns out to be really useful when distinguishing UTC time points from time points that are associated with an as-yet-unspecified time zone (think type safety).

So if creating a clock without a static now() is ok for the standard, why isn't it ok for you?!  And the only reason I can think of is that "minor bug" in the standard I reference above.

27.6 [time.point] in the C++20 spec says this about template<class Clock, class Duration> class time_point:

1 Clock shall either satisfy the Cpp17Clock requirements (27.3) or be the type local_t.

I now believe this is overly restrictive.  Programmers ought to be able to instantiate time_point with a stateful clock.  They just can't call condition_variable::wait_until (et al.) with that time_point.  But they can still get all of the algebraic benefits of using that time_point and the durations resulting from its differences.

There's no good reason for this restriction except for the standard saying so.  And the very existence of local_t which also doesn't meet the Cpp17Clock requirements pretty much proves the point.

1 Clock shall either satisfy the Cpp17Clock requirements (27.3) or be the type local_t have the nested type duration if the instantiation defaults the template parameter Duration.

Update 2

There is now a paper tracking this issue.

Update 3

The proposed changes are now in the working draft for the standard after C++20:

http://eel.is/c++draft/time.point.general

http://eel.is/c++draft/thread.req.paramname

Much thanks to Alexey Dmitriev for driving this work.


问:
how to use java streams api to transform a hierarchal map to a flat map
So, I have this function which takes a map, where a name is associated with one of a number of different indexes into an array.  The index numbers will only ever have one name associated with them, so no duplicates and no nulls so it's safe to flatten the hierarchy using the following function.

```<code>public Map<Integer, Object> normalize( Map<Object, List<Integer>> hierarchalMap ) {

    Map<Integer, Object> normalizedMap = new HashMap<>();
    for (Map.Entry<Object, List<Integer>> entry : hierarchalMap.entrySet()) {
        for (Integer integer : entry.getValue()) {
            noramizedMap.put(integer, entry.getKey());
        }
    }
    return normalizedMap;
}
</code>```

I'm trying to change this function into using the streams API and I've gotten this far:

```<code>Map<Integer, Object> noramizedMap = new HashMap<>();
for (Map.Entry<Object, List<Integer>> entry : vars.entrySet()) {

    entry.getValue().forEach(e -> noramizedMap.put(e, entry.getValue()));

}
</code>```

If this were some other functional language i'd do a partial bind or whatever but with java I try and unwrap the outer loop into a stream...collectTo i just get lost.

答:
Here are two convenience collectors you can use in java 8 that are not just limited to maps.

```<code>public static <T, K, V> Collector<T, ?, Map<K, V>> flatInverseMapping(Function<? super T, ? extends Stream<? extends K>> keyStreamFunction,
        Function<? super T, ? extends V> valueFunction) {
    return Collector.of(HashMap::new,
            (m, v) ->
                    keyStreamFunction.apply(v).forEach(innerV -> m.put(innerV, valueFunction.apply(v))),
            (m1, m2) -> {
                m1.putAll(m2);
                return m2;
            });
}

public static <T, K, V> Collector<T, ?, Map<K, V>> flatInverseMapping(Function<? super T, ? extends Collection<? extends K>> keyStreamFunction,
        Function<? super T, ? extends V> valueFunction) {
    return Collector.of(HashMap::new,
            (m, v) ->
                    keyStreamFunction.apply(v).forEach(innerV -> m.put(innerV, valueFunction.apply(v))),
            (m1, m2) -> {
                m1.putAll(m2);
                return m2;
            });
}
</code>```

Since both streams and collections have a forEach, it makes both implementations identical other than input object.

For a brief explanation of how this works, the output of the collector is a Map of the K and V (key and value) params that are defined by the outputs of the two functions. For each of the key values derived from the input object in the stream, the same value function will be applied so the map will be inverted with a consistent value across shared keys. Note that if there are multiple items in the stream that resolve to the same keys, this will not throw the merge exception like the normal toMap implementation. The BiConsumer will need to be changed to this to maintain that behavior:

```<code>(var1, var2) -> {
    Iterator<Map.Entry<K,V>> var3 = var2.entrySet().iterator();

    while(var3.hasNext()) {
        Map.Entry<K,V> var4 = var3.next();
        var1.merge(var4.getKey(), var4.getValue(), (v0, v1) -> {
            throw new IllegalStateException(String.format("Duplicate key %s", v0));
        });
    }
    return var1;
}
</code>```

For reference, this was essentially copied from the Collectors.toMap code.

Body:
So, I have this function which takes a map, where a name is associated with one of a number of different indexes into an array.  The index numbers will only ever have one name associated with them, so no duplicates and no nulls so it's safe to flatten the hierarchy using the following function.

public Map<Integer, Object> normalize( Map<Object, List<Integer>> hierarchalMap ) {

    Map<Integer, Object> normalizedMap = new HashMap<>();
    for (Map.Entry<Object, List<Integer>> entry : hierarchalMap.entrySet()) {
        for (Integer integer : entry.getValue()) {
            noramizedMap.put(integer, entry.getKey());
        }
    }
    return normalizedMap;
}

I'm trying to change this function into using the streams API and I've gotten this far:

Map<Integer, Object> noramizedMap = new HashMap<>();
for (Map.Entry<Object, List<Integer>> entry : vars.entrySet()) {

    entry.getValue().forEach(e -> noramizedMap.put(e, entry.getValue()));

}

If this were some other functional language i'd do a partial bind or whatever but with java I try and unwrap the outer loop into a stream...collectTo i just get lost.

Body:
Here are two convenience collectors you can use in java 8 that are not just limited to maps.

public static <T, K, V> Collector<T, ?, Map<K, V>> flatInverseMapping(Function<? super T, ? extends Stream<? extends K>> keyStreamFunction,
        Function<? super T, ? extends V> valueFunction) {
    return Collector.of(HashMap::new,
            (m, v) ->
                    keyStreamFunction.apply(v).forEach(innerV -> m.put(innerV, valueFunction.apply(v))),
            (m1, m2) -> {
                m1.putAll(m2);
                return m2;
            });
}

public static <T, K, V> Collector<T, ?, Map<K, V>> flatInverseMapping(Function<? super T, ? extends Collection<? extends K>> keyStreamFunction,
        Function<? super T, ? extends V> valueFunction) {
    return Collector.of(HashMap::new,
            (m, v) ->
                    keyStreamFunction.apply(v).forEach(innerV -> m.put(innerV, valueFunction.apply(v))),
            (m1, m2) -> {
                m1.putAll(m2);
                return m2;
            });
}

Since both streams and collections have a forEach, it makes both implementations identical other than input object.

For a brief explanation of how this works, the output of the collector is a Map of the K and V (key and value) params that are defined by the outputs of the two functions. For each of the key values derived from the input object in the stream, the same value function will be applied so the map will be inverted with a consistent value across shared keys. Note that if there are multiple items in the stream that resolve to the same keys, this will not throw the merge exception like the normal toMap implementation. The BiConsumer will need to be changed to this to maintain that behavior:

(var1, var2) -> {
    Iterator<Map.Entry<K,V>> var3 = var2.entrySet().iterator();

    while(var3.hasNext()) {
        Map.Entry<K,V> var4 = var3.next();
        var1.merge(var4.getKey(), var4.getValue(), (v0, v1) -> {
            throw new IllegalStateException(String.format("Duplicate key %s", v0));
        });
    }
    return var1;
}

For reference, this was essentially copied from the Collectors.toMap code.


问:
Why ng build just doesn’t work in the Angular app?
Created a new project, did not change anything. I started ng build, took the dist folder (only it) and ran it on the local server. In the end, nothing. What's wrong?</p>

答:
So i followed your link and used the view source to see what your base href is. Currently, your base href in your index.html is set to:

```<code> <base href="/my-dream-app">
</code>```

if you change this to:

```<code><base href="https://artartem.000webhostapp.com/my-dream-app/index.html">
</code>```

your application should run as intended.

Body:
So i followed your link and used the view source to see what your base href is. Currently, your base href in your index.html is set to:

 <base href="/my-dream-app">

if you change this to:

<base href="https://artartem.000webhostapp.com/my-dream-app/index.html">

your application should run as intended.


问:
delete unwanted properties from the javascript object
I have a javascript object like the one below with several fields and arrays and arrays within arrays. I'm only interested only in non-junk fields and wanted to remove all the junk properties from the objects. How can I do that using lodash?

I can do that by using delete, but I don't want to do that because that list is huge and I don't want to keep changing my code to write a delete every time a new junk property is added to my object.

```<code>{
 state: 'New York',
 country: 'usa',
 counties : [['washington','DC'],'Long Island',['New','Jersey']],
 city : 'Manhattan',
 zip: '43543545',
 JunkOne : ['3453454','45345','45345'],
 JunkTwo: '5454545',
 JunkThree: {adc:'4545',vdfd:'45345'}
}
</code>```

答:
Disappointed that none of these answers solve the problem without making a new object (copy). I want something that works like _.set() that can delete at a path without causing an error when the path doesn't completely exist. Came up with this:

```<code>_.set(obj, 'path.to.property', null);
delete obj.path.to.property;
</code>```

Body:
I have a javascript object like the one below with several fields and arrays and arrays within arrays. I'm only interested only in non-junk fields and wanted to remove all the junk properties from the objects. How can I do that using lodash?

I can do that by using delete, but I don't want to do that because that list is huge and I don't want to keep changing my code to write a delete every time a new junk property is added to my object.

{
 state: 'New York',
 country: 'usa',
 counties : [['washington','DC'],'Long Island',['New','Jersey']],
 city : 'Manhattan',
 zip: '43543545',
 JunkOne : ['3453454','45345','45345'],
 JunkTwo: '5454545',
 JunkThree: {adc:'4545',vdfd:'45345'}
}

Body:
Disappointed that none of these answers solve the problem without making a new object (copy). I want something that works like _.set() that can delete at a path without causing an error when the path doesn't completely exist. Came up with this:

_.set(obj, 'path.to.property', null);
delete obj.path.to.property;


问:
Django mails not being saved (File backend)
I have configured Django to use a file backend for email sending on my local machine. This seemed to work fine earlier on, and all mails were recorded in the directory I had specified in my settings.py file:

```<code>EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/code/mails/'
</code>```

However, this suddenly stopped working. I have checked the permissions of the folder, and this seems to be fine. There is no error that I can see. I'm using docker, and when I start the Python server I have the logs shown in my terminal. Normally when there is an error I see it there. But nothing appears. To test things, I have renamed the folder and tried sending a mail. This time, no error appears either. In production, where my settings.py are different but all else is the same, the emails are sent out just fine. So the code seems to be working, but the local filebased backend seems to be a problem.

Anybody any idea?

I have configured these log settings:

```<code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/code/logs/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}
</code>```

The logs seem to work fine and provide detailed logging; but none of it related to the e-mail error.

答:
I spent some time on this myself and after some frustration, I just swapped the two variables, and it worked.</p>

```<code>EMAIL_FILE_PATH = '/code/mails/'
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
</code>```

Body:
I have configured Django to use a file backend for email sending on my local machine. This seemed to work fine earlier on, and all mails were recorded in the directory I had specified in my settings.py file:

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/code/mails/'

However, this suddenly stopped working. I have checked the permissions of the folder, and this seems to be fine. There is no error that I can see. I'm using docker, and when I start the Python server I have the logs shown in my terminal. Normally when there is an error I see it there. But nothing appears. To test things, I have renamed the folder and tried sending a mail. This time, no error appears either. In production, where my settings.py are different but all else is the same, the emails are sent out just fine. So the code seems to be working, but the local filebased backend seems to be a problem.

Anybody any idea?

I have configured these log settings:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/code/logs/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

The logs seem to work fine and provide detailed logging; but none of it related to the e-mail error.

Body:
I spent some time on this myself and after some frustration, I just swapped the two variables, and it worked.

EMAIL_FILE_PATH = '/code/mails/'
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'


问:
Best way to search data in xml files?
In our new project we have to provide a search functionality to retrieve data from hundreds of xml files. I have a brief of our current plan below, I would like to know your suggestions/improvements on this.

These xml files contain personal information, and the search is based on 10 elements in it for example last name, first name, email etc. Our current plan is to create an master XmlDocument with all the searchable data and a key to the actual file. So that when the user searches the data we first look at master file and get the the results. We will also cache the actual xml files from the recent searches so simillar searches later can be handled quickly.

Our application is a .net 2.0 web application.

答: Why dont you store the searchable data in a database table with key to the actual file? So your search would be on database table rather than xml file. I suppose this would be faster because you may index the table for faster searching.</p>

OwnerDisplayName: gk

ContentLicense: CC BY-SA 2.5

Title: Best way to search data in xml files?

OwnerDisplayName: Nahom Tijnam


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答:
I started using HAML pretty early on and I really like it.  Though like all tools, it has its uses. Some quick points

Don't forget you can have both HAML and ERB templates in the same project... just change the extension to change which is used.  You don't have to commit to one or the other.

HAML doesn't change the ruby/rails side of the templates... only the representation of the HTML, so it should not hamper your learning.

HAML is slower than ERB.  While in most situations this is insignificant (not noticeable to the end user) it is something to keep in mind if you have a partial that is going to be rendered over and over again.

Just some thoughts.


问:
addEventListener for multiple pages and buttons
I'm way too used to working in react and components so doing this all in vanilla JS makes my brain go blank some times.

I have a website with multiple pages/URLs. Certain pages have unique styles that users interact with.

I have a single file script.js. I get elements with document.getElementsByClassName, I then use an addEventListener for 'clicks' and what not. When I only worked on one page I never noticed that when I started building out the second page the script breaks because it can't find the element (which was on the previous page).

This does make sense but how do you work around this? My entire script is encapulslated with window.onload.

For example,

Page1.html

```<code><button class="first"> Click me </button>
</code>```

Page2.html

```<code><button class="second"> Click me </div>
</code>```

Scrip.js

```<code>var buttonOne = document.getElementsByClassName("first")[0];
var buttonTwo = document.getElementsByClassName("second")[0];

buttonOne.addEventListener('click',function(){
        firstFun();
})

buttonTwo.addEventListener('click',function(){
        secondFun();
})

function firstFun () { .. }
function secondFun () { .. }
</code>```

In which this script wouldn't work because it would break trying to find the element and adding the event listener.

答:
Another solution can be to add onclick event to the buttons, like below

```<code><button onclick="myFunction()">Click me</button>.
</code>```

And define the function in js fie.

Body:
I'm way too used to working in react and components so doing this all in vanilla JS makes my brain go blank some times.

I have a website with multiple pages/URLs. Certain pages have unique styles that users interact with.

I have a single file script.js. I get elements with document.getElementsByClassName, I then use an addEventListener for 'clicks' and what not. When I only worked on one page I never noticed that when I started building out the second page the script breaks because it can't find the element (which was on the previous page).

This does make sense but how do you work around this? My entire script is encapulslated with window.onload.

For example,

Page1.html

<button class="first"> Click me </button>

Page2.html

<button class="second"> Click me

Scrip.js

var buttonOne = document.getElementsByClassName("first")[0];
var buttonTwo = document.getElementsByClassName("second")[0];

buttonOne.addEventListener('click',function(){
        firstFun();
})

buttonTwo.addEventListener('click',function(){
        secondFun();
})

function firstFun () { .. }
function secondFun () { .. }

In which this script wouldn't work because it would break trying to find the element and adding the event listener.

Body:
Another solution can be to add onclick event to the buttons, like below

<button onclick="myFunction()">Click me</button>.

And define the function in js fie.


问:
The parameter is missing a value
I am creating a report based in SSRS and I am getting an error related to the parameter missing a value.

I tried searching for a few links online but none of them have anything related to the issue I am facing.

The issue I am facing is that I have a few datasets with the query  defined inside the report itself. These queries are not producing the values as intended.

Below is relevant code that could be useful in understand the problem.

```<code>      <Query>
        <DataSourceName>SBR_DATA</DataSourceName>
.
.
.
          <QueryParameter Name="@PU_CS">
            <Value>=Parameters!PU_CS.Value</Value>
          </QueryParameter>
.
.
.
          <CommandText>
                SELECT XYZ FROM ABC
                WHERE Value in (@PU_CS)
          </CommandText>
</DataSet>
<DataSet Name="Pick_Up_List">
      <Query>
        <DataSourceName>SBR_DATA</DataSourceName>
        <CommandText>SELECT
                    PQR AS PickUpList
                    FROM RST
        </CommandText>
        <rd:UseGenericDesigner>true</rd:UseGenericDesigner>
      </Query>
      <Fields>
        <Field Name="PickUpList">
          <DataField>PickUpList</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
      </Fields>
</DataSet>
.
.
.
<ReportParameter Name="PU_CS">
      <DataType>String</DataType>
      <DefaultValue>
        <DataSetReference>
          <DataSetName>Pick_Up_List</DataSetName>
          <ValueField>PickUpList</ValueField>
        </DataSetReference>
      </DefaultValue>
      <Prompt>Pick Up City, State:</Prompt>
      <ValidValues>
        <DataSetReference>
          <DataSetName>Pick_Up_List</DataSetName>
          <ValueField>PickUpList</ValueField>
          <LabelField>PickUpList</LabelField>
        </DataSetReference>
      </ValidValues>
      <MultiValue>true</MultiValue>
</ReportParameter>
</code>```

I expect that the result should be displayed as I am specifying each and every result and not missing anything.

答:
Few things you may need to check:

Do you put parameter @PU_CS at the first position in all parameters? Parameter with DB need to be placed as the first parameter to run the rerpot.

And try to set a default value for the parameter to see the result.

Title: The parameter is missing a value

Body:
I am creating a report based in SSRS and I am getting an error related to the parameter missing a value.

I tried searching for a few links online but none of them have anything related to the issue I am facing.

The issue I am facing is that I have a few datasets with the query  defined inside the report itself. These queries are not producing the values as intended.

Below is relevant code that could be useful in understand the problem.

      <Query>
        <DataSourceName>SBR_DATA</DataSourceName>
.
.
.
          <QueryParameter Name="@PU_CS">
            <Value>=Parameters!PU_CS.Value</Value>
          </QueryParameter>
.
.
.
          <CommandText>
                SELECT XYZ FROM ABC
                WHERE Value in (@PU_CS)
          </CommandText>
</DataSet>
<DataSet Name="Pick_Up_List">
      <Query>
        <DataSourceName>SBR_DATA</DataSourceName>
        <CommandText>SELECT
                    PQR AS PickUpList
                    FROM RST
        </CommandText>
        <rd:UseGenericDesigner>true</rd:UseGenericDesigner>
      </Query>
      <Fields>
        <Field Name="PickUpList">
          <DataField>PickUpList</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
      </Fields>
</DataSet>
.
.
.
<ReportParameter Name="PU_CS">
      <DataType>String</DataType>
      <DefaultValue>
        <DataSetReference>
          <DataSetName>Pick_Up_List</DataSetName>
          <ValueField>PickUpList</ValueField>
        </DataSetReference>
      </DefaultValue>
      <Prompt>Pick Up City, State:</Prompt>
      <ValidValues>
        <DataSetReference>
          <DataSetName>Pick_Up_List</DataSetName>
          <ValueField>PickUpList</ValueField>
          <LabelField>PickUpList</LabelField>
        </DataSetReference>
      </ValidValues>
      <MultiValue>true</MultiValue>
</ReportParameter>

I expect that the result should be displayed as I am specifying each and every result and not missing anything.


问:
Create BIGQUERY Table via GAS
I'm working on a Google App Script on a Google Sheet to load my sheet to BigQuery into a new table that I will create.

When I try to create a table, I get a parse error.

Here is my code:

```<code>function CreateTable() {

  var projectId = 'project-id-';

  var datasetId = 'testing';

  // Here is where I try to create the bqTable
  var tableId = 'test2';
  var table = {
    tableReference: {
      projectId: projectId,
      datasetId: datasetId,
      tableId: tableId,
    },
    schema: {
      fields: [
        {name: 'Id', type: 'STRING'},

      ],
    },
  };
  table = BigQuery.Tables.insert(tableId, projectId, datasetId);

}
</code>```

How do I solve the problem?

答:
I've looked at your code and found the bug.

Change this:

```<code>BigQuery.Tables.insert(tableId, projectId, datasetId);
</code>```

To this:

```<code>BigQuery.Tables.insert(table, projectId, datasetId);
</code>```

Title: Create BIGQUERY Table via GAS

Body:
I'm working on a Google App Script on a Google Sheet to load my sheet to BigQuery into a new table that I will create.

When I try to create a table, I get a parse error.

Here is my code:

function CreateTable() {

  var projectId = 'project-id-';

  var datasetId = 'testing';

  // Here is where I try to create the bqTable
  var tableId = 'test2';
  var table = {
    tableReference: {
      projectId: projectId,
      datasetId: datasetId,
      tableId: tableId,
    },
    schema: {
      fields: [
        {name: 'Id', type: 'STRING'},

      ],
    },
  };
  table = BigQuery.Tables.insert(tableId, projectId, datasetId);

}

How do I solve the problem?

Body:
I've looked at your code and found the bug.

Change this:

BigQuery.Tables.insert(tableId, projectId, datasetId);

To this:

BigQuery.Tables.insert(table, projectId, datasetId);


问:
Input Simulator Virtual Key Code RETURN acts as spacebar
I am using the InputSimulator package with c# and im trying to simulate the entry of the 'enter' key. When i do this instead of the enter key being pressed the spacebar is.

Alternating the keycodes.

                            .KeyPress(VirtualKeyCode.RETURN)
```

I expect it to press the enter key however it presses the spacebar.

答: Update: The program i was trying to submit the keys into was blocking the enter key. My solution of fixing this was to deselect the input and then reselect it and then use the enter key.</p>

Body:
I am using the InputSimulator package with c# and im trying to simulate the entry of the 'enter' key. When i do this instead of the enter key being pressed the spacebar is.

Alternating the keycodes.

                            .KeyPress(VirtualKeyCode.RETURN)

I expect it to press the enter key however it presses the spacebar.


问:
Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)
I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.

```<code> var http = require('http');
 var fs = require('fs');
 var path = require('path');

 http.createServer(function (request, response) {

    console.log('request starting for ');
    console.log(request);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    console.log(filePath);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

 }).listen(5000);

 console.log('Server running at http://127.0.0.1:5000/');
</code>```

Any idea ?

答:
In my case I had two issues...

1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"

2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

Body:
I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.

 var http = require('http');
 var fs = require('fs');
 var path = require('path');

 http.createServer(function (request, response) {

    console.log('request starting for ');
    console.log(request);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    console.log(filePath);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

 }).listen(5000);

 console.log('Server running at http://127.0.0.1:5000/');

Any idea ?


问:
Why is Vue v-bind:class not updating?
Updating data property does not update dynamic class.

Have tried setting data property through computed value.

```<code><div class="customize-box" v-on:click="select" v-bind:class="{active: customizeBoxVisible}"></div>
<script>
    export default {
        data() {
            return {
                isSelected: false
            }
        },
        computed: {
            customizeBoxVisible: {
                get() {
                    return this.isSelected;
                },
                set(value) {
                    this.isSelected = value;
                }
            }
       },
       methods: {
            select() {
                this.isSelected = true;
            }
        }
   }
</script>
</code>```

Inspecting component data in chrome dev tools shows that customizeBoxVisible is set to true. After toggling isSelected in dev tools, class gets applied.

答:
You are calling select method but never changing isSelected data value. The correct way to toggle isSelected value is.</p>

```<code>methods: {
    select() {
        this.isSelected = !this.isSelected;
    }
}
</code>```

Title: Why is Vue v-bind:class not updating?

Body:
Updating data property does not update dynamic class.

Have tried setting data property through computed value.

Inspecting component data in chrome dev tools shows that customizeBoxVisible is set to true. After toggling isSelected in dev tools, class gets applied.

Body:
You are calling select method but never changing isSelected data value. The correct way to toggle isSelected value is.

methods: {
    select() {
        this.isSelected = !this.isSelected;
    }
}


问:
Fix header in scrolling material-ui popover
material-ui can have a fixed header and footer in a Dialog with long, scrolling content.

I wish to achieve this same effect, in a popover.

Taking the example:

```<code><Popover>
  <Header>Fixed header</Header>
  <Content>long long long text</Content>
  <Footer>Submit button</Footer>
</Popover>
</code>```

I want the scrollbar to appear in Content, while Header and Footer stay fixed in their popover.

I can achieve the desired result by setting a simple style={{ height: 250 }} on Content, but then I'd lose the dynamic sizing of the popover, which adjust its height according to the required size by its children but staying within the limits of the screen.

Is this even possible by using the library itself? If not, is anyone aware of any workarounds?

答:
You could achieve this by setting the max-height of the content in a dynamic way, you have to use max-height: calc( 100vh - {headerHeigh - footerHeight}) you have to do {headerHeigh - footerHeight} manually, then your content should now how to handle the overflow with overflow: auto;, a working example:

body {
  font-family: sans-serif;
  box-sizing: border-box;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.grid .popover {
  border: 1px solid black;
}

.grid .popover .content {
  max-height: calc(100vh - 70px);
  overflow: auto;
}

header {
  background: red;
  height: 40px;
}

footer {
  background: green;
  height: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="popover">
   <header>header</header>
   <div class="content">
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
   </div>
   <footer>footer</footer>
  </div>
  <div class="popover">
   <header>header</header>
   <div class="content">
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
   </div>
   <footer>footer</footer>
  </div>
 </div></code>```

Body:
material-ui can have a fixed header and footer in a Dialog with long, scrolling content.

I wish to achieve this same effect, in a popover.

Taking the example:

<Popover>
  Fixed header
  <Content>long long long text</Content>
  Submit button
</Popover>

I want the scrollbar to appear in Content, while Header and Footer stay fixed in their popover.

I can achieve the desired result by setting a simple style={{ height: 250 }} on Content, but then I'd lose the dynamic sizing of the popover, which adjust its height according to the required size by its children but staying within the limits of the screen.

Is this even possible by using the library itself? If not, is anyone aware of any workarounds?

Body:
You could achieve this by setting the max-height of the content in a dynamic way, you have to use max-height: calc( 100vh - {headerHeigh - footerHeight}) you have to do {headerHeigh - footerHeight} manually, then your content should now how to handle the overflow with overflow: auto;, a working example:

body {
  font-family: sans-serif;
  box-sizing: border-box;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.grid .popover {
  border: 1px solid black;
}

.grid .popover .content {
  max-height: calc(100vh - 70px);
  overflow: auto;
}

header {
  background: red;
  height: 40px;
}

footer {
  background: green;
  height: 30px;
}

<div class="grid">
  <div class="popover">
   <header>header</header>
   <div class="content">
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
   </div>
   <footer>footer</footer>
  </div>
  <div class="popover">
   <header>header</header>
   <div class="content">
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
    Lollipop pudding jelly bonbon caramels. Danish pastry chocolate cake. Macaroon oat cake marzipan powder bear claw
    sweet cake jujubes. Bear claw candy croissant oat cake cookie cotton candy fruitcake halvah. Carrot cake toffee
    powder topping. Cotton candy pudding chocolate bar croissant halvah danish jelly-o. Dessert cupcake marzipan
    pastry. Candy canes wafer donut. Dragée tart chocolate bar. Chupa chups oat cake candy sweet roll halvah biscuit
    brownie pastry lemon drops. Caramels danish soufflé fruitcake tootsie roll apple pie. Lemon drops soufflé tootsie
    roll cotton candy dessert liquorice.
   </div>
   <footer>footer</footer>
  </div>
 </div>


问:
How do you set Entry parameter 'show' in Tkinter to always show fixed number of asterisks in Entry field?
I set the 'show' parameter to '*' so that Entry field doesn't reveal what was typed in. The issue I am having is, it hints how long the word actually is. So, for example, if I type in word 'blue', it will show as '****' which hints it's a 4 characters long word. Also, the solution code needs to work with the random function filling in the above mentioned field

How do I solve this easy way?

EDIT: To put things into a context this is the code of the app I made.

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

def num_guess():
    try:
        int(num_input.get())

    except ValueError:
        Ans = "You must enter a number in your number field!\n"
        result_field.insert(INSERT, Ans)

    if int(num_input.get()) == int(hidden_num):
        Ans = "Congrats you guessed correctly!\n"
        result_field.insert(INSERT, Ans)
        secret_num.delete(0, END)
        secret_num.insert(END, hidden_num)

    elif int(num_input.get()) in range(int(hidden_num) - 2, int(hidden_num) + 3):
        Ans = "You are very close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 5, int(hidden_num) + 6):
        Ans = "You are close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 10, int(hidden_num) + 11):
        Ans = "You are relatively close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 15, int(hidden_num) + 16):
        Ans = "You are far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    else:
        Ans = "You are very far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

def start_new():
    global hidden_num
    result_field.delete('1.0', END)
    secret_num.delete(0, END)
    secret_num.insert(END, random.randint(1,100))
    hidden_num = secret_num.get()
    secret_num.delete(0, END)
    secret_num.insert(END, "***")
    result_field.insert(INSERT, "Now enter your number as a guess!\n")

def hide_num():
    global hidden_num

    try:
        int(secret_num.get())
        hidden_num = secret_num.get()
        secret_num.delete(0, END)
        secret_num.insert(END, "***")
        result_field.insert(INSERT, "Now enter your number as a guess!\n")

    except ValueError:
        Ans = "You must enter a number in secret number field!\n"
        result_field.insert(INSERT, Ans)

hidden_num = 0

window = Tk()
window.title('Guess the Number!')
Label(window, text = "").grid(row=0)
Label(window, text = "Secret number:").grid(row=7, column=1, padx=8)
Label(window, text = "Enter your number:").grid(row=8, column=1, padx=8)
Label(window, text = "").grid(row=10)

#find textbox code!
result_field = Text(window, width=54, height=18)
result_field.grid(row=1, column=1, columnspan=6, rowspan=6, padx=8)
result_field.insert(INSERT, "Click 'Start new' to start a new game!\n")

sb1 = Scrollbar(window)
sb1.grid(row=1, column=7, rowspan=6, sticky = 'NS')
result_field.configure(yscrollcommand=sb1.set)
sb1.configure(command = result_field.yview)

secret_num = Entry(window, width=6)
secret_num.grid(row=7, column=2)

num_input = Entry(window, width=6)
num_input.grid(row=8, column=2)

b1 = Button(window, text = "Take a guess!", command=num_guess, width=12)
b1.grid(row=9, column=1, pady=8, padx=8)
b2 = Button(window, text = "Start new", command=start_new, width=12)
b2.grid(row=9, column=2, pady=8, padx=8)
b3 = Button(window, text = "Quit", command=window.destroy, width=12)
b3.grid(row=9, column=3, pady=8, padx=8)
b4 = Button(window, text = "Hide number", command=hide_num, width=12)
b4.grid(row=7, column=3, sticky = 'W')

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

答:
How do you set Entry parameter 'show' in Tkinter to always show fixed number of asterisks in Entry field? .. How do I solve this easy way?

There is no easy way, and there's no way to use the show attribute to hide the length other than to set show to whitespace.

If you need something more secure you'll have to create your own bindings that accept input from a user and then display something else.

Body:
I set the 'show' parameter to '*' so that Entry field doesn't reveal what was typed in. The issue I am having is, it hints how long the word actually is. So, for example, if I type in word 'blue', it will show as '****' which hints it's a 4 characters long word. Also, the solution code needs to work with the random function filling in the above mentioned field

How do I solve this easy way?

EDIT: To put things into a context this is the code of the app I made.

import random
from tkinter import *

def num_guess():
    try:
        int(num_input.get())

    except ValueError:
        Ans = "You must enter a number in your number field!\n"
        result_field.insert(INSERT, Ans)

    if int(num_input.get()) == int(hidden_num):
        Ans = "Congrats you guessed correctly!\n"
        result_field.insert(INSERT, Ans)
        secret_num.delete(0, END)
        secret_num.insert(END, hidden_num)

    elif int(num_input.get()) in range(int(hidden_num) - 2, int(hidden_num) + 3):
        Ans = "You are very close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 5, int(hidden_num) + 6):
        Ans = "You are close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 10, int(hidden_num) + 11):
        Ans = "You are relatively close to secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    elif int(num_input.get()) in range(int(hidden_num) - 15, int(hidden_num) + 16):
        Ans = "You are far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

    else:
        Ans = "You are very far from secret number!..." + str(num_input.get()) + "\n"
        result_field.insert(INSERT, Ans)

def start_new():
    global hidden_num
    result_field.delete('1.0', END)
    secret_num.delete(0, END)
    secret_num.insert(END, random.randint(1,100))
    hidden_num = secret_num.get()
    secret_num.delete(0, END)
    secret_num.insert(END, "***")
    result_field.insert(INSERT, "Now enter your number as a guess!\n")

def hide_num():
    global hidden_num

    try:
        int(secret_num.get())
        hidden_num = secret_num.get()
        secret_num.delete(0, END)
        secret_num.insert(END, "***")
        result_field.insert(INSERT, "Now enter your number as a guess!\n")

    except ValueError:
        Ans = "You must enter a number in secret number field!\n"
        result_field.insert(INSERT, Ans)

hidden_num = 0

window = Tk()
window.title('Guess the Number!')
Label(window, text = "").grid(row=0)
Label(window, text = "Secret number:").grid(row=7, column=1, padx=8)
Label(window, text = "Enter your number:").grid(row=8, column=1, padx=8)
Label(window, text = "").grid(row=10)

#find textbox code!
result_field = Text(window, width=54, height=18)
result_field.grid(row=1, column=1, columnspan=6, rowspan=6, padx=8)
result_field.insert(INSERT, "Click 'Start new' to start a new game!\n")

sb1 = Scrollbar(window)
sb1.grid(row=1, column=7, rowspan=6, sticky = 'NS')
result_field.configure(yscrollcommand=sb1.set)
sb1.configure(command = result_field.yview)

secret_num = Entry(window, width=6)
secret_num.grid(row=7, column=2)

num_input = Entry(window, width=6)
num_input.grid(row=8, column=2)

b1 = Button(window, text = "Take a guess!", command=num_guess, width=12)
b1.grid(row=9, column=1, pady=8, padx=8)
b2 = Button(window, text = "Start new", command=start_new, width=12)
b2.grid(row=9, column=2, pady=8, padx=8)
b3 = Button(window, text = "Quit", command=window.destroy, width=12)
b3.grid(row=9, column=3, pady=8, padx=8)
b4 = Button(window, text = "Hide number", command=hide_num, width=12)
b4.grid(row=7, column=3, sticky = 'W')

window.mainloop()


问:
How to listen for a WebView finishing loading a URL?
I have a WebView that is loading a page from the Internet. I want to show a ProgressBar until the loading is complete.

How do I listen for the completion of page loading of a WebView?

答:
The renderer will not finish rendering when the OnPageFinshed method is called or the progress reaches 100% so both methods don't guarantee you that the view was completely rendered.

But you can figure out from OnLoadResource method what has been already rendered and what is still rendering. And this method gets called several times.

```<code>        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
           // Log and see all the urls and know exactly what is being rendered and visible. If you wanna know when the entire page is completely rendered, find the last url from log and check it with if clause and implement your logic there.
            if (url.contains("assets/loginpage/img/ui/forms/")) {
                // loginpage is rendered and visible now.
               // your logic here.

            }
        }
</code>```

Body:
The renderer will not finish rendering when the OnPageFinshed method is called or the progress reaches 100% so both methods don't guarantee you that the view was completely rendered.

But you can figure out from OnLoadResource method what has been already rendered and what is still rendering. And this method gets called several times.

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
           // Log and see all the urls and know exactly what is being rendered and visible. If you wanna know when the entire page is completely rendered, find the last url from log and check it with if clause and implement your logic there.
            if (url.contains("assets/loginpage/img/ui/forms/")) {
                // loginpage is rendered and visible now.
               // your logic here.

            }
        }


问:
Why is typescript compiler changing my tsconfig.json file on server start up?
I'm trying to move my react app to a react-typescript app. firstly, this seems really tricky which is disappointing

the issue I'm having is that I get typescript errors in my console. I'm trying to fix them by changing my tsconfig.json file

but whenever I do and restart the server, I get a message in the console saying: the following changes are being made to your tsconfig.json file
and then it lists the changes which are basically "undos" of the stuff I've just added or changed. why would it do this?

it is a create-react-app project and I followed this to migrate to typescript: https://facebook.github.io/create-react-app/docs/adding-typescript

答: You can manually add a tsconfig.path.json file with all the compilerOptions included and add "extends": "./tsconfig.path.json" to your tsconfig file.</p>


问:
Msgbox not closing when WSH.Popup waits for certain time
I have an Excel file that opens automatically with Windows Scheduler. Also I have an Auto_Open sub to run a macro immediately. To avoid that every time it opens it starts running without a chance to modify it, I set up a msgbox that let me choose if the macro runs or not. However, I want Excel to automatically choose "Yes" after 10 seconds have passed, and I'm not able to get it. This is my code:

I have tried to place the seconds directly without a variable, I have also tried Case -1 alone, yet nothing works.

```<code>Sub Auto_Open()

Set WSH = CreateObject("WScript.Shell")
'cTime = 10
BtnCode = WSH.Popup("¿Desea generar la consulta de vacaciones?", cTime, "Consulta", vbYesNo)

Select Case BtnCode
    Case vbYes
    Call consulta

    Case vbNo

    Case 1, -1
    Call consulta

    End Select

End Sub
</code>```

答:
It might be easier to use a userform in combination with a module to run this. The UserForm would need to replace whatever you're doing with Msgbox. The code you'll need would look something like this:

USERFORM clode

```<code>Private Sub CommandButton2_Click()

'Run code for yes

'then
Unload Me

End Sub

Private Sub CommandButton1_Click()
'run code for "no".

'then
Unload Me

End Sub

Private Sub UserForm_Activate()

Application.OnTime Now + TimeValue("00:00:10"), "KeepItGoing"

End Sub
</code>```

Then you can have it interact with an external module:

```<code>Sub launchSOMETHING()
'Run this first

UserForm1.Show

End Sub

Sub KeepItGoing()

If UserForm1.Visible = True Then
    MsgBox "BOOOOMO"
    Unload UserForm1

End If

End Sub
</code>```

You can see an example in this file here.

UPDATED: It appears that all macros will pause while Msgbox is open. In the below two procedures, you'll note that the second one won't be triggered until after the box is closed, even though it was supposed to run in 5 seconds.

```<code>Sub TestWhatMsgBoxDoes()

Application.OnTime Now + TimeValue("00:00:5"), "someOtherMacro"
MsgBox "Everything is on hold?"

End Sub

Sub someOtherMacro()
Application.StatusBar = "The Second Macro has run at" & Now()

End Sub
</code>```

Body:
I have an Excel file that opens automatically with Windows Scheduler. Also I have an Auto_Open sub to run a macro immediately. To avoid that every time it opens it starts running without a chance to modify it, I set up a msgbox that let me choose if the macro runs or not. However, I want Excel to automatically choose "Yes" after 10 seconds have passed, and I'm not able to get it. This is my code:

I have tried to place the seconds directly without a variable, I have also tried Case -1 alone, yet nothing works.

Sub Auto_Open()

Set WSH = CreateObject("WScript.Shell")
'cTime = 10
BtnCode = WSH.Popup("¿Desea generar la consulta de vacaciones?", cTime, "Consulta", vbYesNo)

Select Case BtnCode
    Case vbYes
    Call consulta

    Case vbNo

    Case 1, -1
    Call consulta

    End Select

End Sub

Body:
It might be easier to use a userform in combination with a module to run this. The UserForm would need to replace whatever you're doing with Msgbox. The code you'll need would look something like this:

USERFORM clode

Private Sub CommandButton2_Click()

'Run code for yes

'then
Unload Me

End Sub

Private Sub CommandButton1_Click()
'run code for "no".

'then
Unload Me

End Sub

Private Sub UserForm_Activate()

Application.OnTime Now + TimeValue("00:00:10"), "KeepItGoing"

End Sub

Then you can have it interact with an external module:

Sub launchSOMETHING()
'Run this first

UserForm1.Show

End Sub

Sub KeepItGoing()

If UserForm1.Visible = True Then
    MsgBox "BOOOOMO"
    Unload UserForm1

End If

End Sub

You can see an example in this file here.

UPDATED: It appears that all macros will pause while Msgbox is open. In the below two procedures, you'll note that the second one won't be triggered until after the box is closed, even though it was supposed to run in 5 seconds.

Sub TestWhatMsgBoxDoes()

Application.OnTime Now + TimeValue("00:00:5"), "someOtherMacro"
MsgBox "Everything is on hold?"

End Sub

Sub someOtherMacro()
Application.StatusBar = "The Second Macro has run at" & Now()

End Sub


问:
TFS Build keep throwing 'Unable to perform the get operation because the file already exists locally' error
I am currently working on an ASP.NET based web application which is version controlled via TFS. A TFS Build server is configured so it is running the build process on every checkin. My problem is that whenever I modify the Web.Config file and check in the modifications, the build process keeps throwing an error when getting the source which says 'Unable to perform the get operation because the file already exists locally'. I tried to remove the Web.Config from TFS and checked in the modifications, but the error was still there, saying 'Unable to perform the delete operation because the file already exists locally'. But when I manually delete the file from the build server's filesystem, the problem is gone. What do you think the problem is?
I have not found anything relevant to this on google, so I would be really happy if you could help me.
Thanks a lot!</p>

答:
I came across this thread after getting the error "Warning s - Unable to get because a directory already exists" in a build definition in TFS 2018. For me, I eventually figured out that the issue was because I specified the full solution path instead of just the solution directory in the server path of the build definition. Removing the solution name from the path (so it was just a folder reference) solved the issue. Hopes that helps others coming across this thread.

TFS Build Definition Image