问:
Is there a better alternative to using sleep in go routine
I want to write a worker which does a job say every 1 hour. There has been no crons in our system as of now so don't want to add a cron. Request for suggestion in the followin implementation:

```<code>func init(){
     go startWorker()
}

func startWorker(){
     doJob()
     time.Sleep(time.Second * 3600)
}
</code>```

Is using a sleep a bad idea in a go routine or are there better alternatives to do such stuff.
The job of doJob() is to fetch from the DB all the failures that have happened in the last hour and do a retry

答:
There are two issues with using time.Sleep in the way you envision, one major and one minor.

You have no way to terminate the goroutine

The goroutine is stuck in an infinite loop, so unless doJob panics, it will never terminate.  You should probably pass it a channel that will be closed when the goroutine needs to terminate:

done := make(chan struct{})
go worker(done)
...
close(done)
...
func worker(done <-chan struct{}){
    for {
        doJob()
        timer := time.NewTimer(time.Hour)
        select {
        case <-timer.C:
            // nothing
        case <-done:
            timer.Stop()
            return
        }
    }
}
```
<p>Or, better yet, using a ticker:</p>
<pre class="lang-golang prettyprint-override"><code>func worker(done <-chan struct{}){
    ticker := time.NewTicker(time.Hour)
    for {
        doJob()
        select {
        case <-ticker.C:
            // nothing
        case <-done:
           ticker.Stop()
           return
        }
    }
}
</code>```

It is good style here to use defer:

func worker(done <-chan struct{}){
    ticker := time.NewTicker(time.Hour)
    defer ticker.Stop()
    for {
        doJob()
        select {
        case <-ticker.C:
            // nothing
        case <-done:
           return
        }
    }
}
```

You're wasting a stack

While a goroutine uses negligible CPU resources, it uses a stack, on the order of a dozen kilobytes or so.  That's probably not a problem for you, but if it is, and if your application has a main loop, then you can insert your ticker and invocation of doWork into the main select statement of the main loop.

Body:
I want to write a worker which does a job say every 1 hour. There has been no crons in our system as of now so don't want to add a cron. Request for suggestion in the followin implementation:

func init(){
     go startWorker()
}

func startWorker(){
     doJob()
     time.Sleep(time.Second * 3600)
}

Is using a sleep a bad idea in a go routine or are there better alternatives to do such stuff.
The job of doJob() is to fetch from the DB all the failures that have happened in the last hour and do a retry

Body:
There are two issues with using time.Sleep in the way you envision, one major and one minor.

You have no way to terminate the goroutine

The goroutine is stuck in an infinite loop, so unless doJob panics, it will never terminate.  You should probably pass it a channel that will be closed when the goroutine needs to terminate:

done := make(chan struct{})
go worker(done)
...
close(done)
...
func worker(done <-chan struct{}){
    for {
        doJob()
        timer := time.NewTimer(time.Hour)
        select {
        case <-timer.C:
            // nothing
        case <-done:
            timer.Stop()
            return
        }
    }
}

Or, better yet, using a ticker:

func worker(done <-chan struct{}){
    ticker := time.NewTicker(time.Hour)
    for {
        doJob()
        select {
        case <-ticker.C:
            // nothing
        case <-done:
           ticker.Stop()
           return
        }
    }
}

It is good style here to use defer:

func worker(done <-chan struct{}){
    ticker := time.NewTicker(time.Hour)
    defer ticker.Stop()
    for {
        doJob()
        select {
        case <-ticker.C:
            // nothing
        case <-done:
           return
        }
    }
}

You're wasting a stack

While a goroutine uses negligible CPU resources, it uses a stack, on the order of a dozen kilobytes or so.  That's probably not a problem for you, but if it is, and if your application has a main loop, then you can insert your ticker and invocation of doWork into the main select statement of the main loop.


来源: stackexchange

问:
Convert object input parameters to give them types so that TypeScript doesn't complain
I'm working on a TypeScript React app. I wanted to find and use a Hook to process keystrokes. I found the following JS component:

```<code>import { useEffect, useState } from "react";

const useKeyPress = (targetKey) => {
  const [keyPressed, setKeyPressed] = useState(false);

  const downHandler = ({ key }) => {
    if (key === targetKey) setKeyPressed(true);
  };

  const upHandler = ({ key }) => {
    if (key === targetKey) setKeyPressed(false);
  };

  useEffect(() => {
    window.addEventListener("keydown", downHandler);
    window.addEventListener("keyup", upHandler);

    return () => {
      window.removeEventListener("keydown", downHandler);
      window.removeEventListener("keyup", upHandler);
    };
  }, []);

  return keyPressed;
};
export default useKeyPress;
</code>```

To get TypeScript to stop harassing me about missing types, I started notating them. The first was easy: I changed const useKeyPress = (targetKey) => { to const useKeyPress = (targetKey:string) => { and that worked fine.

But next, I wanted to annotate const downHandler = ({ key }) => {. When I tried to say   const downHandler = ({ key:string }) => {, TypeScript refused to compile because I'm assuming key:string looks like an object key-value pair. The specific error message was:

'string' is declared but its value is never read.ts(6133)

Binding element 'string' implicitly has an 'any' type.ts(7031)

So now I'm stumped. How do I annotate the TypeScript so it compiles?

Thanks in advance for your help!

答:
Second problem is related to what you are telling TypeScript/JavaScript to do. In this case const downHandler = ({ key:string }) => { is telling TypeScript to destructure an object which has a property named key and you want to store the value of property key into the parameter key, but when you specify '{ key:string }' you are indicating that you are receiving (destructuring) a key/value pair, but with the wrong syntax.

The actual syntax to achieve what you want is specifying an interface, which could be:

Inline interface. In this sample, we are sending an object with multiple properties, one of them key which is of type string.

```<code>const downHandler = ({ key }: { key: string }) => {
    if (key === targetKey) setKeyPressed(true);
};
</code>```

...or...with an explicit interface.

```<code>interface IMyType {
  key: string
}

const downHandler = ({ key }: IMyType) => {
    if (key === targetKey) setKeyPressed(true);
};
</code>```

You can find a good explanation, and samples, about destructuring in this post: https://medium.com/@rileyhilliard/es6-destructuring-in-typescript-4c048a8e9e15

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a TypeScript React app. I wanted to find and use a Hook to process keystrokes. I found the following JS component:

import { useEffect, useState } from "react";

const useKeyPress = (targetKey) => {
  const [keyPressed, setKeyPressed] = useState(false);

  const downHandler = ({ key }) => {
    if (key === targetKey) setKeyPressed(true);
  };

  const upHandler = ({ key }) => {
    if (key === targetKey) setKeyPressed(false);
  };

  useEffect(() => {
    window.addEventListener("keydown", downHandler);
    window.addEventListener("keyup", upHandler);

    return () => {
      window.removeEventListener("keydown", downHandler);
      window.removeEventListener("keyup", upHandler);
    };
  }, []);

  return keyPressed;
};
export default useKeyPress;

To get TypeScript to stop harassing me about missing types, I started notating them. The first was easy: I changed const useKeyPress = (targetKey) => { to const useKeyPress = (targetKey:string) => { and that worked fine.

But next, I wanted to annotate const downHandler = ({ key }) => {. When I tried to say   const downHandler = ({ key:string }) => {, TypeScript refused to compile because I'm assuming key:string looks like an object key-value pair. The specific error message was:

'string' is declared but its value is never read.ts(6133)

Binding element 'string' implicitly has an 'any' type.ts(7031)

So now I'm stumped. How do I annotate the TypeScript so it compiles?

Thanks in advance for your help!

Body:
Second problem is related to what you are telling TypeScript/JavaScript to do. In this case const downHandler = ({ key:string }) => { is telling TypeScript to destructure an object which has a property named key and you want to store the value of property key into the parameter key, but when you specify '{ key:string }' you are indicating that you are receiving (destructuring) a key/value pair, but with the wrong syntax.

The actual syntax to achieve what you want is specifying an interface, which could be:

Inline interface. In this sample, we are sending an object with multiple properties, one of them key which is of type string.

const downHandler = ({ key }: { key: string }) => {
    if (key === targetKey) setKeyPressed(true);
};

...or...with an explicit interface.

interface IMyType {
  key: string
}

const downHandler = ({ key }: IMyType) => {
    if (key === targetKey) setKeyPressed(true);
};

You can find a good explanation, and samples, about destructuring in this post: https://medium.com/@rileyhilliard/es6-destructuring-in-typescript-4c048a8e9e15


问:
Problem embedding a custom framework inside an .app bundle with XCode 4
I've been searching the web (and S.O.) for a while before asking this question. But I'm totally stuck and I don't know how to fix this.

I have to embed a custom framework inside an .app bundle, using XCode 4. I know I have to fix the install path of the framework using the install_name_tool utility. I've done it like this:

```<code>install_name_tool -change /Library/Frameworks/Ogg.framework/Versions/A/Ogg @executable_path/../Frameworks/Ogg.framework/Versions/A/Ogg <input framework>
</code>```

I've verified that the framework was actually processed by looking at the "last modified" timestamp of the file.

Now the problem: the framework gets copied into the app bundle, but when I run the application, it crashes and in the error report it tells that /Library/Frameworks/Ogg.framework/Versions/A/Ogg image could not be found. Please note the wrong name.

I'm sure I'm embedding the right version of the framework (the one modified by install_name_tool).

What can I do? Thank you in advance.

EDIT: I even tried recompiling the library from sources, specifiying a different install path, but the problem persists. I've tried otool -L on the executable of my application, and it lists the Ogg framework with the wrong path (/Library/Frameworks/....). I don't know where it takes it. Please help...

答:
You want to run install_name_tool on the application's binary.

Or you can change the install name of the framework to @executable_path/../<blah blah> before you link the application to it.

ContentLicense: CC BY-SA 3.0

Body:
I've been searching the web (and S.O.) for a while before asking this question. But I'm totally stuck and I don't know how to fix this.

I have to embed a custom framework inside an .app bundle, using XCode 4. I know I have to fix the install path of the framework using the install_name_tool utility. I've done it like this:

install_name_tool -change /Library/Frameworks/Ogg.framework/Versions/A/Ogg @executable_path/../Frameworks/Ogg.framework/Versions/A/Ogg <input framework>

I've verified that the framework was actually processed by looking at the "last modified" timestamp of the file.

Now the problem: the framework gets copied into the app bundle, but when I run the application, it crashes and in the error report it tells that /Library/Frameworks/Ogg.framework/Versions/A/Ogg image could not be found. Please note the wrong name.

I'm sure I'm embedding the right version of the framework (the one modified by install_name_tool).

What can I do? Thank you in advance.

EDIT: I even tried recompiling the library from sources, specifiying a different install path, but the problem persists. I've tried otool -L on the executable of my application, and it lists the Ogg framework with the wrong path (/Library/Frameworks/....). I don't know where it takes it. Please help...


问:
How can the "More videos" overlay on pause be removed from YouTube embed? Edpuzzle and Khan Academy somehow do it
I want to have the "More videos" overlay not show up when an embedded YouTube video is paused.

I've seen other posts like this one or this one, but none have mentioned the fact that somehow Edpuzzle (e.g. https://edpuzzle.com/media/5e96205457b2f23efd7e8903) and Khan Academy are able to prevent the "More videos" (ytp-pause-overlay) from showing.

Is there some exception from YouTube for educational sites?

答:
The rel parameter is what hides the More Videos overlay, but we cannot use the full feature because YouTube only allows certain sites to do so.

example: rel=0 on khan academy hides the overlay but not on your site.

What the docs state:

This is a deprecation announcement for the showinfo and rel parameter. Titles, channel information, and related videos are an important part of YouTube’s core user experience, and these changes help to make the YouTube viewing experience consistent across different platforms.

Now that we know that we cannot hide the More Videos overlay when the user pauses with the official iFrame API. What we can do is use a more "hacky" solution.

Method 1:

Simply hide the top and bottom section of a player by "div cropping". A working demo can be found here. This basically hides the More Videos section but it also hides the controls, which might be undesirable.

This works because the YouTube player always centers a video, even with a really tall player. So all we have to do is make the player really tall and crop out the top and bottom.

To do the cropping we will need to wrap the iFrame with divs, so our HTML may look something like this.

```

Embedding a YouTube player will not work on Stack Overflow so instead of posting all the code here I used CodePen since they allow YouTube embedding.

Method 2:

Another method to hide the more videos overlay is to use rel=0 parameter to videos from channels with no public videos. A limitation to this method is that the videos must be from a channel with all videos unlisted or private.

correction: it seems like this behavior has changed, now embedded videos from channels with no public videos will no longer show the "more videos", "related videos" overlay regardless of the rel parameter in your embedds.

Here's a playlist from my test channel with no public videos with rel=0 parameter

Here's an embed from my test channel with the rel=1 parameter

Body:
The rel parameter is what hides the More Videos overlay, but we cannot use the full feature because YouTube only allows certain sites to do so.

example: rel=0 on khan academy hides the overlay but not on your site.

What the docs state:

This is a deprecation announcement for the showinfo and rel parameter. Titles, channel information, and related videos are an important part of YouTube’s core user experience, and these changes help to make the YouTube viewing experience consistent across different platforms.

Now that we know that we cannot hide the More Videos overlay when the user pauses with the official iFrame API. What we can do is use a more "hacky" solution.

Method 1:

Simply hide the top and bottom section of a player by "div cropping". A working demo can be found here. This basically hides the More Videos section but it also hides the controls, which might be undesirable.

This works because the YouTube player always centers a video, even with a really tall player. So all we have to do is make the player really tall and crop out the top and bottom.

To do the cropping we will need to wrap the iFrame with divs, so our HTML may look something like this.

<div id="player-size" style="">
  <div id="cropping-div" style="">
    <div id="div-to-crop" style="">
      <div id="player-wrapper">
        <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
        <div id="player"></div>
      </div>
    </div>
  </div>
</div>

Embedding a YouTube player will not work on Stack Overflow so instead of posting all the code here I used CodePen since they allow YouTube embedding.

Method 2:

Another method to hide the more videos overlay is to use rel=0 parameter to videos from channels with no public videos. A limitation to this method is that the videos must be from a channel with all videos unlisted or private.

correction: it seems like this behavior has changed, now embedded videos from channels with no public videos will no longer show the "more videos", "related videos" overlay regardless of the rel parameter in your embedds.

Here's a playlist from my test channel with no public videos with rel=0 parameter

Here's an embed from my test channel with the rel=1 parameter


问:
How to display user's inputted text from textarea on the same page?
So here's the idea:
Someone inputs a text on my textarea:

Then upon clicking on the COUNT button, I want the inputted text to display here:

Here's my code:

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Word Counter</title>
  </head>
  <body>
    <div id="input-text-page">
      <h1>Word Counter</h1>
      <form action="">
        <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>
        <br />
      </form>
      <button onclick="countPage()">COUNT</button>
    </div>
    <div id="count-page" style="display: none;">
      <h1>Your Text:</h1>
      <p id=display-user-text></p>
    </div>
  </body>
  <script src="app.js"></script>
</html>
</code>```

JavaScript:

```<code>const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";
};
</code>```

I really don't know how to do this, and I tried googling for the answer. So any help would be appreciated.

答:
you just need to take the text entered in the #inputted-user-text and  you have to put it in the #display-user-text.

const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";

  let textOut = document.getElementById("display-user-text")
  let textIn = document.getElementById("inputted-user-text").value;
  textOut.innerText = textIn;

};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="input-text-page">
  <h1>Word Counter</h1>
  <form action="">
    <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>
    <br />
  </form>
  <button onclick="countPage()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
  <h1>Your Text:</h1>
  <p id=display-user-text></p>
</div></code>```

Body:
So here's the idea:
Someone inputs a text on my textarea:

Then upon clicking on the COUNT button, I want the inputted text to display here:

Here's my code:

HTML:

<!DOCTYPE html>

    <title>Word Counter</title>

Word Counter

      <form action="">
        <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>

      </form>
      <button onclick="countPage()">COUNT</button>

Your Text:

JavaScript:

const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";
};

I really don't know how to do this, and I tried googling for the answer. So any help would be appreciated.

Body:
you just need to take the text entered in the #inputted-user-text and  you have to put it in the #display-user-text.

const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";

  let textOut = document.getElementById("display-user-text")
  let textIn = document.getElementById("inputted-user-text").value;
  textOut.innerText = textIn;

};

<div id="input-text-page">
  <h1>Word Counter</h1>
  <form action="">
    <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>
    <br />
  </form>
  <button onclick="countPage()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
  <h1>Your Text:</h1>
  <p id=display-user-text></p>
</div>


问:
How can i get sub-collections of sub-collections in Firebase in one call
I have a firebase schema that look like this:
posts > posts(documents) > comments > comments(collections) > replies > replies(documents)

const allComments = await firebase
  .collection('posts')
  .doc(params.slug as string)
  .collection('comments')
  .orderBy("date", "desc")
  .get()
```

<p>if i tried to get the reply like this:</p>

<pre class="lang-js prettyprint-override"><code>const allComments = await firebase
  .collection('posts')
  .doc(params.slug as string)
  .collection('comments')
  .doc("some_random_id")
  .collection('reply')
  .get()
</code>```

i will get only the reply, which is not the desired output.
i need to get each reply of each comment in one call.
so the returned object would be every comment, and each comment contains an object of replies.

答:
Firestore queries are "shallow", and only return documents immediately within the collection being queried.  They don't consider any documents from subcollections.  To get documents from subcollections, you would need to make another query for each subcollection.

It might be better to simply put all the comments and replies in a single collection, mark them each with a boolean indicating if it's a reply or not, and use that as a filter if needed on the query.  The size of the collection will not have any impact on performance.

Body:
I have a firebase schema that look like this:
posts > posts(documents) > comments > comments(collections) > replies > replies(documents)

const allComments = await firebase
  .collection('posts')
  .doc(params.slug as string)
  .collection('comments')
  .orderBy("date", "desc")
  .get()

if i tried to get the reply like this:

const allComments = await firebase
  .collection('posts')
  .doc(params.slug as string)
  .collection('comments')
  .doc("some_random_id")
  .collection('reply')
  .get()

i will get only the reply, which is not the desired output.
i need to get each reply of each comment in one call.
so the returned object would be every comment, and each comment contains an object of replies.


问:
How to specify username and password to get sources in TFS2008?
TFS2008 getting sources not working due to user permissions

Hi

My new buildserver is not working, is not getting the sources. By default TFSBuild uses windows account to get the sources.. but as in my case buildserver is in a different domain of TFS is not working. I could add permissions and have it fix.
But is not possible at the moment.

So second best solution should be specifying username/password that TFSBuild is going to use CoreGet task... maybe in InitializeBuild, InitializeWorkspace or BeforeGet tasks.. or maybe as a property.

But I don't know if it is possible. So my question is:

Is possible to specify username and password to get sources in TFS2008? If so, how? Any link where they explain it?

Thanks

答: TFSBuild uses standard Windows authentication techniques to authenticate to Team Foundation Server.  By default, it will authenticate using your domain credentials.  As you note, you could add the appropriate permissions in order to accomplish this, but you can also specify credentials in the Windows Credential Manager: go to Control Panel > User Accounts > Credential Manager and you can add Windows Credentials for your TFS server.</p>


问:
Type requirement in C++ concepts (C++20)
I am learning the newly implemented concepts of C++20 standard using g++ 10.
I am stuck with a simple type requirement. Namely I want to implement a requirement for a template argument T to have T::inner member name.
Here is my code with error. What is wrong with this simple code and how to fix it?

```<code>#include<concepts>

template<typename T>
concept ContainsInner = requires
{
  typename T::inner;
};

template<ContainsInner T>
struct S{};

struct Q
{
  int inner;
};

int main()
{
  S<Q> s;     // instantiate S with Q for template type,
              // which must satisfy the ContainsInner concept.
              // Q indeed contains the inner name but still the compilation fails
}
</code>```

答:
This:

```<code>template<typename T>
concept ContainsInner = requires
{
  typename T::inner;
};
</code>```

is requiring that T has a type named inner. Which gcc tells you in its error:

```<code>source>:6:12: note: the required type 'typename T::inner' is invalid
    6 |   typename T::inner;
      |   ~~~~~~~~~^~~~~~~~~
</code>```

Q doesn't have a type named inner. If what you want is to have a member variable named inner, then you want:

```<code>template<typename T>
concept ContainsInner = requires(T t) {
    t.inner;
};
</code>```

Note that this doesn't even check what type it is, just that it exists. Which isn't very useful. Maybe you want to require that it's an int:

```<code>template<typename T>
concept ContainsInner = requires(T t) {
    { t.inner } -> std::same_as<int&>;
};
</code>```

Body:
I am learning the newly implemented concepts of C++20 standard using g++ 10.
I am stuck with a simple type requirement. Namely I want to implement a requirement for a template argument T to have T::inner member name.
Here is my code with error. What is wrong with this simple code and how to fix it?

#include<concepts>

template<typename T>
concept ContainsInner = requires
{
  typename T::inner;
};

template<ContainsInner T>
struct S{};

struct Q
{
  int inner;
};

int main()
{
  S<Q> s;     // instantiate S with Q for template type,
              // which must satisfy the ContainsInner concept.
              // Q indeed contains the inner name but still the compilation fails
}

Body:
This:

template<typename T>
concept ContainsInner = requires
{
  typename T::inner;
};

is requiring that T has a type named inner. Which gcc tells you in its error:

source>:6:12: note: the required type 'typename T::inner' is invalid
    6 |   typename T::inner;
      |   ~~~~~~~~~^~~~~~~~~

Q doesn't have a type named inner. If what you want is to have a member variable named inner, then you want:

template<typename T>
concept ContainsInner = requires(T t) {
    t.inner;
};

Note that this doesn't even check what type it is, just that it exists. Which isn't very useful. Maybe you want to require that it's an int:

template<typename T>
concept ContainsInner = requires(T t) {
    { t.inner } -> std::same_as<int&>;
};


问:
Connection between DBeaver & MySQL
I use DBeaver to watch an SQL database on MySQL 8+.

Everything is working, but sometimes, opening DBeaver, I have the following error message :

```<code>Public Key Retrieval is not allowed
</code>```

And then, DBeaver can't connect to MySQL.

In order to fix this problem, I have to reconfigure MySQL.

Is there any simplest way to fix this problem ?

答: Ratish Bansal's solution works for me on MacOS Mojave, and after that, I always get a timezone error. The solution for that is to set my local timezone in the connection settings:

Title: Connection between DBeaver & MySQL

Body:
I use DBeaver to watch an SQL database on MySQL 8+.

Everything is working, but sometimes, opening DBeaver, I have the following error message :

Public Key Retrieval is not allowed

And then, DBeaver can't connect to MySQL.

In order to fix this problem, I have to reconfigure MySQL.

Is there any simplest way to fix this problem ?


问:
Finding the center of circles in an image
I'm fairly new to programming and need to write a program that will find the center of 4 discs (circles) that are located in each corner of a square image.

I don't know the exact coordinates of the discs but have a very good approximation of them. How can I go about finding the location of the centers of each of the 4 discs?

答: The window will most likely draw images using the top left corner as X= 0, Y = 0. Circles tend to be drawn from the centre outwards, so the centre of the circle is most likely the (X,Y) coordinates used to draw the given circle. You can probably find a way to request the values for the circles coordinates depending how they're being drawn and what you're using to draw them. There are a number of ways of drawing to screen with python, so It depends how you are doing it. Can you provide a little more details? </p>


问:
See if Dictionary Item is the last one in the dictionary
Given the code ..

```<code>var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});
</code>```

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

```<code>bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;
</code>```

but that did not work...

答:
Dictionary.Last returns a KeyValuePair, and you are comparing that to just the value of a key. You'd instead need to check:

dictionary[item.Key].Equals( dictionary.Last().Value )

Also IAbstract was correct that you'd probably need to use an OrderedDictionary.

Body:
Given the code ..

var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;

but that did not work...


问:
Pycharm - any way to add code completion hints for config or custom nested dict?
I have a YAML config file with lots of nested parameters that I read into my_config.
To make coding easier I am also using Python-box to allow me to use dot notation as in
mock_mode = my_config.default.mock_mode

The code works fine but I would like to have autocompletion hints particularly for the deeply nested parameters.
I was hoping that if I set a breakpoint after my_config is populated and then break there in debug mode that I could write code using my_config and Pycharm would then know and list the parameter tree when I type the first . after myconfig but it does not do so.

I have enabled 'Collect runtime types information for code insight' and am using Kite but neither help.

Are there any tricks to make Pycharm aware of my config structure?

```<code>from box import Box
import yaml

with open('config.yml') as f:
    config_dict = yaml.load(f, Loader=yaml.FullLoader)
    config_box = Box(config_dict)

    # I now want to add more code  - e.g choose gateway from list of config parameters
    gateway = config_box.ip_settings.
    # code completion popup on hitting period shows few things but not keys from config_box
</code>```

答:
add these two plugins to your IDE:

Yaml

Yaml-Config Autocomplete

Body:
I have a YAML config file with lots of nested parameters that I read into my_config.
To make coding easier I am also using Python-box to allow me to use dot notation as in
mock_mode = my_config.default.mock_mode

The code works fine but I would like to have autocompletion hints particularly for the deeply nested parameters.
I was hoping that if I set a breakpoint after my_config is populated and then break there in debug mode that I could write code using my_config and Pycharm would then know and list the parameter tree when I type the first . after myconfig but it does not do so.

I have enabled 'Collect runtime types information for code insight' and am using Kite but neither help.

Are there any tricks to make Pycharm aware of my config structure?

from box import Box
import yaml

with open('config.yml') as f:
    config_dict = yaml.load(f, Loader=yaml.FullLoader)
    config_box = Box(config_dict)

    # I now want to add more code  - e.g choose gateway from list of config parameters
    gateway = config_box.ip_settings.
    # code completion popup on hitting period shows few things but not keys from config_box


问:
Parse path length to <=260 characters correctly. Strange behaviour with 260-character Paths
I'm making a function to parse a file path + name for Windows computers.

Here's my code:

```<code>def parse_out_path(directory, filename, extension):
    """Ensures filenames are valid. Strips disallowed characters and ensures path is not too long for Windows"""

    # Sanitize name to avoid illegal characters.
    filename = sanitize_filename(filename)
    total_len = len(os.path.join(directory, '{}.{}'.format(filename, extension)))
    if total_len > 260:
        # Shave excess characters from filename
        excess = total_len - 260
        filename = filename[:-excess]

    return os.path.join(directory, '{}.{}'.format(filename, extension))
</code>```

This function generates the output file path with the filename and extension. If it is longer than the Windows limit (260 characters), it shaves some of the filename off to be compliant.

For example:

If C:\long\path\here\example-file.txt is 5 characters too long (265 characters), it becomes C:\long\path\here\example.txt (260 characters).

When I then run this with a filename that's too long, for example:

```<code>filename_too_long = '01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'
parsed_path = ScraperUtils.parse_out_path(os.getcwd(), filename_too_long, 'txt')
open(parsed_path, 'w')
</code>```

This does write successfully without any OSErrors. But when I open Windows File Explorer and click Properties, the Location field shows as:

\\?\C:\Users\<rest of path>

If I open the textfile in Notepad++ or WordPad, these programs either crash or fail to open the file.

If I change my code to create 259-character long filenames the strange symbols at the front of the path disappear. But the file still can't be opened in Notepad++.

If I change my code to create 258-character long filenames, everything appears to work as it should.

Can anyone explain why I'm seeing this strange behaviour? Is 260-characters actually the Windows path limit, or is it infact shorter?

答:
From this forum thread:

... Windows Explorer is still unable to open files stored in a folder whose path length exceeds 259 characters ...

The problem is your program allows a filepath to be 260 when the limit is 259 for windows file explorer. Changing 260 to 259 in your code should do the trick. As for other applications like notepad++, the limit might be less than that, I'm not really sure (if I were to guess it's probably 256).

Body:
I'm making a function to parse a file path + name for Windows computers.

Here's my code:

def parse_out_path(directory, filename, extension):
    """Ensures filenames are valid. Strips disallowed characters and ensures path is not too long for Windows"""

    # Sanitize name to avoid illegal characters.
    filename = sanitize_filename(filename)
    total_len = len(os.path.join(directory, '{}.{}'.format(filename, extension)))
    if total_len > 260:
        # Shave excess characters from filename
        excess = total_len - 260
        filename = filename[:-excess]

    return os.path.join(directory, '{}.{}'.format(filename, extension))

This function generates the output file path with the filename and extension. If it is longer than the Windows limit (260 characters), it shaves some of the filename off to be compliant.

For example:

If C:\long\path\here\example-file.txt is 5 characters too long (265 characters), it becomes C:\long\path\here\example.txt (260 characters).

When I then run this with a filename that's too long, for example:

filename_too_long = '01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'
parsed_path = ScraperUtils.parse_out_path(os.getcwd(), filename_too_long, 'txt')
open(parsed_path, 'w')

This does write successfully without any OSErrors. But when I open Windows File Explorer and click Properties, the Location field shows as:

\\?\C:\Users\<rest of path>

If I open the textfile in Notepad++ or WordPad, these programs either crash or fail to open the file.

If I change my code to create 259-character long filenames the strange symbols at the front of the path disappear. But the file still can't be opened in Notepad++.

If I change my code to create 258-character long filenames, everything appears to work as it should.

Can anyone explain why I'm seeing this strange behaviour? Is 260-characters actually the Windows path limit, or is it infact shorter?


问:
let "this" scope on find()
I have this line of code:

```<code>$(this).parent().find('.nameValue').replaceWith('<input type="text" value="' + $(this).text() + '">');
</code>```

Now I want to set the value of the input to the text from ".nameValue". But the "this" selector scopes onto the click event, causing that the inputs value is the value from the button I clicked.

This worked:

```<code>$(this).parent().find('.nameValue').each(function() {

    replaceWith('<input type="text" value="' + $(this).text() + '">');
});
</code>```

But I dont really need the each function. So I hope there is a better approach. I Hope you understand what I mean - Im not a native english speaker.

答:
You can use a function callback:

```<code>$(this).parent().find('.nameValue').replaceWith(function(){
      return '<input type="text" value="' + $(this).text() + '">'
});
</code>```

You can't avoid a function callback to bind this to the current element or assign a variable to the current element on each iteration.  You must have some way to refer to the current element as you iterate on them to retrieve the value you are trying to retrieve.

Title: let "this" scope on find()

Body:
I have this line of code:

$(this).parent().find('.nameValue').replaceWith('<input type="text" value="' + $(this).text() + '">');

Now I want to set the value of the input to the text from ".nameValue". But the "this" selector scopes onto the click event, causing that the inputs value is the value from the button I clicked.

This worked:

$(this).parent().find('.nameValue').each(function() {

    replaceWith('<input type="text" value="' + $(this).text() + '">');
});

But I dont really need the each function. So I hope there is a better approach. I Hope you understand what I mean - Im not a native english speaker.

Body:
You can use a function callback:

$(this).parent().find('.nameValue').replaceWith(function(){
      return '<input type="text" value="' + $(this).text() + '">'
});

You can't avoid a function callback to bind this to the current element or assign a variable to the current element on each iteration.  You must have some way to refer to the current element as you iterate on them to retrieve the value you are trying to retrieve.


问:
Best way to use SQL trigger with conditional count to audit database reports?
I'm looking to implementing a trigger in my SQL server to save report edits as they are being made.

The server operates a report/dictation software package. Basically a "report_text" draft is created by user1, then edited by user2 before being finalized by user2. The drafts of user1 are saved to a table and overwritten with every save in the database, once user1 is finished and user2 makes edits, the data is further overwritten. So, the final draft of user1 is lost once user2 saves their edits.

I am trying to save the "report_text" to a new table once user1 is finished.

A separate table keeps an audit log with a report_id, access_time, and user who has accessed the report. New rows are inserted to the audit table for every access until finalized, so that each report_id in the audit table can have anywhere from 2 to 4 lines (depending on the number of users who have accessed the file before being finalized). The trigger should capture the "report_text" when the number of rows for each report_id in the audit table for each report_id changes from 2 to 3.

```<code>USE SERVER
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER trigger [dbo].[prelim_text_trigger]
on [dbo].[report_to_user]
AFTER INSERT
AS
BEGIN

SET NOCOUNT ON;

INSERT INTO
dbo.report_compare (report_id)

SELECT report_id
FROM inserted
WHERE (SELECT COUNT(report_id)
FROM report_to_user
GROUP BY report_id
HAVING count(report_id) > 2);

END
</code>```

I tried the following code without success. Nothing was inserted into dbo.report_compare and there were issues with the audit table dbo.report_to_user while the trigger was running. I think the trigger failed and transaction were being rolled back.

What am I doing wrong? Should I have made a conditional statement so that if the condition isn't met the transaction proceeds? Does this accurately count the whole table for the number of instances report_id is present, or is it counting just from the temporary table from inserted?

Going forward, if the trigger fails I would like the transactions to continue. If I add XACT_ABORT OFF or COMMIT TRANS to the beginning of the trigger would that work?

Also, should FOR EACH ROW be added to this trigger, just in case multiple reports are saved by the database simultaneously?

UPDATE

I have since revised the code, as below:

```<code>ALTER trigger [dbo].[report_compare_trigger]
on [dbo].[report_test_to_user]
after insert

as
set xact_abort off
begin

set nocount on;

merge report_compare as target
    using (select report_id from inserted) as source (report_id)
    on (target.report_id = source.report_id)
    when not matched then insert (report_id) values (report_id);

if (select accession_id from report_compare where report_compare.report_id = (select report_id from inserted)) is null
    begin
        update report_compare
        set accession_id = id from accession_test
        where report_compare.report_id = (select report_id from inserted) and accession_test.report_id = (select report_id from inserted);
    end

update report_compare
    set report_compare.id_count = id_count + 1
    where report_compare.report_id = (select report_id from inserted);

if (select date_opened from report_compare where report_compare.report_id = (select report_id from inserted)) is null
    begin
        update report_compare
        set date_opened = cre_time from report_test_section
        where report_compare.report_id = (select report_id from inserted) and report_test_section.report_id = (select report_id from inserted);
    end

if (select user_id from inserted) <> 'EmergencyDept'
    begin
        if (select users from report_compare where report_compare.report_id = (select report_id from inserted)) is null
            begin
                update report_compare
                set users = isnull(users, '') + user_id from inserted where report_compare.report_id = (select report_id from inserted)
            end
        else
            begin
update report_compare
        set users = isnull(users, '') + ', ' + user_id from inserted where report_compare.report_id = (select report_id from inserted)
            end
    end

end;

</code>```

答:
Slightly offtopic perhaps but it sounds like you might benefit from temporal tables - available from SQL Server 2016. SQL server also has auditing features so you don't have to completely reinvent the wheel.

I tried the following code without success. Nothing was inserted into
  dbo.report_compare and there were issues with the audit table
  dbo.report_to_user while the trigger was running.

What kind of issues ?

Does that statement actually return a row ?

```<code>SELECT report_id
FROM inserted
WHERE (SELECT COUNT(report_id)
FROM report_to_user
GROUP BY report_id
HAVING count(report_id) > 2);
</code>```

Body:
I'm looking to implementing a trigger in my SQL server to save report edits as they are being made.

The server operates a report/dictation software package. Basically a "report_text" draft is created by user1, then edited by user2 before being finalized by user2. The drafts of user1 are saved to a table and overwritten with every save in the database, once user1 is finished and user2 makes edits, the data is further overwritten. So, the final draft of user1 is lost once user2 saves their edits.

I am trying to save the "report_text" to a new table once user1 is finished.

A separate table keeps an audit log with a report_id, access_time, and user who has accessed the report. New rows are inserted to the audit table for every access until finalized, so that each report_id in the audit table can have anywhere from 2 to 4 lines (depending on the number of users who have accessed the file before being finalized). The trigger should capture the "report_text" when the number of rows for each report_id in the audit table for each report_id changes from 2 to 3.

USE SERVER
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER trigger [dbo].[prelim_text_trigger]
on [dbo].[report_to_user]
AFTER INSERT
AS
BEGIN

SET NOCOUNT ON;

INSERT INTO
dbo.report_compare (report_id)

SELECT report_id
FROM inserted
WHERE (SELECT COUNT(report_id)
FROM report_to_user
GROUP BY report_id
HAVING count(report_id) > 2);

END

I tried the following code without success. Nothing was inserted into dbo.report_compare and there were issues with the audit table dbo.report_to_user while the trigger was running. I think the trigger failed and transaction were being rolled back.

What am I doing wrong? Should I have made a conditional statement so that if the condition isn't met the transaction proceeds? Does this accurately count the whole table for the number of instances report_id is present, or is it counting just from the temporary table from inserted?

Going forward, if the trigger fails I would like the transactions to continue. If I add XACT_ABORT OFF or COMMIT TRANS to the beginning of the trigger would that work?

Also, should FOR EACH ROW be added to this trigger, just in case multiple reports are saved by the database simultaneously?

UPDATE

I have since revised the code, as below:

ALTER trigger [dbo].[report_compare_trigger]
on [dbo].[report_test_to_user]
after insert

as
set xact_abort off
begin

set nocount on;

merge report_compare as target
    using (select report_id from inserted) as source (report_id)
    on (target.report_id = source.report_id)
    when not matched then insert (report_id) values (report_id);

if (select accession_id from report_compare where report_compare.report_id = (select report_id from inserted)) is null
    begin
        update report_compare
        set accession_id = id from accession_test
        where report_compare.report_id = (select report_id from inserted) and accession_test.report_id = (select report_id from inserted);
    end

update report_compare
    set report_compare.id_count = id_count + 1
    where report_compare.report_id = (select report_id from inserted);

if (select date_opened from report_compare where report_compare.report_id = (select report_id from inserted)) is null
    begin
        update report_compare
        set date_opened = cre_time from report_test_section
        where report_compare.report_id = (select report_id from inserted) and report_test_section.report_id = (select report_id from inserted);
    end

if (select user_id from inserted) <> 'EmergencyDept'
    begin
        if (select users from report_compare where report_compare.report_id = (select report_id from inserted)) is null
            begin
                update report_compare
                set users = isnull(users, '') + user_id from inserted where report_compare.report_id = (select report_id from inserted)
            end
        else
            begin
update report_compare
        set users = isnull(users, '') + ', ' + user_id from inserted where report_compare.report_id = (select report_id from inserted)
            end
    end

end;

Body:
Slightly offtopic perhaps but it sounds like you might benefit from temporal tables - available from SQL Server 2016. SQL server also has auditing features so you don't have to completely reinvent the wheel.

I tried the following code without success. Nothing was inserted into
  dbo.report_compare and there were issues with the audit table
  dbo.report_to_user while the trigger was running.

What kind of issues ?

Does that statement actually return a row ?

SELECT report_id
FROM inserted
WHERE (SELECT COUNT(report_id)
FROM report_to_user
GROUP BY report_id
HAVING count(report_id) > 2);


问:
CSS Grid - How can I align my menu items evenly?
So, I noticed that my menu items looked weird because some of the links are closers together than others due to the nav menu item having more letters.

I'm not sure what CSS I could add to ensure that they are all perfectly taking up the same space, while maintaining an even look. I'll include a picture below of what the problem looks like

Here is my code so far and as you can see the grid-template-columns perfectly space them 1fr each, but if you see "Home" is perfectly centered, but "about us" and "contact us" have much less space to work with and ends up making the menu items look like they aren't aligned properly.

```<code> .nav-menu {
display: grid;
grid-template-columns: repeat(4, 1fr);
list-style: none;
text-align: center;

}

.nav-links {
color: white;
text-decoration: none;
transition: color 0.3s ease-out;
}
</code>```

Is there a way to fix this?

答:
You may use justify-content and auto instead 1fr .

example :

ul,
li {
  margin: 0;
  padding: 0;
}

ul {
  border: solid;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
  width: 356.84px;
  margin-bottom:1em;
}

/* Possible Update */

ul+ul {
  grid-template-columns: repeat(4, auto);
  justify-content: space-around;
}

li {
  list-style: none;
  box-shadow: 0 0 0 1px;
}

a {
  background: lightblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>Home</li>
    <li>Service</li>
    <li>About us</li>
    <li>Contact Us</li>
  </ul>
  <ul>
    <li>Home</li>
    <li>Service</li>
    <li>About us</li>
    <li>Contact Us</li>
  </ul>
</nav></code>```

Body:
So, I noticed that my menu items looked weird because some of the links are closers together than others due to the nav menu item having more letters.

I'm not sure what CSS I could add to ensure that they are all perfectly taking up the same space, while maintaining an even look. I'll include a picture below of what the problem looks like

Here is my code so far and as you can see the grid-template-columns perfectly space them 1fr each, but if you see "Home" is perfectly centered, but "about us" and "contact us" have much less space to work with and ends up making the menu items look like they aren't aligned properly.

 .nav-menu {
display: grid;
grid-template-columns: repeat(4, 1fr);
list-style: none;
text-align: center;

}

.nav-links {
color: white;
text-decoration: none;
transition: color 0.3s ease-out;
}

Is there a way to fix this?

Body:
You may use justify-content and auto instead 1fr .

example :

ul,
li {
  margin: 0;
  padding: 0;
}

ul {
  border: solid;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
  width: 356.84px;
  margin-bottom:1em;
}

/* Possible Update */

ul+ul {
  grid-template-columns: repeat(4, auto);
  justify-content: space-around;
}

li {
  list-style: none;
  box-shadow: 0 0 0 1px;
}

a {
  background: lightblue;
}

<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Service</a></li>
    <li><a href="#">About us</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Service</a></li>
    <li><a href="#">About us</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
</nav>


问:
AWS Application Load Balancer redirect all www and non http to https://
I have a rule setup to redirect all traffic from http to https

How can I also redirect http://www to https://? As far as I can tell the {host} variable contains www and I cant remove it.

答:
In fact it's pretty simple

Instead of writing {host} in your rule just put the name of your website.

So, for example, it will look like this :
https://example.com:443/#{path}?#{query}


问:
foreignkey django
how to choice multiple instances of a foreignkey for example

```<code>class Mobile(models.Model):
    mobile = models.CharField(max_length=20,unique=True)
    quantity = models.IntegerField()
    imei = models.ForeignKey(Imei,on_delete=models.CASCADE)

class Imei(models.Model):
    imei = models.CharField(max_length=13,unique=True)
</code>```

each mobile have different Imei in Mobile if mobile =samsung A51 and quantity = 10 then we have 10 unique  imei

i want to know how to let the user the select 10 imei's (with barcode reader) in the same form ?

i appreciate your helps

答:
I think what you need here is ManyToMany relation. Your Mobile model will look like.

```<code>class Mobile(models.Model):
    mobile = models.CharField()
    quantity = models.IntegerField(
    imei = models.ManyToManyField(Imei)
</code>```

EDITED: Since there are unique imei for each Mobile, you have 2 options to achieve this

Either implement the unique validation at the time of adding an object to the ManyToManyField. (I think this will simplify your relationships)

If you really want to have this logic in db, create a middle table to save the relationship. You have your Mobile table and Imei table. Create another table to store the relationship of both, let's say MobielImei with following fields

```<code>class MobileImei(models.Model):
    mobile = models.ForeignKey(Mobile)
    imei = models.ForeignKey(Imei)

    class Meta:
        unique_together = ("mobile", "imei")
</code>```

This unique_together will ensure, that for every mobile there's a unique imei and single imei is also associated to a unique mobile.

Title: foreignkey django

Body:
how to choice multiple instances of a foreignkey for example

class Mobile(models.Model):
    mobile = models.CharField(max_length=20,unique=True)
    quantity = models.IntegerField()
    imei = models.ForeignKey(Imei,on_delete=models.CASCADE)

class Imei(models.Model):
    imei = models.CharField(max_length=13,unique=True)

each mobile have different Imei in Mobile if mobile =samsung A51 and quantity = 10 then we have 10 unique  imei

i want to know how to let the user the select 10 imei's (with barcode reader) in the same form ?

i appreciate your helps

Body:
I think what you need here is ManyToMany relation. Your Mobile model will look like.

class Mobile(models.Model):
    mobile = models.CharField()
    quantity = models.IntegerField(
    imei = models.ManyToManyField(Imei)

EDITED: Since there are unique imei for each Mobile, you have 2 options to achieve this

Either implement the unique validation at the time of adding an object to the ManyToManyField. (I think this will simplify your relationships)

If you really want to have this logic in db, create a middle table to save the relationship. You have your Mobile table and Imei table. Create another table to store the relationship of both, let's say MobielImei with following fields

class MobileImei(models.Model):
    mobile = models.ForeignKey(Mobile)
    imei = models.ForeignKey(Imei)

    class Meta:
        unique_together = ("mobile", "imei")

This unique_together will ensure, that for every mobile there's a unique imei and single imei is also associated to a unique mobile.


问:
C# - Create instance of all sub classes of a generic base class via Reflection
I want to create instances of all classes which are sub classes of a generic base class. I have searched for some time now. Didn't find anything.

```<code>public class BaseClass<T> { }
public class CustomSubClass: BaseClass<int> { }
</code>```

I have problems with the generic type. Anyone who can help me?

答:
having the same question, I end up here.
But also looking this answer too.

So I end up with this draft of code merging both part :

```<code>// Get all derivative class of BaseClass<T>
    var allSubTypes = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(a=>a.GetTypes())
        .Where(x => x.BaseType != null
                             && !x.IsAbstract
                             && (x.GetConstructor(Type.EmptyTypes) != null)
                             && x.BaseType.IsGenericType
                             && x.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>));

    // and instantiate them
    foreach (var type in allSubTypes)
    {
        object instance = Activator.CreateInstance(type);
    }
</code>```

Body:
I want to create instances of all classes which are sub classes of a generic base class. I have searched for some time now. Didn't find anything.

public class BaseClass<T> { }
public class CustomSubClass: BaseClass<int> { }

I have problems with the generic type. Anyone who can help me?

Body:
having the same question, I end up here.
But also looking this answer too.

So I end up with this draft of code merging both part :

// Get all derivative class of BaseClass<T>
    var allSubTypes = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(a=>a.GetTypes())
        .Where(x => x.BaseType != null
                             && !x.IsAbstract
                             && (x.GetConstructor(Type.EmptyTypes) != null)
                             && x.BaseType.IsGenericType
                             && x.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>));

    // and instantiate them
    foreach (var type in allSubTypes)
    {
        object instance = Activator.CreateInstance(type);
    }


答:
But I dont really need the each function

You do.

The value of this is determined on a per-function basis, so you need a separate function to be applied to each element that you find.

Title: let "this" scope on find()


问:
how to close Python selenium webdriver window
I have a python script that scraps data off from a website on an hourly basis. It is stored on the server at the moment and is working well as I am using task scheduler to schedule it to execute the script on an hourly basis.

I am using this code

```<code>driver.quit()
</code>```

to quit the browser window

My problem to this that whenever I am not logging in to the server, it will start stacking up the webdriver window as somehow the driver.quit() function does not work when I am logging into the server. every morning when I came to work, I have tons of window to close from the server.

I tried to quit, close, dispose, but it doesn't help. What else I can try?

答:
Could'nt you scrape in headless mode? (example for chrome)</p>

```<code>chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.headless = True
...
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.create_options()
</code>```

Body:
I have a python script that scraps data off from a website on an hourly basis. It is stored on the server at the moment and is working well as I am using task scheduler to schedule it to execute the script on an hourly basis.

I am using this code

driver.quit()

to quit the browser window

My problem to this that whenever I am not logging in to the server, it will start stacking up the webdriver window as somehow the driver.quit() function does not work when I am logging into the server. every morning when I came to work, I have tons of window to close from the server.

I tried to quit, close, dispose, but it doesn't help. What else I can try?

Body:
Could'nt you scrape in headless mode? (example for chrome)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.headless = True
...
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.create_options()


问:
android: how do I format number as phone with parentheses
I have a number that I need to format as a telephone number. If I do

```<code> PhoneNumberUtils.formatNumber(numStr);
</code>```

Then I get

```<code>888-555-1234
</code>```

But what I need to get is

```<code>(888) 555-1234
</code>```

How do I get the second one? Is there a standard android way?

答:
Working solution in 2020:</p>

```<code>TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();

phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));
</code>```

Body:
I have a number that I need to format as a telephone number. If I do

 PhoneNumberUtils.formatNumber(numStr);

Then I get

888-555-1234

But what I need to get is

(888) 555-1234

How do I get the second one? Is there a standard android way?

Body:
Working solution in 2020:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();

phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));


问:
Control loaded swish animation in AS 3.0
I'm developing an AS 3.0 wrapper to add some extra stuff that has to load some old and plain frame to frame SwishMax 3 animations and then be able to stop them, play them, and so...

Here is my code:

```<code>package {

    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.display.Loader;
    import flash.display.MovieClip;
    import flash.net.URLRequest;
    import flash.events.*;

    [SWF(backgroundColor="#ffffff", frameRate="17", width="300", height="250")]

    public class SwishMaxWrapper extends Sprite {

        function SwishMaxWrapper() {

            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;

            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
            addChild(loader);

            var request:URLRequest = new URLRequest("swishy.swf");
            loader.load(request);

        }

        private function completeHandler(event:Event):void {

            var movie:MovieClip = event.target.content;
            movie.stop();

        }

    }

}
</code>```

The animation load works as expected but the movie.stop() doesn't. What is wrong?

答:
stop() isn't recurive, I think the problem is here.</p>

```<code> function ruleThemAll(target : DisplayObjectContainer, doStop : Boolean = true) : void
   {
      for(var i : uint = 0; i < target.childNum; ++i)
      {
         var child : DisplayObject = target.getChildAt(i);

         // If it's a container, go into to stop children
         if(child is DisplayObjectContainer)
            ruleThemAll(child as DisplayObjectContainer, doStop);

         if(child is MovieClip)
         {
             if(doStop)
                MovieClip(child).stop();
             else
                MovieClip(child).play();
         }
      }
   }
</code>```

Body:
I'm developing an AS 3.0 wrapper to add some extra stuff that has to load some old and plain frame to frame SwishMax 3 animations and then be able to stop them, play them, and so...

Here is my code:

package {

    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.display.Loader;
    import flash.display.MovieClip;
    import flash.net.URLRequest;
    import flash.events.*;

    [SWF(backgroundColor="#ffffff", frameRate="17", width="300", height="250")]

    public class SwishMaxWrapper extends Sprite {

        function SwishMaxWrapper() {

            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;

            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
            addChild(loader);

            var request:URLRequest = new URLRequest("swishy.swf");
            loader.load(request);

        }

        private function completeHandler(event:Event):void {

            var movie:MovieClip = event.target.content;
            movie.stop();

        }

    }

}

The animation load works as expected but the movie.stop() doesn't. What is wrong?

Body:
stop() isn't recurive, I think the problem is here.

 function ruleThemAll(target : DisplayObjectContainer, doStop : Boolean = true) : void
   {
      for(var i : uint = 0; i < target.childNum; ++i)
      {
         var child : DisplayObject = target.getChildAt(i);

         // If it's a container, go into to stop children
         if(child is DisplayObjectContainer)
            ruleThemAll(child as DisplayObjectContainer, doStop);

         if(child is MovieClip)
         {
             if(doStop)
                MovieClip(child).stop();
             else
                MovieClip(child).play();
         }
      }
   }


问:
Typescript: Type 'string | undefined' is not assignable to type 'string'
When I make any property of an interface optional, and while assigning its member to some other variable like this:

```<code>interface Person {
  name?: string,
  age?: string,
  gender?: string,
  occupation?: string,
}

function getPerson() {
  let person = <Person>{name:"John"};
  return person;
}

let person: Person = getPerson();
let name1: string = person.name; // <<< Error here
</code>```

I get an error like the following:

```<code>TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
</code>```

How do I get around this error?

答:
A more production-ready way to handle this is to actually ensure that name is present. Assuming this is a minimal example of a larger project that a group of people are involved with, you don't know how getPerson will change in the future.

```<code>if (!person.name) {
    throw new Error("Unexpected error: Missing name");
}

let name1: string = person.name;
</code>```

Alternatively, you can type name1 as string | undefined, and handle cases of undefined further down. However, it's typically better to handle unexpected errors earlier on.

You can also let TypeScript infer the type by omitting the explicit type: let name1 = person.name This will still prevent name1 from being reassigned as a number, for example.

Body:
When I make any property of an interface optional, and while assigning its member to some other variable like this:

interface Person {
  name?: string,
  age?: string,
  gender?: string,
  occupation?: string,
}

function getPerson() {
  let person = <Person>{name:"John"};
  return person;
}

let person: Person = getPerson();
let name1: string = person.name; // <<< Error here

I get an error like the following:

TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.

How do I get around this error?

Body:
A more production-ready way to handle this is to actually ensure that name is present. Assuming this is a minimal example of a larger project that a group of people are involved with, you don't know how getPerson will change in the future.

if (!person.name) {
    throw new Error("Unexpected error: Missing name");
}

let name1: string = person.name;

Alternatively, you can type name1 as string | undefined, and handle cases of undefined further down. However, it's typically better to handle unexpected errors earlier on.

You can also let TypeScript infer the type by omitting the explicit type: let name1 = person.name This will still prevent name1 from being reassigned as a number, for example.


问:
Rendering font character LSB or placement varies
I am running into inconsistencies with how glyphs are spaced in some situations.

I am using DirectWrite with a IDWriteFontFace and using the GetGlyphIndices with GetDesignGlyphMetrics to get the metrics of the glyphs so I can take each glyph, store it as an image, then reconstruct the whole string using the glyph information (advance, lsb, rsb, etc). I am rendering each glyph using ID2D1RenderTarget.DrawTextLayout with WIC bitmaps. While 99% of tests I have done seem to work, I am running into inconsistent spacing and I have no idea what is causing it. Maybe someone can shed some light, but I am not sure where to start.

From my basic interpretation the font layout is composed of rendering the glyphs as lsb + width, and then the place to put the next character is called the advance and the advance width is composed of lsb, glyph width, rsb.

I am using this Zapfino font, because it seems fairly complex and a good metric to test if things are rendering correctly.

So here are some rendering comparisons line by line:

correct render: Here are two different strings left and right, correctly rendered through paint.net

my render: I include the advance placements (red) and the starting position (yellow).
On the left, we have World! rendered, and the orld! is correctly placed, but the distance between W and o is too large now compared to the correct rendering.

On the right side we have Hold! rendered and for the most part is consistent with the paint.net render.

I overlap both to give a better idea of comparison. I align the left of the orld! so you can see that atleast that part is consistent, it's the W is off. Right side is almost identical.

Paint.net shows the cursor position in what I assume is the advance. You can see that the advance placement, the o is right on top of it. But with o on the right side, you can see it has distance from advance to the o. When rendering the o at the front (5), next to a different character, or by itself, it still has that distance. I believe (appearance wise) it's the LSB that seems to shrink?

orld! rendered with paint.net with the cursor. You can see the o is intersecting the advance. Some other examples, We has the same problem as Wo, shrunk LSB, but for instance in Wi, the glyph has proper distance from the advance, like it would be on its own.

What is this effect called where it shrinks the LSB or moves the placement of the glyph depending on characters? How can I detect such behavior through glyph data?

答:
I figured it out, it is kerning. I was thrown off because when I checked the font, DirectWrite returns 0 for HasKerningPairs. However, I opened up the font in a font editor and could see it does have kerning pairs. Further looking at the docs it says:

Newer fonts may have only GPOS kerning instead of the legacy pair-table kerning. Such fonts, like Gabriola, will only return 0's for adjustments. GetKerningPairAdjustments doesn't virtualize and flatten these GPOS entries into kerning pairs.

They don't offer any other way to grab them, so this is a dead end. There is no way to get these variables from the font in DirectWrite, which I find odd because the built in TextLayout makes these adjustments internally. However, as such there is no solution to this issue with the API provided by DirectWrite, this can be marked solved and unresolved.


问:
Filter number followed by dots out of an array
I would like to get rid of the numbers followed by a dot in an array.

I tried something like this.

function parseMoves(){
  const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."] // And so on.
  const reg = new RegExp('[0-9]+\.');
  const filtered = pgnmoves.filter((x) => {
        return x != reg.test(x)
    })
  return filtered;
}```
</div>
</div>
</p>

<p>But that doesn't seem to do the trick, I am not so good with regular expressions.</p>

<p>This is the expected output:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>["Nf3", "Nc6", "Bc4", "e6"]</code>```

Thank you for helping out!

答:
Your regular expression is fine. You need to preserve items that fail the test, by using the ! operator:

function parseMoves(){
  const reg = /[0-9]+\./; // /^[0-9]+\.$/ - if you want to remove just items that start with a number and have a single dot at the end

  return pgnmoves.filter((x) => !reg.test(x));
}

const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."]; // And so on.

const result = parseMoves(pgnmoves);

console.log(result);```

Body:
I would like to get rid of the numbers followed by a dot in an array.

I tried something like this.

function parseMoves(){
  const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."] // And so on.
  const reg = new RegExp('[0-9]+\.');
  const filtered = pgnmoves.filter((x) => {
        return x != reg.test(x)
    })
  return filtered;
}

But that doesn't seem to do the trick, I am not so good with regular expressions.

This is the expected output:

["Nf3", "Nc6", "Bc4", "e6"]

Thank you for helping out!


问:
Mongo: filter after projection
I'm working with pymongo. One of my fields is: published_date which is a string formated as 2020/03/10 07:20:09

I'm able to convert this value to a datetime using the following aggregate:

```<code>isodate = datetime.now()
pipeline = [
    {'$limit': 2},
    {'$project': {
        'date':'$published_date',
        'date2': {
            '$dateFromString': {
                'dateString': '$published_date',
                }
            },
        }
    }
]
cursor = TEST_COLLECTION.aggregate(pipeline)
list(cursor)
</code>```

where date2 is the value converted to datetime (working already).
Now, the list of documents should be filtered such as the date2 >= isodate
I've tried to do it by implementing:

```<code>'date2': {
                '$filter': {
                    'input': {
                        '$dateFromString': {
                            'dateString': '$published_date',
                            }
                        },
                    'as': "date2",
                    'cond': {
                        '$gte': ['$$date2', isodate]
                        }
                    }
                }
</code>```

but it sems it is not working since i get the following error:

OperationFailure: input to $filter must be an array not date

Update
As asked in the comments, the data consists of documents with several fields, published_date being one of them. I expect as an output a list of documents that comply with the filter of published_date >= datetime.now().

Maybe the solution is not a pipeline but I'm not sure since it is my first time with aggregates.

Any thoughts?

答:
Forget $filter. It serves different purpose.
You want an extra $match stage in the pipeline to filter out documents produced by the $project stage:

```<code>pipeline = [
    {'$limit': 2},
    {'$project': {
        'date':'$published_date',
        'date2': {
            '$dateFromString': {
                'dateString': '$published_date',
                }
            },
        }
    },
    {'$match': {'date2': {'$gte': isodate}}}
]
</code>```

assuming your isodate is a valid date object.

Title: Mongo: filter after projection

Body:
I'm working with pymongo. One of my fields is: published_date which is a string formated as 2020/03/10 07:20:09

I'm able to convert this value to a datetime using the following aggregate:

isodate = datetime.now()
pipeline = [
    {'$limit': 2},
    {'$project': {
        'date':'$published_date',
        'date2': {
            '$dateFromString': {
                'dateString': '$published_date',
                }
            },
        }
    }
]
cursor = TEST_COLLECTION.aggregate(pipeline)
list(cursor)

where date2 is the value converted to datetime (working already).
Now, the list of documents should be filtered such as the date2 >= isodate
I've tried to do it by implementing:

'date2': {
                '$filter': {
                    'input': {
                        '$dateFromString': {
                            'dateString': '$published_date',
                            }
                        },
                    'as': "date2",
                    'cond': {
                        '$gte': ['$$date2', isodate]
                        }
                    }
                }

but it sems it is not working since i get the following error:

OperationFailure: input to $filter must be an array not date

Update
As asked in the comments, the data consists of documents with several fields, published_date being one of them. I expect as an output a list of documents that comply with the filter of published_date >= datetime.now().

Maybe the solution is not a pipeline but I'm not sure since it is my first time with aggregates.

Any thoughts?

Body:
Forget $filter. It serves different purpose.
You want an extra $match stage in the pipeline to filter out documents produced by the $project stage:

pipeline = [
    {'$limit': 2},
    {'$project': {
        'date':'$published_date',
        'date2': {
            '$dateFromString': {
                'dateString': '$published_date',
                }
            },
        }
    },
    {'$match': {'date2': {'$gte': isodate}}}
]

assuming your isodate is a valid date object.


问:
How to sort Eloquent collection after fetching results?
In my controller I have this query

```<code>$query = Market::whereHas('cities', function($query) use ($city) {
    $query->where('id', $city);
})->get();
</code>```

Then I want to make a few operations with this collection and remove my subquerys from the main object

```<code>$return['highlighted'] = $markets->where('highlighted', true);
$markets = $markets->diff($return['highlighted']);
</code>```

The problem is when I try to sort it by created_at

```<code>$return['latest'] = $markets->sortByDesc('created_at')->take(4);
$markets = $markets->diff($return['latest']);
</code>```

It just won't work, keeps returning the first 4 objects order by id, I've tried parsing created_at inside a callback function with Carbon::parse() and strtotime with no results.

I'm avoiding at all cost to make 2 different database querys since the original $markets has all the data that I need.

Any suggestion?
Thanks

答:
I think your problem is you try to sort and take in one-go and also missing a small thing when you try to access the values of the collection.

Try below approach:

```<code> $return['latest'] = $markets->sortByDesc('created_at');

 $markets = $markets->diff($return['latest']->values()->take(4));
</code>```

Or you may need to do it like:

```<code> $return['latest'] = $markets->sortByDesc('created_at');
 $return['latest'] = $return['latest']->values()->take(4);

 $markets = $markets->diff($return['latest']->all());
</code>```

Body:
In my controller I have this query

$query = Market::whereHas('cities', function($query) use ($city) {
    $query->where('id', $city);
})->get();

Then I want to make a few operations with this collection and remove my subquerys from the main object

$return['highlighted'] = $markets->where('highlighted', true);
$markets = $markets->diff($return['highlighted']);

The problem is when I try to sort it by created_at

$return['latest'] = $markets->sortByDesc('created_at')->take(4);
$markets = $markets->diff($return['latest']);

It just won't work, keeps returning the first 4 objects order by id, I've tried parsing created_at inside a callback function with Carbon::parse() and strtotime with no results.

I'm avoiding at all cost to make 2 different database querys since the original $markets has all the data that I need.

Any suggestion?
Thanks

Body:
I think your problem is you try to sort and take in one-go and also missing a small thing when you try to access the values of the collection.

Try below approach:

 $return['latest'] = $markets->sortByDesc('created_at');

 $markets = $markets->diff($return['latest']->values()->take(4));

Or you may need to do it like:

 $return['latest'] = $markets->sortByDesc('created_at');
 $return['latest'] = $return['latest']->values()->take(4);

 $markets = $markets->diff($return['latest']->all());


问:
How do I loop through child array and check if component exists React Testing Library
Currently I want to loop through all the child components and check if all the components exist with React Testing Library. The test below gave me the following error:

TypeError: component.contains is not a function

Not sure what is wrong with this test, but it seems it cannot test based on the test ID.

import React from 'react'
import { RandomMeals } from '../RandomMeals/RandomMeals';
import ListMeals from '../ListMeals/ListMeals';
import { SearchBar } from '../SearchBar/SearchBar';
import { TopBar } from '../TopBar/TopBar';
import SearchResult from '../SearchResult/SearchResult';

export const AppComponent = () => (

      <TopBar/>

        <RandomMeals/>
        <SearchBar/>
        <SearchResult/>

        <ListMeals/>

)

test("It should check if components exist", () => {
    render(
        <Provider store={store}>
          <AppComponent/>
        </Provider>
    );

    const component = screen.getAllByTestId("app-component-test");
    console.log(component);
    expect(component.contains(<RandomMeals/>)).toBe(true);
});```

答:
If you want to check that <RandomMeals /> is being rendered, you should query based on that element:

function RandomMeals(props) {
  return
...

}

test("It should check if components exist", () => {
  const screen = render(
    <Provider store={store}>
      <AppComponent/>
    </Provider>
  );

  expect(screen.getByTestId("random-meals-test")).not.toThrow()
  // alternatively
  expect(screen.queryByTestId("random-meals-test")).toBeTruthy()
});
```

To answer your question about what's wrong with the test, getAllByTestId returns an array of DOM nodes that match the query. And Array#contains is not a method in JavaScript. You could use getByTestId to return a single DOM node, which does have a contains method, but even in that case you cannot pass arbitrary JSX as an argument.

Body:
If you want to check that <RandomMeals /> is being rendered, you should query based on that element:

function RandomMeals(props) {
  return <div data-testid="random-meals-test">...</div>
}

test("It should check if components exist", () => {
  const screen = render(
    <Provider store={store}>
      <AppComponent/>
    </Provider>
  );

  expect(screen.getByTestId("random-meals-test")).not.toThrow()
  // alternatively
  expect(screen.queryByTestId("random-meals-test")).toBeTruthy()
});

To answer your question about what's wrong with the test, getAllByTestId returns an array of DOM nodes that match the query. And Array#contains is not a method in JavaScript. You could use getByTestId to return a single DOM node, which does have a contains method, but even in that case you cannot pass arbitrary JSX as an argument.


问:
How to install aws-cli on alpine?
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

```<code>  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages
</code>```

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

```<code>~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'
</code>```

Thanks!

答:
There is an official AWS-CLI image on docker hub published by Amazon, although it uses AmazonLinux2 and not Alpine. I will recommend you use it though.

Reference:
https://hub.docker.com/r/amazon/aws-cli

It's DockerFile:
https://github.com/aws/aws-cli/blob/v2/docker/Dockerfile

```<code>FROM amazonlinux:2 as installer
COPY awscli-exe-linux-x86_64.zip .
RUN yum update -y \
  && yum install -y unzip \
  && unzip awscli-exe-linux-x86_64.zip \
  # The --bin-dir is specified so that we can copy the
  # entire bin directory from the installer stage into
  # into /usr/local/bin of the final stage without
  # accidentally copying over any other executables that
  # may be present in /usr/local/bin of the installer stage.
  && ./aws/install --bin-dir /aws-cli-bin/

FROM amazonlinux:2
RUN yum update -y \
  && yum install -y less groff \
  && yum clean all
COPY --from=installer /usr/local/aws-cli/ /usr/local/aws-cli/
COPY --from=installer /aws-cli-bin/ /usr/local/bin/
WORKDIR /aws
ENTRYPOINT ["/usr/local/bin/aws"]
</code>```

Title: How to install aws-cli on alpine?

Body:
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'

Thanks!

Body:
There is an official AWS-CLI image on docker hub published by Amazon, although it uses AmazonLinux2 and not Alpine. I will recommend you use it though.

Reference:
https://hub.docker.com/r/amazon/aws-cli

It's DockerFile:
https://github.com/aws/aws-cli/blob/v2/docker/Dockerfile

FROM amazonlinux:2 as installer
COPY awscli-exe-linux-x86_64.zip .
RUN yum update -y \
  && yum install -y unzip \
  && unzip awscli-exe-linux-x86_64.zip \
  # The --bin-dir is specified so that we can copy the
  # entire bin directory from the installer stage into
  # into /usr/local/bin of the final stage without
  # accidentally copying over any other executables that
  # may be present in /usr/local/bin of the installer stage.
  && ./aws/install --bin-dir /aws-cli-bin/

FROM amazonlinux:2
RUN yum update -y \
  && yum install -y less groff \
  && yum clean all
COPY --from=installer /usr/local/aws-cli/ /usr/local/aws-cli/
COPY --from=installer /aws-cli-bin/ /usr/local/bin/
WORKDIR /aws
ENTRYPOINT ["/usr/local/bin/aws"]