问:
Splash does not connect to proxy using any of the 3 ways described in documentation
Splash browser does not send anything to through the http proxy. The pages are fetched even when the proxy is not running.

I am using scrapy with splash in python 3 to fetch pages after authentication for a an Angular.js website. The script is able to fetch pages, authenticate, and fetch pages after authentication. However, it does not use the proxy setup at localhost:8090 and wireshark confirms that traffic coming from port 8050 goes to some port in the 50k range.

The setup is
- splash running locally on a docker image (latest) on port 8050
- python 3 running locally on a mac
- Zap proxy running locally on a mac at port 8090
- Web page accessed through VPN

I have tried to specify the proxy host:port through the server using Chrome with a LUA script. Page is fetched without the proxy.

I have tried to specify the proxy in the python script with both Lua and with the api (args={'proxy':'host:port'} and the page is fetched without using the proxy.

I have tried using the proxy-host file and I get status 502.

Proxy set through Lua on Chrome (no error, not proxied):

```<code>function main(splash, args)
  splash:on_request(function(request)
    request:set_proxy{
      host = "127.0.0.1",
      port = 8090,
      username = "",
      password = "",
      type = "HTTP"
    }
  end
  )
  assert(splash:go(args.url))
  assert(splash:wait(0.5))

  return {
    html = splash:html(),
    png = splash:png(),
    har = splash:har(),
  }
end

req = SplashRequest("http://mysite/home", self.log_in,
                     endpoint='execute', args={'lua_source': script})
</code>```

Proxy set through api (status 502):

```<code>req = SplashRequest("http://mysite/home",
                            self.log_in, args={'proxy': 'http://127.0.0.1:8090'})
</code>```

Proxy set through Lua in Python (no error, not proxied):

```<code>def start_requests(self):
        script = """
            function main(splash, args)

                assert(splash:go(args.url))
                assert(splash:wait(0.5))
                splash:on_request(function(request)
                    request:set_proxy{
                        host = "127.0.0.1",
                        port = 8090,
                        username = "",
                        password = "",
                        type = "HTTP"
                    }
                end
                )

                return {
                    html = splash:html(),
                    png = splash:png(),
                    har = splash:har(),
             }
            end
            """
        req = SplashRequest("http://mysite/home", self.log_in,
                            endpoint='execute', args={'lua_source': script})
        # req.meta['proxy'] = 'http://127.0.0.1:8090'
        yield req
</code>```

Proxy set through proxy file in docker image (status 502):
proxy file:

```<code>[proxy]

; required
host=127.0.0.1
port=8090
</code>```

Shell command:

```<code>docker run -it -p 8050:8050 -v ~/Documents/proxy-profile:/etc/splash/proxy-profiles scrapinghub/splash --proxy-profiles-path=/etc/splash/proxy-profiles
</code>```

All of the above should display the page in zap proxy at port 8090.

Some of the above seem to set the proxy, but the proxy can't reach localhost:8090 (status 502). Some don't work at all (no error, not proxied). I think this may be related to fact that a docker image is being used.

I am not looking to use Selenium because that is what this replacing.

答:
Alright I have been struggling with the same problem for a while now, but I found the solution for your first method on GitHub, which is based on what the Docker docs state:

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.
  The gateway is also reachable as gateway.docker.internal.

Meaning that you should/could use the "host.docker.internal" as host instead for your proxy E.g.

```<code>splash:on_request(function (request)
     request:set_proxy{
         host = "host.docker.internal",
         port = 8090
     }
end)
</code>```

Here is the link to the explanation: https://github.com/scrapy-plugins/scrapy-splash/issues/99#issuecomment-386158523

Body:
Splash browser does not send anything to through the http proxy. The pages are fetched even when the proxy is not running.

I am using scrapy with splash in python 3 to fetch pages after authentication for a an Angular.js website. The script is able to fetch pages, authenticate, and fetch pages after authentication. However, it does not use the proxy setup at localhost:8090 and wireshark confirms that traffic coming from port 8050 goes to some port in the 50k range.

The setup is
- splash running locally on a docker image (latest) on port 8050
- python 3 running locally on a mac
- Zap proxy running locally on a mac at port 8090
- Web page accessed through VPN

I have tried to specify the proxy host:port through the server using Chrome with a LUA script. Page is fetched without the proxy.

I have tried to specify the proxy in the python script with both Lua and with the api (args={'proxy':'host:port'} and the page is fetched without using the proxy.

I have tried using the proxy-host file and I get status 502.

Proxy set through Lua on Chrome (no error, not proxied):

function main(splash, args)
  splash:on_request(function(request)
    request:set_proxy{
      host = "127.0.0.1",
      port = 8090,
      username = "",
      password = "",
      type = "HTTP"
    }
  end
  )
  assert(splash:go(args.url))
  assert(splash:wait(0.5))

  return {
    html = splash:html(),
    png = splash:png(),
    har = splash:har(),
  }
end

req = SplashRequest("http://mysite/home", self.log_in,
                     endpoint='execute', args={'lua_source': script})

Proxy set through api (status 502):

req = SplashRequest("http://mysite/home",
                            self.log_in, args={'proxy': 'http://127.0.0.1:8090'})

Proxy set through Lua in Python (no error, not proxied):

def start_requests(self):
        script = """
            function main(splash, args)

                assert(splash:go(args.url))
                assert(splash:wait(0.5))
                splash:on_request(function(request)
                    request:set_proxy{
                        host = "127.0.0.1",
                        port = 8090,
                        username = "",
                        password = "",
                        type = "HTTP"
                    }
                end
                )

                return {
                    html = splash:html(),
                    png = splash:png(),
                    har = splash:har(),
             }
            end
            """
        req = SplashRequest("http://mysite/home", self.log_in,
                            endpoint='execute', args={'lua_source': script})
        # req.meta['proxy'] = 'http://127.0.0.1:8090'
        yield req

Proxy set through proxy file in docker image (status 502):
proxy file:

[proxy]

; required
host=127.0.0.1
port=8090

Shell command:

docker run -it -p 8050:8050 -v ~/Documents/proxy-profile:/etc/splash/proxy-profiles scrapinghub/splash --proxy-profiles-path=/etc/splash/proxy-profiles

All of the above should display the page in zap proxy at port 8090.

Some of the above seem to set the proxy, but the proxy can't reach localhost:8090 (status 502). Some don't work at all (no error, not proxied). I think this may be related to fact that a docker image is being used.

I am not looking to use Selenium because that is what this replacing.

Body:
Alright I have been struggling with the same problem for a while now, but I found the solution for your first method on GitHub, which is based on what the Docker docs state:

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.
  The gateway is also reachable as gateway.docker.internal.

Meaning that you should/could use the "host.docker.internal" as host instead for your proxy E.g.

splash:on_request(function (request)
     request:set_proxy{
         host = "host.docker.internal",
         port = 8090
     }
end)

Here is the link to the explanation: https://github.com/scrapy-plugins/scrapy-splash/issues/99#issuecomment-386158523


来源: stackexchange

问:
How to keep a normative Software Engineering when many .py files import duplicated packages?
I write some utility/ tool .py files, but it import many duplicated packages. And I will import these .py files in the rest .py files.

For example:

```<code># tool_a.py
import a
from b import b_1
import c
from e import e_1
# some implementations in a.py.
... ...
... ...

# tool_b.py
import b
import c
from d import d_1
# some implementations in b.py
... ...
... ...

# tool_c.py
import c
import d
import e
# some implementations c.py
... ...
... ...

# And there are so many tools files like this
... ...
... ...
</code>```
```<code># Class A
import tool_a
import tool_b
# some implementations in Class A
... ...
... ...

# Class B
import tool_a
import tool_c
# some implementations in Class B
... ...
... ...

# And there are so many Class implementation files will include these tool files just like here
... ...
... ...
</code>```

So if I just import these tools files one by one in each class file it will import so many duplicated packages and cause dependency problems

Sure it is a bad way, but I don't know how to solve the terrible packages dependency problems.

Could anyone help me ?

答: I don't think you need to worry about the multiple imports. If you tell python to import a module that is already imported, it will just access the cached module from when it was initially imported. The best practice is to just import the modules where you need them and not worry if the same module is imported in several files.</p>

ContentLicense: CC BY-SA 4.0

Body:
I write some utility/ tool .py files, but it import many duplicated packages. And I will import these .py files in the rest .py files.

For example:

# tool_a.py
import a
from b import b_1
import c
from e import e_1
# some implementations in a.py.
... ...
... ...

# tool_b.py
import b
import c
from d import d_1
# some implementations in b.py
... ...
... ...

# tool_c.py
import c
import d
import e
# some implementations c.py
... ...
... ...

# And there are so many tools files like this
... ...
... ...

# Class A
import tool_a
import tool_b
# some implementations in Class A
... ...
... ...

# Class B
import tool_a
import tool_c
# some implementations in Class B
... ...
... ...

# And there are so many Class implementation files will include these tool files just like here
... ...
... ...

So if I just import these tools files one by one in each class file it will import so many duplicated packages and cause dependency problems

Sure it is a bad way, but I don't know how to solve the terrible packages dependency problems.

Could anyone help me ?


问:
Legacy C# and VB Expression Evaluators in Visual Studio 2019 16.5+
I am working with ArcObjects 10.4 in my .NET Project and I need "Use the legacy C# and VB expression evaluators" option to watch variables while debugging. After updating Visual Studio 2019 to version 16.5 there isn't an option to turn it on. It only shows an empty place where this option should be.

Is there any way to turn it on or am I stuck with VS 2019 16.4?

答:
I found way to turn it on. In CurrentSettings.vssettings file located in "%LocalAppData%\Microsoft\VisualStudio\16.0_xxxxxxxx\Settings" there is

<PropertyValue name="UseVBCSLegacyExpressionEvaluator">0</PropertyValue>

setting it to 1 makes legacy evaluator work again.

UPDATE

There is an easier way to turn this option on.

In Visual Studio export settings using Tools > Import and Export Settings... > Export selected environment settings > Next > Select only Debugging in Options node > Next >  Finish.

Edit exported settings file and change

<PropertyValue name="UseVBCSLegacyExpressionEvaluator">0</PropertyValue>

to

<PropertyValue name="UseVBCSLegacyExpressionEvaluator">1</PropertyValue>

Import back settings to Visual Studio using Tools > Import and Export Settings... > Import selected environment settings > Yes, save my current settings > Next > Browse... > Next >  Finish.


问:
FileNotFoundError: [Errno 2] No such file or directory: in jupyter notebook
```<code>from scipy.io import wavfile

train_audio_path = 'E:/'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-27-cd74bbc41446> in <module>
      3 train_audio_path = 'E:/'
      4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
      6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
    262         mmap = False
    263     else:
--> 264         fid = open(filename, 'rb')
    265
    266     try:

FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'
</code>```

I have a problem with my code. I tried to do everything but failed. I have no idea why this error is made. I changed path to everywhere from c to e but still not working at all. what's wrong in my code?

答:
Try

```<code>train_audio_path = 'E:\' OR 'E:\\'
</code>```

change the direction of '\'

And don't forget to add the extension of your image file as well (i.e., jpg,png or any other). I also get this error multiple times in windows.Hope it helps.

Body:
from scipy.io import wavfile

train_audio_path = 'E:/'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-27-cd74bbc41446> in <module>
      3 train_audio_path = 'E:/'
      4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
      6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
    262         mmap = False
    263     else:
--> 264         fid = open(filename, 'rb')
    265
    266     try:

FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'

I have a problem with my code. I tried to do everything but failed. I have no idea why this error is made. I changed path to everywhere from c to e but still not working at all. what's wrong in my code?

Body:
Try

train_audio_path = 'E:\' OR 'E:\\'

change the direction of '\'

And don't forget to add the extension of your image file as well (i.e., jpg,png or any other). I also get this error multiple times in windows.Hope it helps.


问:
is there any way to read "select mock location app" from Android developer settings?
I know the recomended way to know in Android if a location is a fake point is something like this:

```<code>boolean isMock = false;
if (android.os.Build.VERSION.SDK_INT >= 18) {
    isMock = location.isFromMockProvider();
} else { // Old Android versions (<6)
    isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
}
</code>```

So, for current Androids I have to request location permission to know if this is a mock location. But I think it is not necessary if I can read "select mock location app".

Also, if you want to show an alert message you can custom this message. e.g.: You could say something like this: "Please remove com.lexa.fakegps app". And when user clicks on "Accept", you could redirect to next link: https://play.google.com/store/apps/details?id=com.lexa.fakegps

Also, there are fake gps apps that return false in the  isFromMockProvider method.

Also, you can do stats with apps more use for yours users.

And finally, I don't understood why you can read every setting of developer settings except "select mock location app":

https://developer.android.com/reference/android/provider/Settings

Is there any solution? Or simply is it a stupid impossible thing?

答:
So first of all... by using the following code

```<code>boolean isMock = false;
if (android.os.Build.VERSION.SDK_INT >= 18) {
    isMock = location.isFromMockProvider();
} else { // Old Android versions (<6)
    isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
}
</code>```

you can't ensure the device location is faked all the time.

For older versions of android

```<code>isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
</code>```

is being used but what it does basically it just gives whether the user turned on the settings for allowing mock location... so it just acts as a filter to check

So if I am using an old phone and turn this setting on even if I am not using fake location it still returns true

For latest versions of android

```<code>isMock = location.isFromMockProvider();
</code>```

it is buggy ... may not always return correct answer i.e even if you set the location using mock location app sometimes it may return false.

Conclusion:

To conclude reading the "select mock location app" setting and making a decision on its value is just a stupid thing. and you can't write software that is always bug-free.

I personally tried and tested with some of the fake GPS apps like

Lexa Fake GPS Location

Fake GPS

for me during my tests isFromMockProvider() always returned me the correct output So I found it the probability of finding the bug is rare.

And in order to make sure it's a buggy value I found this remedy on this post : Location on Android: Stop Mocking Me! I quote remedy from this article

Since most location readings are correctly labeled, it’s not too
  difficult to identify and reject the false negatives. I chose the
  following strategy:

Remember the most recent location labeled as a mock

If a new “non-mock” reading is within 1km of the last mock, reject it.

Only clear the last mock location after 20 consecutive “non-mock”
readings.

And I also recommend you to go through FauChristian Answer for Detect or prevent if the user uses fake location

Thank you...

Body:
I know the recomended way to know in Android if a location is a fake point is something like this:

boolean isMock = false;
if (android.os.Build.VERSION.SDK_INT >= 18) {
    isMock = location.isFromMockProvider();
} else { // Old Android versions (<6)
    isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
}

So, for current Androids I have to request location permission to know if this is a mock location. But I think it is not necessary if I can read "select mock location app".

Also, if you want to show an alert message you can custom this message. e.g.: You could say something like this: "Please remove com.lexa.fakegps app". And when user clicks on "Accept", you could redirect to next link: https://play.google.com/store/apps/details?id=com.lexa.fakegps

Also, there are fake gps apps that return false in the  isFromMockProvider method.

Also, you can do stats with apps more use for yours users.

And finally, I don't understood why you can read every setting of developer settings except "select mock location app":

https://developer.android.com/reference/android/provider/Settings

Is there any solution? Or simply is it a stupid impossible thing?

Body:
So first of all... by using the following code

boolean isMock = false;
if (android.os.Build.VERSION.SDK_INT >= 18) {
    isMock = location.isFromMockProvider();
} else { // Old Android versions (<6)
    isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
}

you can't ensure the device location is faked all the time.

For older versions of android

isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");

is being used but what it does basically it just gives whether the user turned on the settings for allowing mock location... so it just acts as a filter to check

So if I am using an old phone and turn this setting on even if I am not using fake location it still returns true

For latest versions of android

isMock = location.isFromMockProvider();

it is buggy ... may not always return correct answer i.e even if you set the location using mock location app sometimes it may return false.

Conclusion:

To conclude reading the "select mock location app" setting and making a decision on its value is just a stupid thing. and you can't write software that is always bug-free.

I personally tried and tested with some of the fake GPS apps like

Lexa Fake GPS Location

Fake GPS

for me during my tests isFromMockProvider() always returned me the correct output So I found it the probability of finding the bug is rare.

And in order to make sure it's a buggy value I found this remedy on this post : Location on Android: Stop Mocking Me! I quote remedy from this article

Since most location readings are correctly labeled, it’s not too
  difficult to identify and reject the false negatives. I chose the
  following strategy:

Remember the most recent location labeled as a mock

If a new “non-mock” reading is within 1km of the last mock, reject it.

Only clear the last mock location after 20 consecutive “non-mock”
readings.

And I also recommend you to go through FauChristian Answer for Detect or prevent if the user uses fake location

Thank you...


问:
How do you reference a Key from Azure Key Vault in a function app?
I've used quite a few secrets for Azure Functions in the past, and now I am trying to use a Key, RSA encrypted , 4096 bits. It's a private PuTTy .ppk key, which I've exported to a .pem type to match Azure's requirements. I have a Python 3.7 App in which I have deployed the needed function and I have tried to reference in the Application Settings the needed key with the following statement :

@Microsoft.KeyVault(SecretUri=https://{thevault-address}.vault.azure.net/keys/{thekey-name}/)

as well as

@Microsoft.KeyVault(SecretUri=https://{thevault-address}.vault.azure.net/keys/{thekey-name}/latestVersionHash)

But when I try to save it , it says that the reference could not be resolved.

The application has Identity On and the Vault has access policies for the Function configured for secrets as Get and List and for Keys as everything (initially just Get and List but added the rest just in case, because I thought that it might be an 'encription/decription' issue).

And idea why am I getting the Status:InvalidSyntax and Error Details:
Key Vault reference was not able to be resolved because invalid Key Vault reference syntax found ? Thanks !

答:
The process you described above is perfectly correct to reference a Secret.That is why in the string @Microsoft.KeyVault(SecretUri= you set SecretUri equals to...

For Keys thow, that would not be possible. A Key cannot be referenced by an azure web app.

To clear any confusion in order to reference a secret to Azure KeyVault from a web app you need three points

You application identity On

Set policies in in Keyvault so your app would be able to access the value

In your web app, in Configuration tab you set the value of your variable as @Microsoft.KeyVault(SecretUri={Secret Identifier}).

Secret identifier can be found if you go to your Keyvault resource and click your secret

The identity value needs to be identical.


问:
How to get dpid of a switch from the xterm of a host in mininet?
I have created a topology in mininet. I want to get the dpid or name of a switch from the host it's connected to using xterm or mininet's python API. I looked it up on google but couldn't find anything.

Thanks in advance.

答:
from the Mininet CLI, you can do:

```<code>py net.getNodeByName("s1").dpid
</code>```

Example:

```<code>root@raspberrypi:~# mn
*** Creating network
*** Adding controller
*** Adding hosts:
h1 h2
*** Adding switches:
s1
*** Adding links:
(h1, s1) (h2, s1)
*** Configuring hosts
h1 h2
*** Starting controller
c0
*** Starting 1 switches
s1 ...
*** Starting CLI:
mininet> py net.getNodeByName("s1").dpid
0000000000000001
mininet>
</code>```

from the python API as explained in the official documentation

```<code>print(switch_node.dpid)
</code>```

Or you can directly see in your host machine or using xterm with:

```<code>bash -c 'ovs-ofctl show s1|grep dpid'
</code>```

Body:
from the Mininet CLI, you can do:

py net.getNodeByName("s1").dpid

Example:

root@raspberrypi:~# mn
*** Creating network
*** Adding controller
*** Adding hosts:
h1 h2
*** Adding switches:
s1
*** Adding links:
(h1, s1) (h2, s1)
*** Configuring hosts
h1 h2
*** Starting controller
c0
*** Starting 1 switches
s1 ...
*** Starting CLI:
mininet> py net.getNodeByName("s1").dpid
0000000000000001
mininet>

from the python API as explained in the official documentation

print(switch_node.dpid)

Or you can directly see in your host machine or using xterm with:

bash -c 'ovs-ofctl show s1|grep dpid'


问:
Cannot create and open File using file handling
I am writing a basic code but run into an error when trying to open a file. I've had a rough break and am having to start from the basics. Following is the part of the code where I run into the error:

```<code>int main()
{
    string name;
    fstream file;
    cout << " Enter file name and type (E.g filname.txt) : ";
    cin >> name;
    file.open(name);
</code>```

Following is the error:

[Error] no matching function for call to 'std::basic_fstream<char>::open(std::string&)'

I am returning after a long break so I apologize for any inconsistencies.

答:
you have to pass the open mode too.

Here is an example:

```<code>// print the content of a text file.
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream ifs;

  ifs.open ("test.txt", std::ifstream::in);

  char c = ifs.get();

  while (ifs.good()) {
    std::cout << c;
    c = ifs.get();
  }

  ifs.close();

  return 0;
}
</code>```

Code taken from Here

I suggest you to always check on cplusplus.com

It's very well documented!

Body:
I am writing a basic code but run into an error when trying to open a file. I've had a rough break and am having to start from the basics. Following is the part of the code where I run into the error:

int main()
{
    string name;
    fstream file;
    cout << " Enter file name and type (E.g filname.txt) : ";
    cin >> name;
    file.open(name);

Following is the error:

[Error] no matching function for call to 'std::basic_fstream<char>::open(std::string&)'

I am returning after a long break so I apologize for any inconsistencies.

Body:
you have to pass the open mode too.

Here is an example:

// print the content of a text file.
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream ifs;

  ifs.open ("test.txt", std::ifstream::in);

  char c = ifs.get();

  while (ifs.good()) {
    std::cout << c;
    c = ifs.get();
  }

  ifs.close();

  return 0;
}

Code taken from Here

I suggest you to always check on cplusplus.com

It's very well documented!


问:
How to have Text with Icon in center Flutter?
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

```<code>FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),
</code>```

答:
Short answer:

```<code>Column(
  mainAxisSize: MainAxisSize.min,
  children: [
    Icon(Icons.call),
    SizedBox(height: 4), // spacing between two
    Text('Call Icon'),
  ],
)
</code>```

Long answer:

Copy this class:

```<code>class TextWithIcon extends StatelessWidget {
  final IconData icon;
  final String text;
  final double spacing;

  const TextWithIcon({Key key, this.icon, this.text, this.spacing = 2}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon),
          SizedBox(height: spacing),
          Text(text),
        ],
      ),
    );
  }
}
</code>```

Usage:

```<code>TextWithIcon(
  icon: Icons.call,
  spacing: 6, // Space between icon and text
  text: 'Call Icon',
)
</code>```

Body:
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),

Body:
Short answer:

Column(
  mainAxisSize: MainAxisSize.min,
  children: [
    Icon(Icons.call),
    SizedBox(height: 4), // spacing between two
    Text('Call Icon'),
  ],
)

Long answer:

Copy this class:

class TextWithIcon extends StatelessWidget {
  final IconData icon;
  final String text;
  final double spacing;

  const TextWithIcon({Key key, this.icon, this.text, this.spacing = 2}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon),
          SizedBox(height: spacing),
          Text(text),
        ],
      ),
    );
  }
}

Usage:

TextWithIcon(
  icon: Icons.call,
  spacing: 6, // Space between icon and text
  text: 'Call Icon',
)


问:
discordjs problems logging whenever a dm is sent
I have a whole logging system that logs whenever various things are done in the server or with the bot, one being a log of whenever a dm is sent to the bot. the log would contain the author ID and the message content. the problem is with logging the message content. the bot crashes whenever a second DM is sent but works fine if its a first DM. the bot crash message is the following: https://gyazo.com/5ad0b41648f83a855ac8c49fb220a612

but the strange thing is, my fields aren't empty:

bot.on('message', msg=>{
    const LogChannel = bot.channels.cache.get('712811824826941460');
    const LogEmbed = new Discord.MessageEmbed()
    .setColor('#606060')
    .setAuthor(msg.author.tag)
    .setDescription('DM Sent')
    .addField('Message', msg.content)
    .setTimestamp()
    if(msg.channel.type === 'dm')
    LogChannel.send(LogEmbed)
});
```

the console thinks that the .addField('Message', msg.content) is empty but as you can see, it's not. keep in mind it only gives me the error message after a second DM is sent following a first one.
any ideas?

答:
There is no Message.content properties. I guess you are looking for Message.cleanContent

```<code>bot.on('message', msg=>{
    const LogChannel = bot.channels.cache.get('712811824826941460');
    const LogEmbed = new Discord.MessageEmbed()
    .setColor('#606060')
    .setAuthor(msg.author.tag)
    .setDescription('DM Sent')
    .addField('Message', msg.cleanContent)
    .setTimestamp()
    if(msg.channel.type === 'dm')
    LogChannel.send(LogEmbed)
});
</code>```

Body:
I have a whole logging system that logs whenever various things are done in the server or with the bot, one being a log of whenever a dm is sent to the bot. the log would contain the author ID and the message content. the problem is with logging the message content. the bot crashes whenever a second DM is sent but works fine if its a first DM. the bot crash message is the following: https://gyazo.com/5ad0b41648f83a855ac8c49fb220a612

but the strange thing is, my fields aren't empty:

bot.on('message', msg=>{
    const LogChannel = bot.channels.cache.get('712811824826941460');
    const LogEmbed = new Discord.MessageEmbed()
    .setColor('#606060')
    .setAuthor(msg.author.tag)
    .setDescription('DM Sent')
    .addField('Message', msg.content)
    .setTimestamp()
    if(msg.channel.type === 'dm')
    LogChannel.send(LogEmbed)
});

the console thinks that the .addField('Message', msg.content) is empty but as you can see, it's not. keep in mind it only gives me the error message after a second DM is sent following a first one.
any ideas?

Body:
There is no Message.content properties. I guess you are looking for Message.cleanContent

bot.on('message', msg=>{
    const LogChannel = bot.channels.cache.get('712811824826941460');
    const LogEmbed = new Discord.MessageEmbed()
    .setColor('#606060')
    .setAuthor(msg.author.tag)
    .setDescription('DM Sent')
    .addField('Message', msg.cleanContent)
    .setTimestamp()
    if(msg.channel.type === 'dm')
    LogChannel.send(LogEmbed)
});


问:
React shortcut to importing style files
I'm working in a React project.

In a component's specific SASS file, I import SASS partials like this:

```<code>@import '../../styles/fonts';
</code>```

When I was working in Angular project, the previous path could be simplified with:

```<code>@import 'fonts';
</code>```

And how this can be achieved is by adding a configuration to ".angular.cli.json" as described in this link https://scotch.io/tutorials/angular-shortcut-to-importing-styles-files-in-components.

My Question is: is there a way to achieve the same result in a React project? and how?

Thank you!

答:
You can use Webpack aliases ( assuming that you're using webpack ) to resolve the imports and then use the alias name in your scss file to import the module like this :

webpack.config.js

```<code>const path = require('path');

module.exports = {
  //...
 resolve: {
    alias: {
       styles: path.join(__dirname, 'app/styles')
   }
 }
};
</code>```

and import like

```<code>@import '~styles/variables';
</code>```

For more info refer these

https://webpack.js.org/configuration/resolve/

https://github.com/webpack-contrib/sass-loader#resolving-import-at-rules

Hope this helps !

Title: React shortcut to importing style files

Body:
I'm working in a React project.

In a component's specific SASS file, I import SASS partials like this:

@import '../../styles/fonts';

When I was working in Angular project, the previous path could be simplified with:

@import 'fonts';

And how this can be achieved is by adding a configuration to ".angular.cli.json" as described in this link https://scotch.io/tutorials/angular-shortcut-to-importing-styles-files-in-components.

My Question is: is there a way to achieve the same result in a React project? and how?

Thank you!

Body:
You can use Webpack aliases ( assuming that you're using webpack ) to resolve the imports and then use the alias name in your scss file to import the module like this :

webpack.config.js

const path = require('path');

module.exports = {
  //...
 resolve: {
    alias: {
       styles: path.join(__dirname, 'app/styles')
   }
 }
};

and import like

@import '~styles/variables';

For more info refer these

https://webpack.js.org/configuration/resolve/

https://github.com/webpack-contrib/sass-loader#resolving-import-at-rules

Hope this helps !


问:
Error when passing a laravel route as a props in VueJS
I want to use the blade syntax route() in a vue js component so i thought i should use something like this :

```<code><nav-bar
:user="{{ json_encode(Auth::user()) }}"
:authPath= "{{ route('auth') }}">

</nav-bar>
</code>```

but an error apear in the console :
app.js:86258 [Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

What did i do wrong?

答:
You are able to pass attributes to Vue component through markup. This is called data binding. Like

```<code><nav-bar
authPath="{{ route('auth') }}">
</nav-bar>
</code>```

The other Vue way to pass the props is with the v-bind: or :(colon), and you have to use both double-quotes and single-quotes in this case.

```<code><nav-bar
authPath="'{{ route('auth') }}'">
</nav-bar>
</code>```

Without both quotes, you will receive Vue warnings.

Body:
I want to use the blade syntax route() in a vue js component so i thought i should use something like this :

but an error apear in the console :
app.js:86258 [Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

What did i do wrong?

Body:
You are able to pass attributes to Vue component through markup. This is called data binding. Like

<nav-bar
authPath="{{ route('auth') }}">
</nav-bar>

The other Vue way to pass the props is with the v-bind: or :(colon), and you have to use both double-quotes and single-quotes in this case.

<nav-bar
authPath="'{{ route('auth') }}'">
</nav-bar>

Without both quotes, you will receive Vue warnings.


问:
bitbucket pipeline error - container 'docker' exceeded memory limit
I am seeing bitbucket pipeline error - container 'docker' exceeded memory limit while running bitbucket pipeline.
I tried to use all possible service memory limits as per below documentation, but issue was not resolved.

Databases and service containers - Service memory limits

Can you help resolve the issue?

答:
As said previously you can use size: 2x on a step to increase the memory limit for that step or set it in options which will enable 2x size for all steps automatically.

However, it is worth noting that doing so will consume twice the number of build minutes compared to a regular step, effectively costing twice as much, as described here


问:
How to Update my Access Database from textboxes
i created a screen where i can edit the details in the database. but as soon as i click on the update button, it says no value given for one or more required parameters. i have attached my code....

Update BUtton...

```<code>Private Sub SimpleButton5_Click(sender As Object, e As EventArgs) Handles SimpleButton5.Click

    Try

        Access.AddParam("@UId", TextBox1.Text)
        Access.AddParam("@ImagePic", PictureBox1.Image)
        Access.AddParam("@Barcod", TextBox2.Text)
        Access.AddParam("@BrandName", TextBox3.Text)
        Access.AddParam("@StockName", TextBox4.Text)
        Access.AddParam("@Category", TextBox5.Text)
        Access.AddParam("@SubCat", TextBox6.Text)
        Access.AddParam("@Subcat2", TextBox7.Text)
        Access.AddParam("@Discrip", TextBox8.Text)
        Access.AddParam("@StockLvl", TextBox9.Text)
        Access.AddParam("@CustomAmount", TextBox10.Text)
        Access.AddParam("@CostPrice", TextBox11.Text)
        Access.AddParam("@Markup", TextBox12.Text)
        Access.AddParam("@TaxAmount", TextBox13.Text)
        Access.AddParam("@SellingPrice", TextBox14.Text)
        Access.AddParam("@BeforTax", TextBox15.Text)
        Access.AddParam("@AfterTax", TextBox16.Text)
        Access.AddParam("@TaxPer", TextBox17.Text)
        Access.AddParam("@MarkupPer", TextBox18.Text)
        Access.AddParam("@LastDate", TextBox19.Text)
        Access.AddParam("@LastUser", TextBox20.Text)

        Access.ExecQuery("UPDATE Inventory " &
                         "SET [Image]=PictureBox1.image, BarCode=Textbox2.text, " &
                         "BrandName=@BrandName, StockName=@StockName, Category=@Category, SubCategory=@SubCat, " &
                         "SubCategory2=@SubCat2, Description=@Discrip, StockLevels=@StockLvl, CustomAmount=@Customamount, " &
                         "CostPrice=@CostPrice, MarkupAmount=@Markup, SellingPrice=@SellingPrice, ProfirBefore=@BeforeTax, " &
                         "ProfitAfter=@AfterTax, TaxAmount=@TaxAmount, taxPer=@TaxPer, MarkupPer=@MarkupPer, LastDateupdated=@LAstDate, " &
                         "UpserUpdated=@LastUser WHERE ID=@UId")

        If NoErrors(True) = False Then Exit Sub

        RefreshData()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally

    End Try

End Sub
</code>```

My Access.ExecQuery --- (Class...)

```<code>Imports System.Data.OleDb

Public Class DBControl
    Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;")
    Private DBCmd As OleDbCommand
    Public DBDA As OleDbDataAdapter
    Public DBDT As DataTable
    Public Params As New List(Of OleDbParameter)
    Public RecordCount As Integer
    Public Exception As String

    Public Sub ExecQuery(Query As String)
        RecordCount = 0
        Exception = ""

        Try
            DBCon.Open()
            DBCmd = New OleDbCommand(Query, DBCon)

            Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))

            Params.Clear()

            DBDT = New DataTable
            DBDA = New OleDbDataAdapter(DBCmd)
            RecordCount = DBDA.Fill(DBDT)
        Catch ex As Exception
            Exception = ex.Message
        End Try

        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Sub

    ' INCLUDE QUERY & COMMAND PARAMETERS
    Public Sub AddParam(Name As String, Value As Object)
        Dim NewParam As New OleDbParameter(Name, Value)
        Params.Add(NewParam)
    End Sub
End Class
</code>```

I have played around with this for 2 days now, but somewhere i am missing something or overlooking something

thx

Jaco

答:
The error message is pretty obvious. Some parameters are missing, either you forgot them or they are misspelled.

You need to double-check your code, it contains quite a few typos.

You are defining parameter @ImagePic, but it's not used in your query.

Same for @Barcod, you put this instead in your SQL: BarCode=Textbox2.text. Just call it @Barcode, why do you abbreviate names like that. That only creates confusion. Use proper English spelling and be consistent.

Another typo: Access.AddParam("@BeforTax", TextBox15.Text). In your SQL: ProfirBefore=@BeforeTax. ProfirBefore is a typo too.

Please do yourself a favor and rename the textboxes too: TextBox1 thru 20 is not good naming practice. There is good chance that you will mix up fields after doing copy-paste of your statements. Textbox20 is not intuitive at all and does not tell you what data you are handling.

I have played around with this for 2 days now, but somewhere i am missing something or overlooking something

Missing glasses perhaps :) I don't know about your development environment put I pasted your code in Notepad++ and by clicking on a keyword it highlights all occurrences of that keyword in the code. It quickly became obvious that some keywords were not being referenced anywhere.

Body:
i created a screen where i can edit the details in the database. but as soon as i click on the update button, it says no value given for one or more required parameters. i have attached my code....

Update BUtton...

Private Sub SimpleButton5_Click(sender As Object, e As EventArgs) Handles SimpleButton5.Click

    Try

        Access.AddParam("@UId", TextBox1.Text)
        Access.AddParam("@ImagePic", PictureBox1.Image)
        Access.AddParam("@Barcod", TextBox2.Text)
        Access.AddParam("@BrandName", TextBox3.Text)
        Access.AddParam("@StockName", TextBox4.Text)
        Access.AddParam("@Category", TextBox5.Text)
        Access.AddParam("@SubCat", TextBox6.Text)
        Access.AddParam("@Subcat2", TextBox7.Text)
        Access.AddParam("@Discrip", TextBox8.Text)
        Access.AddParam("@StockLvl", TextBox9.Text)
        Access.AddParam("@CustomAmount", TextBox10.Text)
        Access.AddParam("@CostPrice", TextBox11.Text)
        Access.AddParam("@Markup", TextBox12.Text)
        Access.AddParam("@TaxAmount", TextBox13.Text)
        Access.AddParam("@SellingPrice", TextBox14.Text)
        Access.AddParam("@BeforTax", TextBox15.Text)
        Access.AddParam("@AfterTax", TextBox16.Text)
        Access.AddParam("@TaxPer", TextBox17.Text)
        Access.AddParam("@MarkupPer", TextBox18.Text)
        Access.AddParam("@LastDate", TextBox19.Text)
        Access.AddParam("@LastUser", TextBox20.Text)

        Access.ExecQuery("UPDATE Inventory " &
                         "SET [Image]=PictureBox1.image, BarCode=Textbox2.text, " &
                         "BrandName=@BrandName, StockName=@StockName, Category=@Category, SubCategory=@SubCat, " &
                         "SubCategory2=@SubCat2, Description=@Discrip, StockLevels=@StockLvl, CustomAmount=@Customamount, " &
                         "CostPrice=@CostPrice, MarkupAmount=@Markup, SellingPrice=@SellingPrice, ProfirBefore=@BeforeTax, " &
                         "ProfitAfter=@AfterTax, TaxAmount=@TaxAmount, taxPer=@TaxPer, MarkupPer=@MarkupPer, LastDateupdated=@LAstDate, " &
                         "UpserUpdated=@LastUser WHERE ID=@UId")

        If NoErrors(True) = False Then Exit Sub

        RefreshData()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally

    End Try

End Sub

My Access.ExecQuery --- (Class...)

Imports System.Data.OleDb

Public Class DBControl
    Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;")
    Private DBCmd As OleDbCommand
    Public DBDA As OleDbDataAdapter
    Public DBDT As DataTable
    Public Params As New List(Of OleDbParameter)
    Public RecordCount As Integer
    Public Exception As String

    Public Sub ExecQuery(Query As String)
        RecordCount = 0
        Exception = ""

        Try
            DBCon.Open()
            DBCmd = New OleDbCommand(Query, DBCon)

            Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))

            Params.Clear()

            DBDT = New DataTable
            DBDA = New OleDbDataAdapter(DBCmd)
            RecordCount = DBDA.Fill(DBDT)
        Catch ex As Exception
            Exception = ex.Message
        End Try

        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Sub

    ' INCLUDE QUERY & COMMAND PARAMETERS
    Public Sub AddParam(Name As String, Value As Object)
        Dim NewParam As New OleDbParameter(Name, Value)
        Params.Add(NewParam)
    End Sub
End Class

I have played around with this for 2 days now, but somewhere i am missing something or overlooking something

thx

Jaco


问:
Bootstrap modal hide is not working
Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.

```<code><button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>

<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
  <div class="modal-bootstrap-dialog modal-sm">
    <div class="modal-bootstrap-content">
      <div class="modal-bootstrap-body">
        -- content ----
      </div>
    </div>
  </div>
  <div class="modal-bootstrap-footer">
     <button type="submit" class="button primary" data-dismiss="modal">Close</button>
     <button type="submit" class="button primary">Save changes</button>
  </div>
</div>

<script type="text/javascript">
$("#buy").click(function () {
   var a = 4;
   if (a == 5) {
     alert("if");
     $('#myModal').modal('show');
   }
   else {
    alert("else");
    $('#myModal').modal('hide');
   }

});
</script>
</code>```

bootply

答:
Check if you closed all nested div inside main modal div </p>

```<code><div data-backdrop="static" class="modal fade" id="modal-progress" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

-----NESTED DIV ------------------

</div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bootstrap modal hide is not working

Body:
Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.

<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>

        -- content ----

     <button type="submit" class="button primary" data-dismiss="modal">Close</button>
     <button type="submit" class="button primary">Save changes</button>

bootply

Body:
Check if you closed all nested div inside main modal div

<div data-backdrop="static" class="modal fade" id="modal-progress" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

-----NESTED DIV ------------------

</div>


问:
How do I get the sum of a txt file and a binary file both of which have array size of 10?
My code is very likely to be incorrect everywhere since I just go started on learning files.
The array of the text file is {3 2 1 3 4 5 6 1 2 3}
The array of the binary is {1 2 3 4 5 6 7 8 9 10}</p>

```<code>#include <stdio.h>
#define ARR_SIZ 10
int main()
{
    int arr_in[ARR_SIZ];
    int arr_bin[ARR_SIZ];
    int i = 0;
    FILE * fp_in = fopen("data/in.txt", "r");
    FILE * fp_bin = fopen("data/in.bin", "wb");
    fread(arr_in, sizeof(int), ARR_SIZ, fp_in);
    fread(arr_bin, sizeof(int), ARR_SIZ, fp_bin);
    int sum[ARR_SIZ];
    for (i=0; i < ARR_SIZ; i++){
            fscanf("%d", arr_in);
    fscanf("%d", arr_in);
    sum[i] = arr_in[i] + arr_bin[i];
    } printf("%d", sum[i]);
    return 0;
    }
</code>```

答:
You can use this simple program (without fread()):

```<code>#include <stdio.h>
#define SIZE 10

int main(void) {
    FILE *text = fopen("in.txt", "r"); // --- declaration
    FILE *binr = fopen("in.bin", "r");
    int text_number[SIZE], binary_number[SIZE], sum = 0;
    // alt: you can change sum to sum[SIZE] = {0} if you want to hold into an array.

    // --- reading data and assigning into arrays
    for (int i = 0; i < SIZE; i++) {
        fscanf(text, "%d", &text_number[i]);
        fscanf(binr, "%d", &binary_number[i]);
    }

    // --- summation
    for (int i = 0; i < SIZE; i++) {
        sum += text_number[i] + binary_number[i]; // alt: do sum[i] when you do sum[SIZE]
        printf("%d ", sum); // alt: do sum[i]
        sum = 0; // should be omitted when you change into sum[SIZE]
    }
    printf("\n");

    return 0;
}
</code>```

in.bin contains: 1 2 3 4 5 6 7 8 9 10

Similarly, in.txt contains: 3 2 1 3 4 5 6 1 2 3

And the result is: 4 4 4 7 9 11 13 9 11 13 (sum of both files' integers taken by array).

Note: If you want to store the sum into array, then use the alt code.

I'm not very much aware of fread(), so I just did what I could at the moment.

Body:
My code is very likely to be incorrect everywhere since I just go started on learning files.
The array of the text file is {3 2 1 3 4 5 6 1 2 3}
The array of the binary is {1 2 3 4 5 6 7 8 9 10}

#include <stdio.h>
#define ARR_SIZ 10
int main()
{
    int arr_in[ARR_SIZ];
    int arr_bin[ARR_SIZ];
    int i = 0;
    FILE * fp_in = fopen("data/in.txt", "r");
    FILE * fp_bin = fopen("data/in.bin", "wb");
    fread(arr_in, sizeof(int), ARR_SIZ, fp_in);
    fread(arr_bin, sizeof(int), ARR_SIZ, fp_bin);
    int sum[ARR_SIZ];
    for (i=0; i < ARR_SIZ; i++){
            fscanf("%d", arr_in);
    fscanf("%d", arr_in);
    sum[i] = arr_in[i] + arr_bin[i];
    } printf("%d", sum[i]);
    return 0;
    }

Body:
You can use this simple program (without fread()):

#include <stdio.h>
#define SIZE 10

int main(void) {
    FILE *text = fopen("in.txt", "r"); // --- declaration
    FILE *binr = fopen("in.bin", "r");
    int text_number[SIZE], binary_number[SIZE], sum = 0;
    // alt: you can change sum to sum[SIZE] = {0} if you want to hold into an array.

    // --- reading data and assigning into arrays
    for (int i = 0; i < SIZE; i++) {
        fscanf(text, "%d", &text_number[i]);
        fscanf(binr, "%d", &binary_number[i]);
    }

    // --- summation
    for (int i = 0; i < SIZE; i++) {
        sum += text_number[i] + binary_number[i]; // alt: do sum[i] when you do sum[SIZE]
        printf("%d ", sum); // alt: do sum[i]
        sum = 0; // should be omitted when you change into sum[SIZE]
    }
    printf("\n");

    return 0;
}

in.bin contains: 1 2 3 4 5 6 7 8 9 10

Similarly, in.txt contains: 3 2 1 3 4 5 6 1 2 3

And the result is: 4 4 4 7 9 11 13 9 11 13 (sum of both files' integers taken by array).

Note: If you want to store the sum into array, then use the alt code.

I'm not very much aware of fread(), so I just did what I could at the moment.


问:
How to reverse the index value in Python using for loop with a given list
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

```<code> X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X
</code>```

I wrote this function:

```<code>def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
</code>```

But i get this print out when i call the function with the given list:

```<code>test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)
</code>```

Output:

```<code> X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

</code>```

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

```<code>print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")
</code>```

答:
a longer version of the solution that can handle size of board greater than 3</p>

```<code>    def display_board(board, size=3):
        parts = []
        h_seps = []
        for i in range(size):
            begin = i * size
            end = begin + size
            parts.append(board[begin:end])
            h_seps.append("-" * 3)

        first = True
        while len(parts) > 0:
            part = parts.pop()

            if first is False:
                print("|".join(h_seps))

            first = False
            print(" " + " | ".join(part))

    display_board(["O", "O", "X", "X", "X", "O", "X", "O", "X"])
</code>```

Body:
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

 X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X

I wrote this function:

def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

But i get this print out when i call the function with the given list:

test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)

Output:

 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")

Body:
a longer version of the solution that can handle size of board greater than 3

    def display_board(board, size=3):
        parts = []
        h_seps = []
        for i in range(size):
            begin = i * size
            end = begin + size
            parts.append(board[begin:end])
            h_seps.append("-" * 3)

        first = True
        while len(parts) > 0:
            part = parts.pop()

            if first is False:
                print("|".join(h_seps))

            first = False
            print(" " + " | ".join(part))

    display_board(["O", "O", "X", "X", "X", "O", "X", "O", "X"])


问:
Creating and saving Visio 2010 stencils using C#
We need to create a Visio 2010 stencil in code, using the .NET Freamework and C#.

The idea is like this:

We have our app, that is used by the app user, and then we have the workflow designer, which user Visio which is installed on another machine.

So we have two different people and two different machines. Lets say that, for this discussion, the application is an organizational structure app, that its object model comprises of various types, including User, Group, Developer, Administrator etc..

I want to add functionality to the app that would allow the app user to take these types and create a stencil from it, saved in a .vss file which is the format Visio uses for stencils. Then, the Visio user can take this vss file and add it to the document he's working on. The idea behind all this is that the app user can add user types any time, say 'Power User', which makes all this process dynamic.

Now, the machine where the application is installed doesn't have Visio installed, which might be important, i guess, in terms of what assemblies related to visio programming can be referenced from the app.

Can this be achived?

Thanks,

Avi

答:
If you want to create a Visio stencil on a machine where you can't use the Visio API (i.e. where Visio is not installed or in a server scenario) you can create a Visio XML file. If you use the file extension VSX then Visio will treat it as a stencil. Creating shapes in a Visio XML file may be much more complicated than creating shapes using the API because you will have manage many things yourself which Visio normally takes care of such as collection IDs, formula evaluation, connection creation, etc.

This approach assumes the definition of the geometry or image to use the shapes is predefined and accessible from your stencil generation code. If the user creating the stencil needs to specify the geometry then you may need to integrate some drawing tool. Visio may be that tool or you could investigate other drawing tools which can create a file which Visio can read, e.g. SVG.


答:
If you want pythonic-one-liner, then here you go</p>

```<code>def display_board(board):
    def display_board(board):
        for i in range(3,-1,-1): print(' | '.join(board[i*3:(i+1)*3]),'\n--|---|---' if 0 < i < 3 else '' )

test_board = ['1','2','3','4','5','6','7','8','9']
display_board(test_board)
</code>```

Title: How to reverse the index value in Python using for loop with a given list

Body:
If you want pythonic-one-liner, then here you go

def display_board(board):
    def display_board(board):
        for i in range(3,-1,-1): print(' | '.join(board[i*3:(i+1)*3]),'\n--|---|---' if 0 < i < 3 else '' )

test_board = ['1','2','3','4','5','6','7','8','9']
display_board(test_board)


问:
CRUD: using mat-Dialog as UI
I'm having a list of a playlist using mat-card and I'm getting my data from an array list inside my PlaylistComponent

What I'm trying to do is to add another playlist that's why I added a new playlist button that will display a dialog

I've added a playlist service that contained my form group.

My problem is that I'm new and I got lost with the architecture of the program.
do I have to use two-way binding or do I have to find a way to implement it in my dialog component

if someone is familiar with this technique please give me an insight.

答:
Your question is asking a lot and you don't give the underlying code so I am going to give an outline and point you to the documentation to follow for your specific implementation.

Basically you take the data from the form and pass it in mat-dialog-close.  When you open the dialog from your playlist component you also subscribe to the afterClosed of the dialog.  In this subscribe, you will get the data back from the mat-dialog-close.  You then can push that data into your existing array.

The first example of mat-dialog in the documentation handles a form and returning the data Dialog | Angular Material

Title: CRUD: using mat-Dialog as UI


问:
Subsetting out rows using pandas
I have two sets of dataframes: datamax, datamax2015 and datamin, datamin2015.

Snippet of data:

```<code>print(datamax.head())
print(datamin.head())
print(datamax2015.head())
print(datamin2015.head())

Date           ID Element  Data_Value
0  2005-01-01  USW00094889    TMAX         156
1  2005-01-02  USW00094889    TMAX         139
2  2005-01-03  USW00094889    TMAX         133
3  2005-01-04  USW00094889    TMAX          39
4  2005-01-05  USW00094889    TMAX          33
         Date           ID Element  Data_Value
0  2005-01-01  USC00200032    TMIN         -56
1  2005-01-02  USC00200032    TMIN         -56
2  2005-01-03  USC00200032    TMIN           0
3  2005-01-04  USC00200032    TMIN         -39
4  2005-01-05  USC00200032    TMIN         -94
         Date           ID Element  Data_Value
0  2015-01-01  USW00094889    TMAX          11
1  2015-01-02  USW00094889    TMAX          39
2  2015-01-03  USW00014853    TMAX          39
3  2015-01-04  USW00094889    TMAX          44
4  2015-01-05  USW00094889    TMAX          28
         Date           ID Element  Data_Value
0  2015-01-01  USC00200032    TMIN        -133
1  2015-01-02  USC00200032    TMIN        -122
2  2015-01-03  USC00200032    TMIN         -67
3  2015-01-04  USC00200032    TMIN         -88
4  2015-01-05  USC00200032    TMIN        -155
</code>```

For datamax, datamax2015, I want to compare their Data_Value columns and create a dataframe of entries in datamax2015 whose Data_Value is greater than all entries in datamax for the same day of the year. Thus, the expected output should be a dataframe with rows from 2015-01-01 to 2015-12-31 but with dates only where the values in the Data_Value column are greater than those in the Data_Value column of the datamax dataframe.

i.e 4 rows and anything from 1 to 364 columns depending on the condition above.

I want the converse (min) for the datamin and datamin2015 dataframes.

I have tried the following code:

```<code>upper = []
for row in datamax.iterrows():
    for j in datamax2015["Data_Value"]:
        if j > row["Data_Value"]:
            upper.append(row)
lower = []
for row in datamin.iterrows():
    for j in datamin2015["Data_Value"]:
        if j < row["Data_Value"]:
            lower.append(row)
</code>```

Could anyone give me a helping hand as to where I am going wrong?

答:
This code does what you want for the datamin. Try to adapt it to the datamax symmetric case as well - leave a comment if you have trouble and happy to help further.

Create Data

```<code>from datetime import datetime
import pandas as pd

datamin = pd.DataFrame({"date": pd.date_range(start=datetime(2005, 1, 1), end=datetime(2015, 12, 31)), "Data_Value": 1})
datamin["day_of_year"] = datamin["date"].dt.dayofyear
# Set the value for the 4th day of the year higher in order for the desired result to be non-empty
datamin.loc[datamin["day_of_year"]==4, "Data_Value"] = 2

datamin2015 = pd.DataFrame({"date": pd.date_range(start=datetime(2015, 1, 1), end=datetime(2015, 12, 31)), "Data_Value": 2})
datamin2015["day_of_year"] = datamin["date"].dt.dayofyear
# Set the value for the 4th day of the year lower in order for the desired result to be non-empty
datamin2015.loc[3, "Data_Value"] = 1
</code>```

The solution

```<code>df1 = datamin.groupby("day_of_year").agg({"Data_Value": "min"})
df2 = datamin2015.join(df1, on="day_of_year", how="left", lsuffix="2015")
lower = df2.loc[df2["Data_Value2015"]<df2["Data_Value"]]
lower
</code>```

We group the datamin by day of year to find the min across all the years for each day of the year (using .dt.dayofyear). Then we join that with datamin2015 and finally can then compare the Data_Value2015 with Data_Value in order to find the indexes of the rows where the Data_Value in 2015 was less than the minimum across all same days of the year in datamin.

In the example above lower has 1 row by the way I set up the dataframes.

Title: Subsetting out rows using pandas

Body:
I have two sets of dataframes: datamax, datamax2015 and datamin, datamin2015.

Snippet of data:

print(datamax.head())
print(datamin.head())
print(datamax2015.head())
print(datamin2015.head())

Date           ID Element  Data_Value
0  2005-01-01  USW00094889    TMAX         156
1  2005-01-02  USW00094889    TMAX         139
2  2005-01-03  USW00094889    TMAX         133
3  2005-01-04  USW00094889    TMAX          39
4  2005-01-05  USW00094889    TMAX          33
         Date           ID Element  Data_Value
0  2005-01-01  USC00200032    TMIN         -56
1  2005-01-02  USC00200032    TMIN         -56
2  2005-01-03  USC00200032    TMIN           0
3  2005-01-04  USC00200032    TMIN         -39
4  2005-01-05  USC00200032    TMIN         -94
         Date           ID Element  Data_Value
0  2015-01-01  USW00094889    TMAX          11
1  2015-01-02  USW00094889    TMAX          39
2  2015-01-03  USW00014853    TMAX          39
3  2015-01-04  USW00094889    TMAX          44
4  2015-01-05  USW00094889    TMAX          28
         Date           ID Element  Data_Value
0  2015-01-01  USC00200032    TMIN        -133
1  2015-01-02  USC00200032    TMIN        -122
2  2015-01-03  USC00200032    TMIN         -67
3  2015-01-04  USC00200032    TMIN         -88
4  2015-01-05  USC00200032    TMIN        -155

For datamax, datamax2015, I want to compare their Data_Value columns and create a dataframe of entries in datamax2015 whose Data_Value is greater than all entries in datamax for the same day of the year. Thus, the expected output should be a dataframe with rows from 2015-01-01 to 2015-12-31 but with dates only where the values in the Data_Value column are greater than those in the Data_Value column of the datamax dataframe.

i.e 4 rows and anything from 1 to 364 columns depending on the condition above.

I want the converse (min) for the datamin and datamin2015 dataframes.

I have tried the following code:

upper = []
for row in datamax.iterrows():
    for j in datamax2015["Data_Value"]:
        if j > row["Data_Value"]:
            upper.append(row)
lower = []
for row in datamin.iterrows():
    for j in datamin2015["Data_Value"]:
        if j < row["Data_Value"]:
            lower.append(row)

Could anyone give me a helping hand as to where I am going wrong?

Body:
This code does what you want for the datamin. Try to adapt it to the datamax symmetric case as well - leave a comment if you have trouble and happy to help further.

Create Data

from datetime import datetime
import pandas as pd

datamin = pd.DataFrame({"date": pd.date_range(start=datetime(2005, 1, 1), end=datetime(2015, 12, 31)), "Data_Value": 1})
datamin["day_of_year"] = datamin["date"].dt.dayofyear
# Set the value for the 4th day of the year higher in order for the desired result to be non-empty
datamin.loc[datamin["day_of_year"]==4, "Data_Value"] = 2

datamin2015 = pd.DataFrame({"date": pd.date_range(start=datetime(2015, 1, 1), end=datetime(2015, 12, 31)), "Data_Value": 2})
datamin2015["day_of_year"] = datamin["date"].dt.dayofyear
# Set the value for the 4th day of the year lower in order for the desired result to be non-empty
datamin2015.loc[3, "Data_Value"] = 1

The solution

df1 = datamin.groupby("day_of_year").agg({"Data_Value": "min"})
df2 = datamin2015.join(df1, on="day_of_year", how="left", lsuffix="2015")
lower = df2.loc[df2["Data_Value2015"]<df2["Data_Value"]]
lower

We group the datamin by day of year to find the min across all the years for each day of the year (using .dt.dayofyear). Then we join that with datamin2015 and finally can then compare the Data_Value2015 with Data_Value in order to find the indexes of the rows where the Data_Value in 2015 was less than the minimum across all same days of the year in datamin.

In the example above lower has 1 row by the way I set up the dataframes.


问:
Deploy code directly to AWS EC2 instance using Github Actions
As the title says I am trying to deploy my Laravel-Angular application directly from Github to AWS EC2 instance using Github Actions.

In my application there are 3 Angular 8+ projects which are needed to be build before deployment. Where as laravel does not need to be build.

The solutions that are available suggests to use AWS Elastic Beanstalk to deploy code. But, if that is to be done how to attach an elastic beanstalk to an existing instance is not clear enough.

Is there a way to deploy code to AWS EC2 without using Elastic Beanstalk?

Here is my Github Actions build.yml :

```<code>name: Build Develop Branch

on:
  push:
    branches: [ develop ]
  pull_request:
    branches: [ develop ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
    - name: Code Checkout
      uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - name: App 1 npm install
      run: npm install
      working-directory: angular-app-1
    - name: App 1 Build
      run: npm run build:staging
      working-directory: angular-app-1
    - name: App 2 npm install
      run: npm install
      working-directory: angular-app-2
    - name: App 2 Build
      run: node node_modules/@angular/cli/bin/ng build --configuration=staging
      working-directory: angular-app-2
    - name: App 3 npm install
      run: npm install
      working-directory: angular-app-3
    - name: App 3 Build
      run: node node_modules/@angular/cli/bin/ng build --configuration=staging
      working-directory: angular-app-3
</code>```

答:
Real final edit

A year later, I finally got around to making the tutorial: https://github.com/Andrew-Chen-Wang/cookiecutter-django-ec2-github.

I found a Medium tutorial that also deserves some light if anyone wants to use Code Pipeline (there's a couple of differences; I store my files on GitHub while the Medium tutorial is on S3. I create a custom VPC that the other author doesn't).

Earlier final edit

AWS has finally made a neat tutorial for CodeDeploy w/ GitHub repository: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-github-prerequisites.html take a look there and enjoy :)

Like the ECS tutorial, we're using Parameter Store to store our secrets. The way AWS previous wanted us to grab secrets was via a script in a bash script: https://aws.amazon.com/blogs/mt/use-parameter-store-to-securely-access-secrets-and-config-data-in-aws-codedeploy/

For example:

```<code>password=$(aws ssm get-parameters --region us-east-1 --names MySecureSQLPassword --with-decryption --query Parameters[0].Value)
password=`echo $password | sed -e 's/^"//' -e 's/"$//'`
mysqladmin -u root password $password
</code>```

New edit (24 December 2020): I think I've nailed it. Below I pointed to Donate Anything for AWS ECS. I've moved to a self deploying setting. If you take a look at bin/scripts, I'm taking advantage of supervisord and gunicorn (for Python web development). But in context of EC2, you can simply point your AppSpec.yml to those scripts! Hope that helps everyone!

Before I start:

This is not a full answer. Not a complete walkthrough, but a lot of hints and some code that will help you with setting up certain AWS stuff like ALB and your files in your repo for this to work. This answer is more like several clues jumbled together from my sprint run trying to make ECS work last night.

I also don't have enough points to neither comment nor chat soo... here's the best thing I can offer.

Quick links (you should probably just skip these two points, though):

Check this out: https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-ec2-configure.html

I don't have enough points to comment or chat... This won't be a full answer, as well, though, as I'm trying to first finish an ECS deploy from GH before moving on to EC2 from GH. Anyhow...

One last edit: this will sound like a marketing ploy but a correct implementation with GitHub actions and workflow_dispatch is located at Donate Anything's GitHub repository. You'll find the same ECS work located below in there. Do note that I changed my GitHub action to use Docker Hub since it was free (and to me cheaper if you're going to use ECS since AWS ECR is expensive).

Edit: The ECS deployment works now. Will start working on the EC2 deployment soon.

Edit 2: I added Donate Anything repo. Additionally, I'm not sure if direct EC2 deployment, at least for me, is viable since install scripts would kinda be weird. However, I still haven't found the time to get to EC2. Again, if anyone is willing to share their time, please do so and contribute!

I do want to warn everyone that SECURITY GROUPS are very important. That clogged me for a long time, so make sure you get them right. In the ECS tutorial, I teach you how I do it.

Full non-full answer:

I'm working on this issue right now in this repo and another for ECS here using GitHub actions. I haven't started too far on the EC2 one, but the basic rundown for testing is this:

CRUCIAL

You need to try and deploy from the AWS CLI first. This is because AWS Actions does not have a dedicated action for deploying to EC2 yet.

Write down each of these statements. We're going to need them later for the GitHub action.

Some hints when testing this AWS setup:

Before using CodeDeploy, you need an EC2 instance, an Application Load Balancer (you'll find it under Elastic Load Balancer), and a target group (which you create DURING the ALB setup). Go to target groups, right click on the group, and register your instance.

To deploy from CodeDeploy, create a new application. Create a new deployment group. I think, for your setup, you should do the in-place deployment type rather than the Blue/Green deployment type.

Finally, testing on the CLI, you should run the code you see here: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-wordpress-deploy-application.html#tutorials-wordpress-deploy-application-create-deployment-cli

Do note, you may want to start from here (using S3 as a location to store your latest code. You can delete it afterwards anyways, as I believe DELETE requests don't incur charges): https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-wordpress-upload-application.html I personally don't know if that GitHub OAuth integration works. I tried once before (very amateur though, i.e. no clue what I was doing before) and nothing happened, soo... I'd just stick with that tutorial.

How your test rundown will look like:

For me, for my ECS repo, I just went a full 10 hours straight trying to configure everything properly step by step like the GitHub action. For you, you should do the same. Imagine you're the code: figure out where you need to start from.

Aha! I should probably figure out CodeDeploy first. Let's right an appspec.yaml file first! The appspec file is how CodeDeploy will work on the hooks for everything. Unfortunately, I'm current going through that problem here but that's because the EC2 and ECS syntax for AppSpec files are different. Luckily, EC2 doesn't have any special areas. Just get your files and hooks right. An example from my test:

```<code>version: 0.0
os: linux

files:
  - source: /
    destination: /code

hooks:
  BeforeInstall:
    - location: aws_scripts/install_dependencies
      timeout: 300
      runas: root
  ApplicationStop:
    - location: aws_scripts/start_server
      runas: root
</code>```

The GitHub action:

What you'll need at minimum:

```<code>jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        # TODO Change your AWS region here!
        aws-region: us-east-2
</code>```

The checking out of code is necessary to... well... get the code.

For the configuration of AWS credentials, you'll want to add AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to your GitHub secrets with a proper IAM credential. For this, I believe the only IAM role needed is for full CodeDeploy stuff.

Deploying the code:

This is when that test code that you should've tried before reaching this step is for. Now that your workflow is setup, let's paste the code from the CLI into your action.

```<code>
    - name: Deploying with CodeDeploy
      id: a-task
      env:
        an-environment-variable: anything you want
      run: |
        echo "Your CLI code should be placed here"
</code>```

Sorry if this was confusing, not what you're looking for, or wanted a complete tutorial. I, too, haven't actually gotten this to work, but it's also been awhile since I last tried, and the last time I tried, I didn't even know what an EC2 instance was... I just did a standalone EC2 instance and used rsync to transfer my files. Hopefully what I've written was several clues that can guide you very easily to a solution.

If you got it to work, please share it on here: https://github.com/Andrew-Chen-Wang/cookiecutter-django-ec2-gh-action so that no one else has to suffer the pain of AWS deployment...

Body:
As the title says I am trying to deploy my Laravel-Angular application directly from Github to AWS EC2 instance using Github Actions.

In my application there are 3 Angular 8+ projects which are needed to be build before deployment. Where as laravel does not need to be build.

The solutions that are available suggests to use AWS Elastic Beanstalk to deploy code. But, if that is to be done how to attach an elastic beanstalk to an existing instance is not clear enough.

Is there a way to deploy code to AWS EC2 without using Elastic Beanstalk?

Here is my Github Actions build.yml :

name: Build Develop Branch

on:
  push:
    branches: [ develop ]
  pull_request:
    branches: [ develop ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
    - name: Code Checkout
      uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - name: App 1 npm install
      run: npm install
      working-directory: angular-app-1
    - name: App 1 Build
      run: npm run build:staging
      working-directory: angular-app-1
    - name: App 2 npm install
      run: npm install
      working-directory: angular-app-2
    - name: App 2 Build
      run: node node_modules/@angular/cli/bin/ng build --configuration=staging
      working-directory: angular-app-2
    - name: App 3 npm install
      run: npm install
      working-directory: angular-app-3
    - name: App 3 Build
      run: node node_modules/@angular/cli/bin/ng build --configuration=staging
      working-directory: angular-app-3

Body:
Real final edit

A year later, I finally got around to making the tutorial: https://github.com/Andrew-Chen-Wang/cookiecutter-django-ec2-github.

I found a Medium tutorial that also deserves some light if anyone wants to use Code Pipeline (there's a couple of differences; I store my files on GitHub while the Medium tutorial is on S3. I create a custom VPC that the other author doesn't).

Earlier final edit

AWS has finally made a neat tutorial for CodeDeploy w/ GitHub repository: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-github-prerequisites.html take a look there and enjoy :)

Like the ECS tutorial, we're using Parameter Store to store our secrets. The way AWS previous wanted us to grab secrets was via a script in a bash script: https://aws.amazon.com/blogs/mt/use-parameter-store-to-securely-access-secrets-and-config-data-in-aws-codedeploy/

For example:

password=$(aws ssm get-parameters --region us-east-1 --names MySecureSQLPassword --with-decryption --query Parameters[0].Value)
password=`echo $password | sed -e 's/^"//' -e 's/"$//'`
mysqladmin -u root password $password

New edit (24 December 2020): I think I've nailed it. Below I pointed to Donate Anything for AWS ECS. I've moved to a self deploying setting. If you take a look at bin/scripts, I'm taking advantage of supervisord and gunicorn (for Python web development). But in context of EC2, you can simply point your AppSpec.yml to those scripts! Hope that helps everyone!

Before I start:

This is not a full answer. Not a complete walkthrough, but a lot of hints and some code that will help you with setting up certain AWS stuff like ALB and your files in your repo for this to work. This answer is more like several clues jumbled together from my sprint run trying to make ECS work last night.

I also don't have enough points to neither comment nor chat soo... here's the best thing I can offer.

Quick links (you should probably just skip these two points, though):

Check this out: https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-ec2-configure.html

I don't have enough points to comment or chat... This won't be a full answer, as well, though, as I'm trying to first finish an ECS deploy from GH before moving on to EC2 from GH. Anyhow...

One last edit: this will sound like a marketing ploy but a correct implementation with GitHub actions and workflow_dispatch is located at Donate Anything's GitHub repository. You'll find the same ECS work located below in there. Do note that I changed my GitHub action to use Docker Hub since it was free (and to me cheaper if you're going to use ECS since AWS ECR is expensive).

Edit: The ECS deployment works now. Will start working on the EC2 deployment soon.

Edit 2: I added Donate Anything repo. Additionally, I'm not sure if direct EC2 deployment, at least for me, is viable since install scripts would kinda be weird. However, I still haven't found the time to get to EC2. Again, if anyone is willing to share their time, please do so and contribute!

I do want to warn everyone that SECURITY GROUPS are very important. That clogged me for a long time, so make sure you get them right. In the ECS tutorial, I teach you how I do it.

Full non-full answer:

I'm working on this issue right now in this repo and another for ECS here using GitHub actions. I haven't started too far on the EC2 one, but the basic rundown for testing is this:

CRUCIAL

You need to try and deploy from the AWS CLI first. This is because AWS Actions does not have a dedicated action for deploying to EC2 yet.

Write down each of these statements. We're going to need them later for the GitHub action.

Some hints when testing this AWS setup:

Before using CodeDeploy, you need an EC2 instance, an Application Load Balancer (you'll find it under Elastic Load Balancer), and a target group (which you create DURING the ALB setup). Go to target groups, right click on the group, and register your instance.

To deploy from CodeDeploy, create a new application. Create a new deployment group. I think, for your setup, you should do the in-place deployment type rather than the Blue/Green deployment type.

Finally, testing on the CLI, you should run the code you see here: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-wordpress-deploy-application.html#tutorials-wordpress-deploy-application-create-deployment-cli

Do note, you may want to start from here (using S3 as a location to store your latest code. You can delete it afterwards anyways, as I believe DELETE requests don't incur charges): https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-wordpress-upload-application.html I personally don't know if that GitHub OAuth integration works. I tried once before (very amateur though, i.e. no clue what I was doing before) and nothing happened, soo... I'd just stick with that tutorial.

How your test rundown will look like:

For me, for my ECS repo, I just went a full 10 hours straight trying to configure everything properly step by step like the GitHub action. For you, you should do the same. Imagine you're the code: figure out where you need to start from.

Aha! I should probably figure out CodeDeploy first. Let's right an appspec.yaml file first! The appspec file is how CodeDeploy will work on the hooks for everything. Unfortunately, I'm current going through that problem here but that's because the EC2 and ECS syntax for AppSpec files are different. Luckily, EC2 doesn't have any special areas. Just get your files and hooks right. An example from my test:

version: 0.0
os: linux

files:
  - source: /
    destination: /code

hooks:
  BeforeInstall:
    - location: aws_scripts/install_dependencies
      timeout: 300
      runas: root
  ApplicationStop:
    - location: aws_scripts/start_server
      runas: root

The GitHub action:

What you'll need at minimum:

jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        # TODO Change your AWS region here!
        aws-region: us-east-2

The checking out of code is necessary to... well... get the code.

For the configuration of AWS credentials, you'll want to add AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to your GitHub secrets with a proper IAM credential. For this, I believe the only IAM role needed is for full CodeDeploy stuff.

Deploying the code:

This is when that test code that you should've tried before reaching this step is for. Now that your workflow is setup, let's paste the code from the CLI into your action.

    - name: Deploying with CodeDeploy
      id: a-task
      env:
        an-environment-variable: anything you want
      run: |
        echo "Your CLI code should be placed here"

Sorry if this was confusing, not what you're looking for, or wanted a complete tutorial. I, too, haven't actually gotten this to work, but it's also been awhile since I last tried, and the last time I tried, I didn't even know what an EC2 instance was... I just did a standalone EC2 instance and used rsync to transfer my files. Hopefully what I've written was several clues that can guide you very easily to a solution.

If you got it to work, please share it on here: https://github.com/Andrew-Chen-Wang/cookiecutter-django-ec2-gh-action so that no one else has to suffer the pain of AWS deployment...


问:
How to select all values that a not a number using SQL?
Due to an earlier error, I ended up with letters and symbols in places where I should have had integers and floars. At this time, I don't know the extent of the problem and working to correct the code as we move forward.

As of right now when I run SELECT distinct col1 from table; I get integers, floats, symbols and letters. A few million of them.

How can I update the SQL to exclude all numbers? In other words, show me only letters and symbols.

答:
You can use the GLOB operator:

```<code>select col1
from tablename
where col1 GLOB '*[^0-9]*'
</code>```

This will return all values of col1 that contain any character different than a digit.

You may change it to include '.' in the list of chars:

```<code>where col1 GLOB '*[^0-9.]*'
</code>```

See the demo.

If what you want is values that do not contain any digits then use this:

```<code>select col1
from tablename
where col1 not GLOB '*[0-9]*'
</code>```

See the demo.

Body:
You can use the GLOB operator:

select col1
from tablename
where col1 GLOB '*[^0-9]*'

This will return all values of col1 that contain any character different than a digit.

You may change it to include '.' in the list of chars:

where col1 GLOB '*[^0-9.]*'

See the demo.

If what you want is values that do not contain any digits then use this:

select col1
from tablename
where col1 not GLOB '*[0-9]*'

See the demo.


问:
what terminates a while loop when its expression is a conditional expression
the title says it all

in a loop likes this written in C

```<code>while(first_statement ? second_statement : third_statement)
</code>```

how can a loop like this be terminated?

答:
A loop using while(statement1 ? statement2 : statement3) will be terminated if at a time when the condition is tested, either of the following apply:

statement1 evaluates to non-zero and statement2 evaluates to zero

statement1 evaluates to zero and statement3 evaluates to zero

(It can of course also be terminated by things such as a break statement or a return from the function that contains it.)

Body:
the title says it all

in a loop likes this written in C

while(first_statement ? second_statement : third_statement)

how can a loop like this be terminated?


问:
Debounce or throttle event handler in Google Apps Script
I'm looking for a neat solution to debounce or throttle a webhook call used in a Google Sheets Apps Script handler. Creating a simple trigger like onEdit or an "installable trigger" for other changes is straight forward but both will call the handler for every single change. If someone is editing the sheet and updates many rows over a few seconds, I want to fire only one event and not flood my webhook service. The conventional pattern for this in Javascript is to use setTimeout and clearTimeout to ensure the body of the event handler is called only once but setTimeout is not available in the Google Apps Script runtime.

答:
Here is my working solution. It uses Utilities.sleep() to wait 10 seconds and check with ScriptProperties to see if this event is the last one called during that time.

Sharing for others to find, if you're looking to solve a similar problem:

/*

  Set the following project properties (File -> Project properties):

  SheetsToWatch: comma separated list of sheets to watch for events
  WebhookUrl: URL of web service to POST update to
  WebhookToken: Authorization bearer token for POST request
  SendLastValue: [optional] set if you wish last value in updated sheet to be posted

  Then create the "installable trigger" (Edit -> Current project's triggers -> Add Trigger):

  Choose which function to run: "handleChangeOrEdit"
  Select event type: "On change" or "On edit"

  A simple trigger like `onEdit` won't work have the privileges to call `UrlFetchApp.fetch`.

 */

function handleChangeOrEdit(event) {
  var sheetId = event.source.getId();
  var sheetUrl = event.source.getUrl();
  var sheetName = (event.range ? event.range.getSheet() : SpreadsheetApp.getActiveSheet()).getName();

  // Trigger only on those sheets we're configured to watch (or all if not specified)
  var sheetsToWatch = PropertiesService.getScriptProperties().getProperty("SheetsToWatch");
  if (sheetsToWatch && sheetsToWatch.split(",").indexOf(sheetName) == -1) {
    return;
  }

  var eventId = Utilities.getUuid();
  setEventTriggerWinner(eventId);
  // OPTIONAL: You might want to save values from each edit here, to be dealt with by the "winner"
  Utilities.sleep(10000);   // Wait to see if another Change/Edit event is triggered
  if (getEventTriggerWinner() == eventId) {
    Logger.log(`Trigger Winner: ${eventId}`);
    callWebhook({eventId, sheetId, sheetUrl, sheetName});
  }
}

function setEventTriggerWinner(value) {
  // Wrapping setProperty in a Lock probably isn't necessary since a set should be atomic
  // but just in case...
  var lock = LockService.getScriptLock();
  if (lock.tryLock(5000)) {
    PropertiesService.getScriptProperties().setProperty("eventTriggerWinner", value);
    lock.releaseLock();
  }
}

function getEventTriggerWinner() {
  return PropertiesService.getScriptProperties().getProperty("eventTriggerWinner");
}

function callWebhook(data) {
  var url = PropertiesService.getScriptProperties().getProperty("WebhookUrl");
  var token = PropertiesService.getScriptProperties().getProperty("WebhookToken");
  UrlFetchApp.fetch(url, {
    headers: {"Authorization": `Bearer ${token}`},
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(data)
  });
}

```


问:
Redux store element seems to be null or undefined
I refactored my application to use Redux.
On first load it seems to work, I can click on "About" and clearly the action is working correctly, elements are not null.

```<code>Reducer:
Object { listItems: (2) […], currentItem: null, currentDisplay: "board" }

Object { type: "@@redux/INITk.b.x.9.2.l" }
</code>```

So it seems like it's working.
But when I click on "Shop" or an item, I will get error:

```<code>TypeError: this.props.listItems is undefined
</code>```

or

```<code>TypeError: this.props.currentItem is undefined
</code>```

So it seems like as if the store would be empty, but it's not true, it's not empty.

This is my mapStateToProps and export sentence:

```<code>function mapStateToProps(state) {
    return {
      listItems: state.listItems,
      currentItem: state.currentItem,
      currentDisplay: state.currentDisplay,
    }
  }

export default connect(mapStateToProps)(Thumbnails);
</code>```

This is in Thumbnails.js, which must run when the page is loaded, because the items are displayed.
I run out of ideas. I wrote a lot of console.log and it really seems that I'm able to update store, there doesn't seem to be a problem with that.

This is code on Github: https://github.com/imestin/IPFS-Store
Error is in Thumbnails and Item

Please help!
Thank you!

答:
You are mutating your redux state, you need to copy old state and then update it. For eg:

```<code>case "NAV":
            return {
                ...state,
                currentDisplay: action.display,
            };case "NAV":
            return {
                ...state,
                currentDisplay: action.display,
            };
</code>```

Here is your complete reducer function:

```<code>function reducer(state = initialState, action) {
    console.log("Reducer: ", state, action);
    //  Surely item numbers gets down here. action.item is correct.

    switch (action.type) {
        case "NAV":
            return {
                ...state,
                currentDisplay: action.display,
            };
        case "ITEM_CLICKED":
            return {
                ...state,
                currentItem: action.item,
            };
        case "BUY":
            return {
                ...state,
                buy: "Not specified",
            };
        default:
            return state;
    }
}
</code>```

Body:
I refactored my application to use Redux.
On first load it seems to work, I can click on "About" and clearly the action is working correctly, elements are not null.

Reducer:
Object { listItems: (2) […], currentItem: null, currentDisplay: "board" }

Object { type: "@@redux/INITk.b.x.9.2.l" }

So it seems like it's working.
But when I click on "Shop" or an item, I will get error:

TypeError: this.props.listItems is undefined

or

TypeError: this.props.currentItem is undefined

So it seems like as if the store would be empty, but it's not true, it's not empty.

This is my mapStateToProps and export sentence:

function mapStateToProps(state) {
    return {
      listItems: state.listItems,
      currentItem: state.currentItem,
      currentDisplay: state.currentDisplay,
    }
  }

export default connect(mapStateToProps)(Thumbnails);

This is in Thumbnails.js, which must run when the page is loaded, because the items are displayed.
I run out of ideas. I wrote a lot of console.log and it really seems that I'm able to update store, there doesn't seem to be a problem with that.

This is code on Github: https://github.com/imestin/IPFS-Store
Error is in Thumbnails and Item

Please help!
Thank you!

Body:
You are mutating your redux state, you need to copy old state and then update it. For eg:

case "NAV":
            return {
                ...state,
                currentDisplay: action.display,
            };case "NAV":
            return {
                ...state,
                currentDisplay: action.display,
            };

Here is your complete reducer function:

function reducer(state = initialState, action) {
    console.log("Reducer: ", state, action);
    //  Surely item numbers gets down here. action.item is correct.

    switch (action.type) {
        case "NAV":
            return {
                ...state,
                currentDisplay: action.display,
            };
        case "ITEM_CLICKED":
            return {
                ...state,
                currentItem: action.item,
            };
        case "BUY":
            return {
                ...state,
                buy: "Not specified",
            };
        default:
            return state;
    }
}