问:
PL/SQL: Run package after checking all rows in trigger
I have an inventory table with expected quantities and actually received quantities. Let's say inv.q_ex and inv.q_rd.

The INSERT to the table has a positive value in q_ex and a zero in q_rd because it hasn't arrived yet. I'd like to run a package when I detect that the q_rd value changes from 0 to something else, indicating it's been received and stored.

Making a trigger to detect after update and checking each row is easy, but I'm not sure how to ensure it only runs once.

The skeleton is:

```<code>CREATE OR REPLACE TRIGGER example
     AFTER UPDATE ON inv
          FOR EACH ROW
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         pkg.proc();
                    END IF;
               END;
/
</code>```

The problem I see is I only want it to run one time. I just need to identify when it needs to be executed. Ideally, on the first row where my condition is met, I would exit the loop (seems like a waste to keep checking when I already know I need to execute) and call my procedure.

I couldn't find a way to "exit" the for each and treat it as a normal AFTER UPDATE, so then I tried using both BEFORE UPDATE and AFTER UPDATE. The BEFORE portion would check each row and update a boolean. The AFTER portion would wait for that to happen and if it was true, call the procedure.

```<code>CREATE OR REPLACE TRIGGER example
     BEFORE UPDATE ON inv
          FOR EACH ROW
               DECLARE
                    shouldExecute BOOLEAN;
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         shouldExecute := TRUE;
                    END IF;
               END;
     AFTER UPDATE ON inv
          BEGIN
               IF shouldExecute THEN
                    pkg.proc();
               END IF;
          END;
/
</code>```

I suspect this wouldn't work anyway because, according to the syntax, it redeclares the boolean variable on each row. I thought that maybe I could make it "global" but regardless, turns out I can't add both BEFORE and AFTER to the same trigger for some reason (unless I didn't research enough), so I broke it out into two triggers. The problem now is I can't share that boolean between the two triggers. Can I share the value, or am I going about this all wrong?

答: You need to do more research. The link above takes you to trigger discussion for Oracle 9. I hope you are not actually using that version; support ended in 2007. Since version 11g Oracle has provided "Compound Triggers" where you can fire the same trigger both Before and After for both statement and row level. Compound triggers do allow sharing variables between the different invocations.</p>

Body:
I have an inventory table with expected quantities and actually received quantities. Let's say inv.q_ex and inv.q_rd.

The INSERT to the table has a positive value in q_ex and a zero in q_rd because it hasn't arrived yet. I'd like to run a package when I detect that the q_rd value changes from 0 to something else, indicating it's been received and stored.

Making a trigger to detect after update and checking each row is easy, but I'm not sure how to ensure it only runs once.

The skeleton is:

CREATE OR REPLACE TRIGGER example
     AFTER UPDATE ON inv
          FOR EACH ROW
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         pkg.proc();
                    END IF;
               END;
/

The problem I see is I only want it to run one time. I just need to identify when it needs to be executed. Ideally, on the first row where my condition is met, I would exit the loop (seems like a waste to keep checking when I already know I need to execute) and call my procedure.

I couldn't find a way to "exit" the for each and treat it as a normal AFTER UPDATE, so then I tried using both BEFORE UPDATE and AFTER UPDATE. The BEFORE portion would check each row and update a boolean. The AFTER portion would wait for that to happen and if it was true, call the procedure.

CREATE OR REPLACE TRIGGER example
     BEFORE UPDATE ON inv
          FOR EACH ROW
               DECLARE
                    shouldExecute BOOLEAN;
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         shouldExecute := TRUE;
                    END IF;
               END;
     AFTER UPDATE ON inv
          BEGIN
               IF shouldExecute THEN
                    pkg.proc();
               END IF;
          END;
/

I suspect this wouldn't work anyway because, according to the syntax, it redeclares the boolean variable on each row. I thought that maybe I could make it "global" but regardless, turns out I can't add both BEFORE and AFTER to the same trigger for some reason (unless I didn't research enough), so I broke it out into two triggers. The problem now is I can't share that boolean between the two triggers. Can I share the value, or am I going about this all wrong?


来源: stackexchange

问:
How to find all the colors between two colors?
I need to pick two colors, then find X colors (or tones) between them, each one separated with the same 'distance' of the other.

I still don't understand how colors are formed. Should I try using HSV, RGB, or hex?

答: I think your best option is to use a HSL representation. Then you can interpolate using the hue value. You will get better results than using a RGB interpolation.</p>

ContentLicense: CC BY-SA 3.0


问:
3-layer architecture. EF in presentation layer
I try to create 3-layer architecture application. There are 2 class library (data access, business logic)and asp.net MVC (presentation).
For DB connection   I use entity framework. In DataAccess I configured DatabaseContext my connection string store in web.config. If I try add raw in database from Presentation I get error

No Entity Framework provider found for the ADO.NET provider with
  invariant name 'System.Data.SqlClient'."

How I understand it is bad practice install EF in presentation level.I think about add reference System.Data.SqlClient but think it's bad practice too. Maybe someone met a similar problem. I'll be greateful for any help.

答:
If your sticking to a true three tier architecture and using interfaces and dependency injection between the layers then the problem is most likely that visual studio doesn't see that you're actually using the data layer and doesn't deploy the dependencies. I've studied this issue a few years back and it's a bit painful to resolve. I'm not absolutely sure if this is your problem due to the minimal information you provided but if it sounds like your problem, you can test by adding a hard dependency from the web to the data layer and see what happens. If that solves the error then there are a couple ways to fix the issue.

Being that the Web project is also considered the Composition Root, it needs to provide configuration to the data layer such as the connection string. So there's already some knowledge shared between the web and data layers. Creating truly separate layers is nearly if not impossible.

If adding a hard dependency fixes the problem, then you can create a static method just for this purpose and document the method so future developers won't try and remove it. The other is to modify the solution file to copy the target dll into the bin folder. This seems like a better fix but I remember that it often broke and I had to keep going back and adding the manual entry back to the solution, which was confusing when it broke.

I also found another stackoverflow discussion that covers this same topic:

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

ContentLicense: CC BY-SA 4.0


问:
How to write Perl modified content into a file in Python scripts?
My research data is not a normal file. The column number of each row may be different. I want to convert the "dat" file into "*.csv" file using Perl because it can run efficiently (I have poor experience in Python). Below is the script I ran. It works fine in Linux, but it does not output the context in Python scripts.

```<code>new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
perl -p -e 's/\\t\s+|\s+/,/g' $new_dat_file |perl -p -e 's/,FRAM/\\nFRAM/g' >  $new_csv_file
</code>```

Above codes work in Linux. I improved them in Python scripts. If I use below command

```<code>import os
new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g'
os.system(cmd)
</code>```

I can see the output correctly. However, if I modify cmd values like below to save the output into a csv file, but I got an empty file.

```<code>cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g' > " + new_csv_file
</code>```

How can I fix this issue? If I cannot do so, any other alternative way available? Any further suggestion would be highly appreciated.

BTW: partial data listed below

```<code>FRAM_#            0            0(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.008
FRAM_#          100           25(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.955
FRAM_#          200           50(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.993
FRAM_#          300           75(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.973
FRAM_#          400          100(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.988
FRAM_#          500          125(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.033
FRAM_#          600          150(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.032
FRAM_#          700          175(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.986
FRAM_#          800          200(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.061
FRAM_#          900          225(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.078
FRAM_#         1000          250(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.922
FRAM_#         1100          275(fs)  CN= 2 PRMRYTGT     14689      H      17402      O  1.257     15449      O  1.430
FRAM_#       303200        75800(fs)  CN= 0 PRMRYTGT_BD     14689      H
FRAM_#       921200       230300(fs)  CN= 1 PRMRYTGT_BD     14689      H        8375      O  1.062
FRAM_#      1078700       269675(fs)  CN= 1 PRMRYTGT_BD     14689      H       12971      O  1.507
FRAM_#     18203400      4550850(fs)  CN= 1 PRMRYTGT_BD     14689      H       16172      O  1.507
</code>```

I hope to get output like below:

```<code>FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430
</code>```

答:
I'm afraid your Perl scripting skills are a bit limited, too. Anyway, this is all easy enough to do natively in Python.

import re

new_dat_file = "14689_bondlength.prmfrm.dat"
new_csv_file = "14689_bondlength.prmfrm.csv"
with open(new_dat_file) as input, open(new_csv_file, 'w') as output:
    for line in input:
        line = line.rstrip('\n')
        line = re.sub(r'\\t\s+|\s+', ',', line)
        # line = line.replace(',FRAM', r'\\nFRAM')
        output.write(line + '\n')
```

<p>The double backslashes look fishy, but I assume that's really what you actually want. <code>\\t</code> is a backslash and a lowercase <code>t</code>, whereas <code>\t</code> represents a tab.</p>

<p>I updated this to chomp off the final newline, then put it back after the regex replace. With that, there's no need to put a newline before <code>FRAM</code>.</p>

<p>If you really, really wanted to use an external process, I'd go with</p>

```import subprocess

with open(new_dat_file) as input, open(new_csv_file, 'w') as output:
    subprocess.run(['perl', '-p', '-e', 's/\\t\s+|\s+/,/g; s/,FRAM/\\nFRAM/g'],
    stidin=input, stdout=output, check=True)
```

and maybe similarly to above, switch to perl -l to avoid having the newlines replaced so you have to put them back again.

Body:
My research data is not a normal file. The column number of each row may be different. I want to convert the "dat" file into "*.csv" file using Perl because it can run efficiently (I have poor experience in Python). Below is the script I ran. It works fine in Linux, but it does not output the context in Python scripts.

new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
perl -p -e 's/\\t\s+|\s+/,/g' $new_dat_file |perl -p -e 's/,FRAM/\\nFRAM/g' >  $new_csv_file

Above codes work in Linux. I improved them in Python scripts. If I use below command

import os
new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g'
os.system(cmd)

I can see the output correctly. However, if I modify cmd values like below to save the output into a csv file, but I got an empty file.

cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g' > " + new_csv_file

How can I fix this issue? If I cannot do so, any other alternative way available? Any further suggestion would be highly appreciated.

BTW: partial data listed below

FRAM_#            0            0(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.008
FRAM_#          100           25(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.955
FRAM_#          200           50(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.993
FRAM_#          300           75(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.973
FRAM_#          400          100(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.988
FRAM_#          500          125(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.033
FRAM_#          600          150(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.032
FRAM_#          700          175(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.986
FRAM_#          800          200(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.061
FRAM_#          900          225(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.078
FRAM_#         1000          250(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.922
FRAM_#         1100          275(fs)  CN= 2 PRMRYTGT     14689      H      17402      O  1.257     15449      O  1.430
FRAM_#       303200        75800(fs)  CN= 0 PRMRYTGT_BD     14689      H
FRAM_#       921200       230300(fs)  CN= 1 PRMRYTGT_BD     14689      H        8375      O  1.062
FRAM_#      1078700       269675(fs)  CN= 1 PRMRYTGT_BD     14689      H       12971      O  1.507
FRAM_#     18203400      4550850(fs)  CN= 1 PRMRYTGT_BD     14689      H       16172      O  1.507

I hope to get output like below:

FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430

Body:
I'm afraid your Perl scripting skills are a bit limited, too. Anyway, this is all easy enough to do natively in Python.

import re

new_dat_file = "14689_bondlength.prmfrm.dat"
new_csv_file = "14689_bondlength.prmfrm.csv"
with open(new_dat_file) as input, open(new_csv_file, 'w') as output:
    for line in input:
        line = line.rstrip('\n')
        line = re.sub(r'\\t\s+|\s+', ',', line)
        # line = line.replace(',FRAM', r'\\nFRAM')
        output.write(line + '\n')

The double backslashes look fishy, but I assume that's really what you actually want. \\t is a backslash and a lowercase t, whereas \t represents a tab.

I updated this to chomp off the final newline, then put it back after the regex replace. With that, there's no need to put a newline before FRAM.

If you really, really wanted to use an external process, I'd go with

import subprocess

with open(new_dat_file) as input, open(new_csv_file, 'w') as output:
    subprocess.run(['perl', '-p', '-e', 's/\\t\s+|\s+/,/g; s/,FRAM/\\nFRAM/g'],
    stidin=input, stdout=output, check=True)

and maybe similarly to above, switch to perl -l to avoid having the newlines replaced so you have to put them back again.


问:
Get a full solution for a conda environment
Let's say I have a simple conda environment

```<code>dependencies:
  - python
</code>```

How do I turn this into a fully specified environment?  I want to run the Solve step of conda and save the result, but not run any of the other steps yet.

I would prefer to avoid actually having to download and extract packages to do this.

I would also love to be able to do this from within Python without shelling out, but that's just an additional request.

答:
You can do,

```<code>conda create -n testenv python --dry-run
</code>```

to get the output and parse it or get the output as json using

```<code>conda create -n testenv python --dry-run --json
</code>```

Body:
Let's say I have a simple conda environment

dependencies:
  - python

How do I turn this into a fully specified environment?  I want to run the Solve step of conda and save the result, but not run any of the other steps yet.

I would prefer to avoid actually having to download and extract packages to do this.

I would also love to be able to do this from within Python without shelling out, but that's just an additional request.

Body:
You can do,

conda create -n testenv python --dry-run

to get the output and parse it or get the output as json using

conda create -n testenv python --dry-run --json


问:
parameters needed for connecting to aws rds instance via ssh
Does anyone know where to find the values needed for the parameters required for an ssh connection involving a bastion host and an AWS RDS instance?

I have listed what I have been able to find so far below:

SSH Hostname - Endpoint given for RDS instance in the AWS console

SSH Username - I'm seeing in tutorials all over the place it's ec2-user, should I also use this?

SSH password - do I need this, since I already have a .pem file for the key pair?
`

SSH Key File` - got this

MySQL Hostname - I'm not sure what to put for this.

MYSQL Server Port - 3306

Username - root

Password - not sure which password this is referring to

答:
First of all you're not SSHing into a Database, SSH is only for EC2 instances. The logical steps would be:

SSH from local computer to EC2 instance (optional depending on settings below)

Connect to the database using something like mysql -H (hostname) -u admin -p it will prompt for password.

If you want to connected to the DB directly, make sure you whitelist your IP on the security group for the DB. The security group by default will not allow you to connect to it directly, or anywhere by default.

If you want to connect to the DB from your bastion host, again, you'll need to whitelist the IP of the bastion host.

Security groups are basic ALLOW from IP on PORT. So for MySQL the port will be 3306.

In AWS, there's a ton of variables why this may be failing.

Are these resources in the same region?

Are these resources in the same subnet? Is the subnet private or public?

During the configuration of RDS, at least in the past, you could not set the security group at all during the configuration. You always had to remember to go back and click Modify, then go in and give it a security group.

The best practice here around security groups, is to

Create one for your bastion host instance, only allowing 22 to your home IP.

Create one for your RDS instance, allowing 3306 from the security group ID of your bastion host. That way you don't need to worry about your bastion host IP changing, any instance that has the bastion host security group will be able to access 3306 on this RDS.

Assign the security groups to the correct resources.

If you're still having problems, I can get much deeper on this.


问:
Javascript Pennies Rounding Mechanism to the nearest multiple of 5 cent
In the Rounding Mechanism exercise, the total amount of a bill which ends in 1, 2, 6 and 7 cent should be rounded down while the total bill which ends in 3, 4, 8 and 9 sen should be rounded up to the nearest multiple of 5 cent.
For example, $3.01 shall be rounded down to $3.00. Another example, $6.23 shall be rounded up to $6.25.

For more example, refer to the image

enter image description here

答:
1 multiply by 20

2 round

3 divide by 20 back

function round(x){return Math.round(x*20)/20}

// tests
[2.3, 3.13, 5.52, 7.88, 9.34, 8.12].forEach(x => console.log(round(x)));```


问:
I don't understand the Fibonacci pair haskell function given (tuples)
Recursion is something I have always struggled with understanding. I hope I can get some assistance here on how this function works. It works but I want to know how:</p>

```<code>fibStep :: (Int,Int) -> (Int,Int)
fibStep    (u,  v)    = (v,  u+v)

fibPair :: Int -> (Int,Int)
fibPair n
    | n==0      = (0,1)
    | otherwise = fibStep (fibPair (n-1))
</code>```

答:
Recursion works much like a loop. With a loop you have a stop condition, and the same is true for recursion, except it is called the base case. In this Fibonacci example, the base case is n==0, which returns the tuple (0,1) -- and of course this represents the first Fibonacci number.

After you've established your base case, now you need to figure out the recursive step -- in this example it is fibStep (fibPair (n-1)). This is equivalent to the code block for a loop, or what step is repeated on every iteration until the base case has been reached. Naturally, it is critical that you make sure you always converge to your base case, else the recursion will never end -- and in the example, the recursive step does converge to the base case, because for each consecutive step, the value of n decreases by one, meaning we must eventually reach the case where n==0 (assuming n is initially positive).

Let us look at the evaluation of fibPair 3. Each consecutive line is an expansion of the previous, using the definitions provided in the example.

```<code>fibPair 3 **note: n is not 0 so we use the recursive step
fibStep (fibPair (3-1))
fibStep (fibPair 2) **note: n is not 0 use recursive step again
fibStep (fibStep (fibPair (2-1)))
fibStep (fibStep (fibPair 1)) **note: n is not 0 use recursive step again
fibStep (fibStep (fibStep (fibPair (1-1))))
fibStep (fibStep (fibStep (fibPair 0))) **note: n equals 0 so base case is used
                                        ** recursion has now ended
fibStep (fibStep (fibStep (0,1))) **note: now fibStep begins evaluation
fibStep (fibStep (1, 1))
fibStep (1, 2)
(2, 3)
</code>```

Importantly, you should become comfortable with an English explanation of what is happening. fibStep takes a tuple of (fib number x, fib number x+1) and returns the next tuple in sequence, namely (fib number x+1, fib number x+2). fibPair acts as loop over fibStep, causing fibStep to be called n times on the same tuple, meaning the tuple (fib number x, fib number x+1) will result as (fib number x+n, fib number x+n+1).

Hopefully that helps clarify things a little bit. Recursion is truly just another way to write a loop; it has all of the same elements yet is written a bit differently. For some problems using recursion results in much simpler logic, or code, or both. Once you become more comfortable with recursion it will be a very useful tool to have for your future programming.

Body:
Recursion is something I have always struggled with understanding. I hope I can get some assistance here on how this function works. It works but I want to know how:

fibStep :: (Int,Int) -> (Int,Int)
fibStep    (u,  v)    = (v,  u+v)

fibPair :: Int -> (Int,Int)
fibPair n
    | n==0      = (0,1)
    | otherwise = fibStep (fibPair (n-1))

Body:
Recursion works much like a loop. With a loop you have a stop condition, and the same is true for recursion, except it is called the base case. In this Fibonacci example, the base case is n==0, which returns the tuple (0,1) -- and of course this represents the first Fibonacci number.

After you've established your base case, now you need to figure out the recursive step -- in this example it is fibStep (fibPair (n-1)). This is equivalent to the code block for a loop, or what step is repeated on every iteration until the base case has been reached. Naturally, it is critical that you make sure you always converge to your base case, else the recursion will never end -- and in the example, the recursive step does converge to the base case, because for each consecutive step, the value of n decreases by one, meaning we must eventually reach the case where n==0 (assuming n is initially positive).

Let us look at the evaluation of fibPair 3. Each consecutive line is an expansion of the previous, using the definitions provided in the example.

fibPair 3 **note: n is not 0 so we use the recursive step
fibStep (fibPair (3-1))
fibStep (fibPair 2) **note: n is not 0 use recursive step again
fibStep (fibStep (fibPair (2-1)))
fibStep (fibStep (fibPair 1)) **note: n is not 0 use recursive step again
fibStep (fibStep (fibStep (fibPair (1-1))))
fibStep (fibStep (fibStep (fibPair 0))) **note: n equals 0 so base case is used
                                        ** recursion has now ended
fibStep (fibStep (fibStep (0,1))) **note: now fibStep begins evaluation
fibStep (fibStep (1, 1))
fibStep (1, 2)
(2, 3)

Importantly, you should become comfortable with an English explanation of what is happening. fibStep takes a tuple of (fib number x, fib number x+1) and returns the next tuple in sequence, namely (fib number x+1, fib number x+2). fibPair acts as loop over fibStep, causing fibStep to be called n times on the same tuple, meaning the tuple (fib number x, fib number x+1) will result as (fib number x+n, fib number x+n+1).

Hopefully that helps clarify things a little bit. Recursion is truly just another way to write a loop; it has all of the same elements yet is written a bit differently. For some problems using recursion results in much simpler logic, or code, or both. Once you become more comfortable with recursion it will be a very useful tool to have for your future programming.


问:
Trouble adding element with text to DOM tree
I created an unordered list of elements and I'm trying to add a new element using DOM manipulation.

```<code>var newEl = document.create Element('li');
var newText = document.createTextNode('Hawaii');
var newEl = newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);
</code>```

The element was added to the ul element but it was not added as an li element, so my new text doesn't have any bulleting.

答:
avoid the reassignment to newEl.

var newEl = document.createElement('LI');
var newText = document.createTextNode('Hawaii');
newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);```

Body:
I created an unordered list of elements and I'm trying to add a new element using DOM manipulation.

var newEl = document.create Element('li');
var newText = document.createTextNode('Hawaii');
var newEl = newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);

The element was added to the ul element but it was not added as an li element, so my new text doesn't have any bulleting.


答:
You can try this.
Set an id to your ul element and append your new li in ul tag

 var node = document.createElement("li");
 var textnode = document.createTextNode("Hawaii");
 node.appendChild(textnode);
document.getElementById("myList").appendChild(node);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="myList">
  <li>Item 1</li>
  <li>Itm 2</li>
</ul></code>```

Title: Trouble adding element with text to DOM tree

Body:
You can try this.
Set an id to your ul element and append your new li in ul tag

 var node = document.createElement("li");
 var textnode = document.createTextNode("Hawaii");
 node.appendChild(textnode);
document.getElementById("myList").appendChild(node);

<ul id="myList">
  <li>Item 1</li>
  <li>Itm 2</li>
</ul>


问:
AssumeRole Action in a Role's Trust Relationship Policy
As per AWS documentation,

A user who wants to access a role in a different account must also
  have permissions that are delegated from the user account
  administrator. The administrator must attach a policy that allows the
  user to call AssumeRole for the ARN of the role in the other account.

I understand this requirement. However, I am not sure as to why an 'AssumeRole' action still need to be specified again in the 'Trust Relationship' of the role. It makes sense to allow/restrict a Principal (using 'AssumeRole' action) to assume a specific role and also the role being assumed to trust the assuming Principal (in its 'Trust Relationship'), but not sure why the role itself has to specify  'AssumeRole' action in its Trust relationship. The roles are always meant to be assumable  - isnt it? Or alternately, what is the significance of specifying 'AssumeRole' action in the 'Trust relationship' of a role?

答:
I'm not an AWS Roles expert, but as far as I know, the Trust Relationship Policy Document makes sense for two main reasons:

A role can be assumed not only with sts:AssumeRole action, but also with sts:AssumeRoleWithSAML and sts:AssumeRoleWithWebIdentity (docs here).

As the name "Trust Relationship Policy Document" says, it's also a policy document. So instead of creating a different template for Trust Relationship, AWS create a single policy template and uses it in all cases - this way we only need to learn the policy template once (docs here).


问:
Why delegate object is nil?
I am facing little weird issue with delegate pattern and I couldn't make it work like I expect. I guess I am missing something here but I couldn't figure it out myself.

Here's how my classes are defined,

```<code>class NetworkManager {

    weak var delegate: DownloaderProtocol?

    func downloadFile(downloadUrl: URL ) {
        downloadTask(with: downloadUrl).resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        delegate?.downloadCompleted(task: task, error: error)
    }
}

class DownloadManager: DownloaderProtocol {

    var networkManager: NetworkManager

    init(networkManager: NetworkManager) {
        self.networkManager = networkManager
    }

    func downloadMatches(urls: [String]) {
        self.networkManager.delegate = self

        for(....) {
            self.networkManager.downloadFile(url: url)
        }
    }

    func downloadCompleted(task: URLSessionTask, error: Error) {
        // Implementation
    }
}

class Matches {

    var networkManager: NetworkManager
    init() {
        self.networkManager = NetworkManager()
    }

    func getMatchSchedules(urls: [String] , completionHandler: @escaping (Result<Data, Error>) -> Void) {
        return DownloadManager.downloadMatches(urls: [String])
    }
}
</code>```

What is the issue ?

When the urlSession - didCompleteWithError method is called, I can see that delegate object is nil.

What I have tried ?

If I remove the weak reference of the delegate i.e weak var delegate: DownloaderProtocol? to var delegate: DownloaderProtocol?, then the delegate object is not nil. It works fine.

I even tried to set the delegates in Matches class, but the delegate is still shown as nil

Any help or point out is welcome.

答:
well I recommend this approach since is not all you code that posted in the question but just the relevant one.

```<code> class NetworkManager {

    weak var delegate: DownloaderProtocol?

    func downloadFile(downloadUrl: URL ) {
        downloadTask(with: downloadUrl).resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        delegate?.downloadCompleted(task: task, error: error)
    }
}

class DownloadManager: DownloaderProtocol {

    var networkManager: NetworkManager

    init(networkManager: NetworkManager) {
        self.networkManager = networkManager
        self.networkManager.delegate = self
    }

    func downloadMatches(urls: [String]) {

        for url in urls {
            guard let url = URL(string: url) else {return}
            self.networkManager.downloadFile(downloadUrl: url)
        }
    }

    func downloadCompleted(task: URLSessionTask, error: Error) {
        // Implementation
    }
}

class Matches {

    var downloadManager: DownloadManager//NetworkManager
    init() {
        //self.networkManager = NetworkManager()
        //self.networkManager.delegate = DownloadManager()
        let networkManager = NetworkManager()
        self.downloadManager = DownloadManager(networkManager: networkManager)
    }

    func getMatchSchedules(urls: [String] , completionHandler: @escaping (Result<Data, Error>) -> Void) {
        return downloadManager.downloadMatches(urls: ["asadsdad"])
    }
}
</code>```

you need a download manager in matches that have a network manager when you create  matches you create the network manger and set to the init of the download manager so you have a delegate set.

Title: Why delegate object is nil?

Body:
I am facing little weird issue with delegate pattern and I couldn't make it work like I expect. I guess I am missing something here but I couldn't figure it out myself.

Here's how my classes are defined,

class NetworkManager {

    weak var delegate: DownloaderProtocol?

    func downloadFile(downloadUrl: URL ) {
        downloadTask(with: downloadUrl).resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        delegate?.downloadCompleted(task: task, error: error)
    }
}

class DownloadManager: DownloaderProtocol {

    var networkManager: NetworkManager

    init(networkManager: NetworkManager) {
        self.networkManager = networkManager
    }

    func downloadMatches(urls: [String]) {
        self.networkManager.delegate = self

        for(....) {
            self.networkManager.downloadFile(url: url)
        }
    }

    func downloadCompleted(task: URLSessionTask, error: Error) {
        // Implementation
    }
}

class Matches {

    var networkManager: NetworkManager
    init() {
        self.networkManager = NetworkManager()
    }

    func getMatchSchedules(urls: [String] , completionHandler: @escaping (Result<Data, Error>) -> Void) {
        return DownloadManager.downloadMatches(urls: [String])
    }
}

What is the issue ?

When the urlSession - didCompleteWithError method is called, I can see that delegate object is nil.

What I have tried ?

If I remove the weak reference of the delegate i.e weak var delegate: DownloaderProtocol? to var delegate: DownloaderProtocol?, then the delegate object is not nil. It works fine.

I even tried to set the delegates in Matches class, but the delegate is still shown as nil

Any help or point out is welcome.

Body:
well I recommend this approach since is not all you code that posted in the question but just the relevant one.

 class NetworkManager {

    weak var delegate: DownloaderProtocol?

    func downloadFile(downloadUrl: URL ) {
        downloadTask(with: downloadUrl).resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        delegate?.downloadCompleted(task: task, error: error)
    }
}

class DownloadManager: DownloaderProtocol {

    var networkManager: NetworkManager

    init(networkManager: NetworkManager) {
        self.networkManager = networkManager
        self.networkManager.delegate = self
    }

    func downloadMatches(urls: [String]) {

        for url in urls {
            guard let url = URL(string: url) else {return}
            self.networkManager.downloadFile(downloadUrl: url)
        }
    }

    func downloadCompleted(task: URLSessionTask, error: Error) {
        // Implementation
    }
}

class Matches {

    var downloadManager: DownloadManager//NetworkManager
    init() {
        //self.networkManager = NetworkManager()
        //self.networkManager.delegate = DownloadManager()
        let networkManager = NetworkManager()
        self.downloadManager = DownloadManager(networkManager: networkManager)
    }

    func getMatchSchedules(urls: [String] , completionHandler: @escaping (Result<Data, Error>) -> Void) {
        return downloadManager.downloadMatches(urls: ["asadsdad"])
    }
}

you need a download manager in matches that have a network manager when you create  matches you create the network manger and set to the init of the download manager so you have a delegate set.


问:
FireBase stuck on "Run your app to verify installation" for android
I'm new to android development, since a long time, I'm stuck in one error that is Run your app to verify installation (Checking if the app has communicated with our servers. You may need to uninstall and reinstall your app.)</p>

```<code>build.gradle(Module:app)
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.firebase:firebase-core:16.0.1'
    }

     dependencies {
            classpath 'com.android.tools.build:gradle:3.3.2'
            classpath 'com.google.gms:google-services:4.0.1'
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
</code>```

答:
I solved updating the SDK Tools: Preferences -> Appearance & Behavior -> System Settings -> Updates, then click on "Check Now".

When the update was completed I uninstalled the app from the emulator, quitted both Android Studio and emulator and ran again

Body:
I'm new to android development, since a long time, I'm stuck in one error that is Run your app to verify installation (Checking if the app has communicated with our servers. You may need to uninstall and reinstall your app.)

build.gradle(Module:app)
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.firebase:firebase-core:16.0.1'
    }

     dependencies {
            classpath 'com.android.tools.build:gradle:3.3.2'
            classpath 'com.google.gms:google-services:4.0.1'
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }


问:
Best way to find lowest number in a list of objects using math.min?
Heres my code, which works but i feel like there is a more simple way doing this. The bold part is where i want to change.</p>

```<code>interface properties {
    age: number;
    salary: number;
    name: string;
}
let minSalary: any;
let maxSalary: any;

let list: properties[] = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

**minSalary =  Math.min.apply(Math, list.map( salaries => {
    return salaries.salary;** // This is the code i want to make easier
}
));

console.log(minSalary);
</code>```

答:
This is a shorter version:

```<code>const minSalary =  Math.min(...list.map(x => x.salary))
</code>```

let list = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

const minSalary =  Math.min(...list.map(x => x.salary))

console.log(minSalary);```

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min

Body:
Heres my code, which works but i feel like there is a more simple way doing this. The bold part is where i want to change.

interface properties {
    age: number;
    salary: number;
    name: string;
}
let minSalary: any;
let maxSalary: any;

let list: properties[] = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

**minSalary =  Math.min.apply(Math, list.map( salaries => {
    return salaries.salary;** // This is the code i want to make easier
}
));

console.log(minSalary);

Body:
This is a shorter version:

const minSalary =  Math.min(...list.map(x => x.salary))

let list = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

const minSalary =  Math.min(...list.map(x => x.salary))

console.log(minSalary);

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min


问:
Trouble reading a .txt file and storing into an array
I've been given a .txt file with a specific structure: each line has a String with 5 characters but with a random number of lines, and we should read the file and store it as we want.
I've tried doing it with a linked list and it worked just fine but as the size of the file grew up, the time it took to execute was too long. Since then i've been trying to store the Strings into an array of strings, so everything would be stored contiguously in memory. When executing, i get a segmentation fault error and i have no idea why. The code goes as follows:

```<code>int nLines (char *path)
{
    int answer = 0;
    FILE* fp;
    fp = fopen(path,"r");
    char line[6];

    while (fgets(line, sizeof(line),fp))
    {
        answer++;
    }

    return answer;
}

int main (int argc, char *argv[])
{
    FILE* fp;
    fp = fopen(argv[1], "r");
    int numberLines = nLines(argv[1]);

    char **storage = malloc(numberLines * 6 * sizeof(char));

    if(storage != NULL)
    {
        int i = 0;
        char line [6];

        while (fgets(line, sizeof(line),fp))
        {
            strcpy(storage[i], line);
            i++;
        }
    }

    free(storage);
}
</code>```

The first function is supposed to return the number of lines there is in the file. With this information, i'm trying to allocate memory equal to the number of strings * the size of each string since i know before hand this value. I'm imagining the problem comes from the line:

```<code>char **storage = malloc (numberLines * 6 *sizeof(char));
</code>```

I haven't touched C in a long time and i'm kinda rusty with the whole pointers and memory stuff. Can someone help please. Thank you!

答:
your allocation is wrong

```<code>int main (int argc, char *argv[])
{
    FILE* fp;
    fp = fopen(argv[1], "r");
    size_t numberLines = 0;

    char **storage = NULL;

    char line [8];

    while (fgets(line, sizeof(line),fp))
    {
        storage = realloc(storage, (numberLines + 1) * sizeof(*storage));
        storage[numberLines] = malloc(8);
        strcpy(storage[numlines++], line);
    }
/* ... */
}
</code>```

you need to allocate space for the pointers, then space for the strings. It is demo only and you should implement the correct error handling (memory and file).

Body:
I've been given a .txt file with a specific structure: each line has a String with 5 characters but with a random number of lines, and we should read the file and store it as we want.
I've tried doing it with a linked list and it worked just fine but as the size of the file grew up, the time it took to execute was too long. Since then i've been trying to store the Strings into an array of strings, so everything would be stored contiguously in memory. When executing, i get a segmentation fault error and i have no idea why. The code goes as follows:

int nLines (char *path)
{
    int answer = 0;
    FILE* fp;
    fp = fopen(path,"r");
    char line[6];

    while (fgets(line, sizeof(line),fp))
    {
        answer++;
    }

    return answer;
}

int main (int argc, char *argv[])
{
    FILE* fp;
    fp = fopen(argv[1], "r");
    int numberLines = nLines(argv[1]);

    char **storage = malloc(numberLines * 6 * sizeof(char));

    if(storage != NULL)
    {
        int i = 0;
        char line [6];

        while (fgets(line, sizeof(line),fp))
        {
            strcpy(storage[i], line);
            i++;
        }
    }

    free(storage);
}

The first function is supposed to return the number of lines there is in the file. With this information, i'm trying to allocate memory equal to the number of strings * the size of each string since i know before hand this value. I'm imagining the problem comes from the line:

char **storage = malloc (numberLines * 6 *sizeof(char));

I haven't touched C in a long time and i'm kinda rusty with the whole pointers and memory stuff. Can someone help please. Thank you!

Body:
your allocation is wrong

int main (int argc, char *argv[])
{
    FILE* fp;
    fp = fopen(argv[1], "r");
    size_t numberLines = 0;

    char **storage = NULL;

    char line [8];

    while (fgets(line, sizeof(line),fp))
    {
        storage = realloc(storage, (numberLines + 1) * sizeof(*storage));
        storage[numberLines] = malloc(8);
        strcpy(storage[numlines++], line);
    }
/* ... */
}

you need to allocate space for the pointers, then space for the strings. It is demo only and you should implement the correct error handling (memory and file).


问:
confused by strange web address especially by "ai" term in start
While making online shopping,i came across a website for Live customer chat

https://ai.alimebot.daraz.pk/

"ai" in start of this web address means artificial intelligence?? If yes why and how?Infact on that link,i had chatted with a csr that was human being

答:
ai.alimebot.daraz.pk is a host name. If you are the domain owner you can create any host names and sub domain names that you want, provided you use legal characters for names.

For example, they could have created you-are-not-expected-to-understand-this.ai.alimebot.daraz.pk


问:
JAVA return longest value if a string contains any of the items from a List
I have the following array of code types:

```<code>["sample_code","code","formal_code"]
</code>```

and the following ids:

```<code>String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";
</code>```

I want to extract the code type from the ids

this is my code snippet:

```<code>    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);
</code>```

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

```<code>for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"
</code>```

答:
Check for the longest code types first. This means the following changes to your code:

Sort the code types by length descending.

Don’t use a parallel stream. A parallel stream hasn’t got an order. A sequential stream makes sure the code types are checked in order.

Use findFirst(), not findAny() to make sure you get the first match.

So it becomes:

```<code>    String codeTypes[] = { "sample_code", "code", "formal_code" };
    Arrays.sort(codeTypes, Comparator.comparing(String::length).reversed());

    String id = "123456789_sample_code_xyz";
    Optional<String> codeType = Arrays.stream(codeTypes).filter(id::contains).findFirst();
    codeType.ifPresent(System.out::println);
</code>```

Now output is:

sample_code

Body:
I have the following array of code types:

["sample_code","code","formal_code"]

and the following ids:

String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";

I want to extract the code type from the ids

this is my code snippet:

    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"

Body:
Check for the longest code types first. This means the following changes to your code:

Sort the code types by length descending.

Don’t use a parallel stream. A parallel stream hasn’t got an order. A sequential stream makes sure the code types are checked in order.

Use findFirst(), not findAny() to make sure you get the first match.

So it becomes:

    String codeTypes[] = { "sample_code", "code", "formal_code" };
    Arrays.sort(codeTypes, Comparator.comparing(String::length).reversed());

    String id = "123456789_sample_code_xyz";
    Optional<String> codeType = Arrays.stream(codeTypes).filter(id::contains).findFirst();
    codeType.ifPresent(System.out::println);

Now output is:

sample_code


问:
Is SQL Server Spatial Index Rebuild Limited to Single-Threaded Execution
When running Windows performance monitoring during a spatial index rebuild (using MAXDOP=8), it appears that there are two phases of the index rebuild process. The first phase (about 1/3 of the execution time) takes advantage of the MAXDOP=8 during which there is a lot of read/write I/0. The second phase (about 2/3 of the execution), seems to be single-threaded even though MAXDOP=8 is specified for the index rebuild command. Note that this is shown on SQL Server Enterprise (not Standard).

Is this a limitation of spatial index rebuilds or all index rebuilds? If not, is there a way to force the entire rebuild to use more threads?

答:
Based on ALTER INDEX:

Important

Although the MAXDOP option is syntactically supported for all XML indexes, for a spatial index or a primary XML index, ALTER INDEX currently uses only a single processor.


问:
What does this Typescript syntax mean
```<code>export declare type SomeType = {
   [key: string] : string
};
</code>```

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?

答:
It means that an object of type SomeType can only have string properties with string values:

Example:

// Valid
{

    firstName: 'John',
    lastName: 'Smith'

},

// Invalid
{

    firstName: 'John',
    age: 10

}
```

This syntax is called Index Signature.

Title: What does this Typescript syntax mean

Body:
export declare type SomeType = {
   [key: string] : string
};

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?

Body:
It means that an object of type SomeType can only have string properties with string values:

Example:

// Valid
{

    firstName: 'John',
    lastName: 'Smith'

},

// Invalid
{

    firstName: 'John',
    age: 10

}

This syntax is called Index Signature.


问:
Navbar items are not clickable and nav items at right side are not getting aligned properly

Two navbar items i.e. About us and Contact us are not
  clickable. How to make these navbar items clickable?

and how to align one of the navbar item properly i.e. Login which is currently
  positioned at rightmost part of the navbar.This login item has dropdown menu which only gets partially displayed because it is situated in rightmost part.

html {
  height: 100%;
}

.navbar-light .navbar-brand {
  color: black;
}

body {
  background: linear-gradient(rgba(255, 255, 255, .5), rgba(255, 255, 255, .5)), url(https://images.unsplash.com/photo-1486312338219-ce68d2c6f44d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80) no-repeat center center fixed;
  background-size: cover;
  background-position: center;
  font-family: catamaran;
}

.center {
  text-align: center;
  margin: 0 auto;
  padding: 5%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.navbar {
  height: 45px;
}

h1,
p {
  color: black;
}

h2>span {
  color: black;
}

@media (max-width:768px) {
  h1 {
    background-color: #449d44;
  }
  h2 {
    background-color: #449d44;
  }
}

@media (min-width:768px) {
  h1 {
    background-color: skyblue;
  }
}

.nav-item active {
  text-align: left;
}

#Login {
  min-width: 250px;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 14px 14px 0;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <link rel="stylesheet" href="css/technical_landing.css">
  <link href="https://fonts.googleapis.com/css?family=Catamaran&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css">

  <title>Minimum Bootstrap HTML Skeleton</title>

  <!--  -->

  <style>

  </style>

</head>

<body>

  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    Technical lab
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

    <div class="  collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">

        <li class="nav-item active ">
          Home <span class="sr-only">(current)</span>
        </li>

        <li class="nav-item ">
          About us
        </li>

        <li class="nav-item ">
          Contact us
        </li>

      </ul>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            Sign Up <span class="sr-only">(current)</span></li>

          <li class="dropdown">
             Log in <span class="caret"></span>

            <ul id="Login" class="dropdown-menu">
              <li>
                <div class="row">
                  <div class="col-md-12">
                    Login via:
                    <div class="social-button">
                      <i class="fa fa-facebook"></i>Facebook
                      <i class="fa fa-twitter"></i>Twitter
                    </div>
                  </div>
                </div>
              </li>
            </ul>

          </li>

        </ul>

      </div>
  </nav>
  </div>
  </nav>

  <div class="container center">
    <div class="row">
      <div class="col-md-12">
        <h2>
          <span class="fa-stack fa-lg">
                     <i class="far fa-square fa-stack-2x"></i>
                     <i class="fab fa-twitter-square fa-stack-1x"></i>
                 </span>
        </h2>
        <h1>Technical lab is coming soon.</h1>
        <p>Waiting is not easy but just wait this time</p>
        <button class="btn btn-success btn-lg">
             <i class="fas fa-spinner"></i>
             <br>Click me</button>

      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

  <script>
  </script>

</body>

</html></code>```

答:
I hope you should copy this code and use in your Html file

If Want exact result

or visit this clink for life  Demo  for the navbar right

.header {
  min-height: 500px;
 }

.rightNavbar .nav-item .dropdown-menu {
  position: absolute;
  right: 0;
  left: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.4.1/cerulean/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header"><nav class="navbar navbar-expand-lg navbar-light bg-light">
  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        Home <span class="sr-only">(current)</span>
      </li>
      <li class="nav-item">
        Link
      </li>
      <li class="nav-item dropdown">

          Dropdown

        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          Action
          Another action
          <div class="dropdown-divider"></div>
          Something else here
        </div>
      </li>
      <li class="nav-item">
        Disabled
      </li>
    </ul>
    <ul class="rightNavbar navbar-nav ml-auto">
      <li class="nav-item active">
        Sign Up
      </li>
      <li class="nav-item dropdown">

          Login

        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          Action
          Another action
          <div class="dropdown-divider"></div>
          Something else here
        </div>
      </li>
    </ul>
  </div>
</nav></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script></code>```

Body:
Two navbar items i.e. About us and Contact us are not
  clickable. How to make these navbar items clickable?

and how to align one of the navbar item properly i.e. Login which is currently
  positioned at rightmost part of the navbar.This login item has dropdown menu which only gets partially displayed because it is situated in rightmost part.

html {
  height: 100%;
}

.navbar-light .navbar-brand {
  color: black;
}

body {
  background: linear-gradient(rgba(255, 255, 255, .5), rgba(255, 255, 255, .5)), url(https://images.unsplash.com/photo-1486312338219-ce68d2c6f44d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80) no-repeat center center fixed;
  background-size: cover;
  background-position: center;
  font-family: catamaran;
}

.center {
  text-align: center;
  margin: 0 auto;
  padding: 5%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.navbar {
  height: 45px;
}

h1,
p {
  color: black;
}

h2>span {
  color: black;
}

@media (max-width:768px) {
  h1 {
    background-color: #449d44;
  }
  h2 {
    background-color: #449d44;
  }
}

@media (min-width:768px) {
  h1 {
    background-color: skyblue;
  }
}

.nav-item active {
  text-align: left;
}

#Login {
  min-width: 250px;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 14px 14px 0;
}

}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <link rel="stylesheet" href="css/technical_landing.css">
  <link href="https://fonts.googleapis.com/css?family=Catamaran&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css">

  <title>Minimum Bootstrap HTML Skeleton</title>

    Technical lab
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

          Home (current)

          About us

          Contact us

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Sign Up (current)

             Log in

                    Login via:

                      Facebook
                      Twitter

Technical lab is coming soon.

Waiting is not easy but just wait this time

        <button class="btn btn-success btn-lg">

Click me</button>

Body:
I hope you should copy this code and use in your Html file

If Want exact result

or visit this clink for life  Demo  for the navbar right

.header {
  min-height: 500px;
 }

.rightNavbar .nav-item .dropdown-menu {
  position: absolute;
  right: 0;
  left: auto;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.4.1/cerulean/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header"><nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
    </ul>
    <ul class="rightNavbar navbar-nav ml-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Sign Up </a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Login
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
  </div>
</nav></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>


问:
How to set Neutral button position to center instead of to the left side in Alert Dialog
Below is my code which shows ok button to the left side.

```<code> AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("No product found");
        builder.setCancelable(false);
        builder.setNeutralButton(
                "Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        ((MainActivity)getActivity()).fragment_Scan_call();
                    }
                });
// Must call show() prior to fetching text view
        AlertDialog alert = builder.create();
        alert.show();
</code>```

答:
BUTTON_NEUTRAL, BUTTON_NEGATIVE, and BUTTON_POSITIVE don't have any semantics attached to them (apart from the actual names), therefore if you want to 'move' the button positions simply flip your event listeners and labels to whichever button is in the position you want.

I.e. given that your original code was:

```<code>builder.setNeutralButton("Save Draft", saveDraftListener)
builder.setNegativeButton("Cancel", cancelListener)
builder.setPositiveButton("Send", sendListener)
</code>```

you can flip it to:

```<code>// flip neutral and negative buttons
builder.setNeutralButton("Cancel", cancelListener)
builder.setNegativeButton("Save Draft", saveDraftListener)
builder.setPositiveButton("Send", sendListener)
</code>```

In the true Humpty-Dumpty way any button can be used for whatever you want, including using BUTTON_NEGATIVE as Ok, and BUTTON_POSITIVE as Cancel.

Body:
Below is my code which shows ok button to the left side.

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("No product found");
        builder.setCancelable(false);
        builder.setNeutralButton(
                "Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        ((MainActivity)getActivity()).fragment_Scan_call();
                    }
                });
// Must call show() prior to fetching text view
        AlertDialog alert = builder.create();
        alert.show();

Body:
BUTTON_NEUTRAL, BUTTON_NEGATIVE, and BUTTON_POSITIVE don't have any semantics attached to them (apart from the actual names), therefore if you want to 'move' the button positions simply flip your event listeners and labels to whichever button is in the position you want.

I.e. given that your original code was:

builder.setNeutralButton("Save Draft", saveDraftListener)
builder.setNegativeButton("Cancel", cancelListener)
builder.setPositiveButton("Send", sendListener)

you can flip it to:

// flip neutral and negative buttons
builder.setNeutralButton("Cancel", cancelListener)
builder.setNegativeButton("Save Draft", saveDraftListener)
builder.setPositiveButton("Send", sendListener)

In the true Humpty-Dumpty way any button can be used for whatever you want, including using BUTTON_NEGATIVE as Ok, and BUTTON_POSITIVE as Cancel.


问:
What's wrong with this Python code? PermissionError: [Errno 13]
This program is supposed to be able to download the contents from an http: URL and save it to a user's directory of choice.

```<code>import urllib.request
import urllib.error

def run_user_interface() -> None:
    url = _choose_url()
    if len(url) == 0:
    return
    else:
        print()
        save_path = _choose_save_path()

        if len(save_path) == 0:
            return
        else:
            _download_url(url, save_path)

def _choose_url() -> str:
    print('Choose a URL to download (press Enter or Return to quit)')
    return input('URL: ').strip()

def _choose_save_path() -> str:
    print('Choose where you\'d like to save the file you download')
    return input('Path: ').strip()

def _download_url(url_to_download: str, file_path: str) -> None:
    response = None
    file_to_save = None

    try:
        response = urllib.request.urlopen(url_to_download)
        file_to_save = open(file_path, 'wb')
        file_to_save.write(response.read())

    except urllib.error.HTTPError as e:
        print('Failed to download contents of URL')
    print('Status code: {}'.format(e.code))
    print()

    finally:
        if file_to_save != None:
            file_to_save.close()

        if response != None:
        response.close()

if __name__ == '__main__':
    run_user_interface()
</code>```

Executing the program on my friend's computer works fine. However, when I execute it on my computer, I receive the following error.

```<code>Traceback (most recent call last):
File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 63, in <module>
run_user_interface()

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 20, in run_user_interface
_download_url(url, save_path)

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 40, in _download_url
file_to_save = open(file_path, 'wb')

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\garci\\Desktop\\ICS_32_Winter_2020'
</code>```

How could I fix this permission error? Thank you.

答:
Seems like your program is not allowed to write to this specific location on your PC.

Change the permissions for the folder C:\Users\garci\Desktop\ICS_32_Winter_2020 and your program should run fine.

A simple way of doing so (on Windows) is to find your directory in the file explorer, right click on the folder, select Properties, and then open the Security tab. From there, you can modify the read/write permissions for the folder.

Body:
This program is supposed to be able to download the contents from an http: URL and save it to a user's directory of choice.

import urllib.request
import urllib.error

def run_user_interface() -> None:
    url = _choose_url()
    if len(url) == 0:
    return
    else:
        print()
        save_path = _choose_save_path()

        if len(save_path) == 0:
            return
        else:
            _download_url(url, save_path)

def _choose_url() -> str:
    print('Choose a URL to download (press Enter or Return to quit)')
    return input('URL: ').strip()

def _choose_save_path() -> str:
    print('Choose where you\'d like to save the file you download')
    return input('Path: ').strip()

def _download_url(url_to_download: str, file_path: str) -> None:
    response = None
    file_to_save = None

    try:
        response = urllib.request.urlopen(url_to_download)
        file_to_save = open(file_path, 'wb')
        file_to_save.write(response.read())

    except urllib.error.HTTPError as e:
        print('Failed to download contents of URL')
    print('Status code: {}'.format(e.code))
    print()

    finally:
        if file_to_save != None:
            file_to_save.close()

        if response != None:
        response.close()

if __name__ == '__main__':
    run_user_interface()

Executing the program on my friend's computer works fine. However, when I execute it on my computer, I receive the following error.

Traceback (most recent call last):
File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 63, in <module>
run_user_interface()

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 20, in run_user_interface
_download_url(url, save_path)

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 40, in _download_url
file_to_save = open(file_path, 'wb')

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\garci\\Desktop\\ICS_32_Winter_2020'

How could I fix this permission error? Thank you.


问:
git central repository and Team
I have been playing around with GIT on my local computer.

As I have gain a bit of knowledge using GIT like add, commit, merge, branch, checkout, status.

I still have more to learn but im confuse one thing.. how does git handle team?

For example:

Developer A computer

Developer B computer

Developer C computer

Central repository (Server)

All Developers working on the same project.

From what I understood (correct me if im wrong).. A ,B and C developers push their branch (master?) to central repository via SSH remote.

But on the central repository, how do I get information or which files (or branch?) that has been pushed from the developers... What would it look like on the central repository?

On the central repository, how would handle merges developers work?

Thanks.

答:
There is no "central repository", per se. You will typically create one because it works out nicely for working in a team and keeping everything/everyone organized.

When setting up this central repository, you will give it a name of some sort. This is your local reference point to this central repository, not everyone on your team has to necessarily call it the same thing. This is a 'remote' in git (and I'm sure many other DVCSs) speak. Most people tend to name it 'origin'. You can find out what branches have been pushed to the origin (and more, such as tags) by doing a git fetch origin. When doing a git pull, you are really doing a git fetch, followed by a git merge.

From what I understood (correct me if im wrong).. A ,B and C developers push their branch (master?) to central repository via SSH remote.

It doesn't necessarily have to be master. Just like origin, master is a naming convention and happens to be the branch that gets created for you when you initialize a directory as being a git repository.

But on the central repository, how do I get information or which files (or branch?) that has been pushed from the developers... What would it look like on the central repository?

See above re: git fetch.

On the central repository, how would handle merges developers work?

You don't have to handle merges on the origin because a developer will have to pull the latest work from everyone else on whatever branch they are working on, before they can push their changes to the origin (and in particular, that branch).

I hope this helps. I am far from understanding all of the ins-and-outs of how it all really works.

Title: git central repository and Team


问:
is swift integer literal not include bitwise expression?
I am learning swift OptionSet, and I write this code and I get a compile error

"error: cannot convert value of type 'Int' to specified type 'Number'"

it happens when I init one with 1 << 0

struct Number: OptionSet, ExpressibleByIntegerLiteral {
    let rawValue: Int

    static let zero: Number = 0
    static let one: Number = 1 << 0
    static let two: Number = 1 << 1
    static let three: Number = 1 << 2

    init(integerLiteral: Int) {
        rawValue = integerLiteral
    }

    init(rawValue: Int) {
        self.rawValue = rawValue
    }
}
```

<p>if I use decimal instead of bitwise expression, everything is good</p>

```struct Number: OptionSet, ExpressibleByIntegerLiteral {
    let rawValue: Int

    static let zero: Number = 0
    static let one: Number = 1
    static let two: Number = 2
    static let three: Number = 4

    init(integerLiteral: Int) {
        rawValue = integerLiteral
    }

    init(rawValue: Int) {
        self.rawValue = rawValue
    }
}
```

Please let me know why!!!

答:
Why it doesn't work

This doesn't work because what you have is a constant expression (an expression whose subexpressions are exclusively other constant expressions, or literals), which itself is not literal.

"Literals" are very narrow: literally only literal forms, like 0xABCD, 0b1010, 123, etc. The intent of ExpressibleByIntegerLiteral is to make Integer's "preferential treatment" over custom types like MyInt be non-preferential, and available to custom types. It's not intended to be a way to define implicit casts for arbitrary expressions.

The straight-forward fix

To fix this, you can either explicitly wrap your expressions like Number(rawValue: 1 << 2).

The "clever" fix

This works, though it's not typical, and I wouldn't recommend it. I add it here just because I think it's kinda interesting.

You can actually achieve this by making a << operator of type (Number, Number) -> Number. The expression1 << 2could then be evaluated asNumber(integerLiteral: 1) << Number(integerLiteral: 2), resulting in aNumber`.

Pro tip: If you don't define any initializes in the main declaration of the struct, and instead define them in extensions (such as for conformance to ExpressibleByIntegerLiteral), you get to keep the "default memberwise initializer, in this case,Number.init(rawValue:)`, that the compiler automatically synthesizes for you.

```<code>struct Number {
    let rawValue: Int
}

extension Number {
    static func << (lhs: Number, rhs: Number) -> Number {
        return Number(rawValue: lhs.rawValue << rhs.rawValue)
    }
}

extension Number: ExpressibleByIntegerLiteral {
    init(integerLiteral: Int) {
        rawValue = integerLiteral
    }
}

extension Number: OptionSet {
    static let zero: Number = 0
    static let one: Number = 1 << 0
    static let two: Number = 1 << 1
    static let three: Number = 1 << 2
}
</code>```

Body:
I am learning swift OptionSet, and I write this code and I get a compile error

"error: cannot convert value of type 'Int' to specified type 'Number'"

it happens when I init one with 1 << 0

struct Number: OptionSet, ExpressibleByIntegerLiteral {
    let rawValue: Int

    static let zero: Number = 0
    static let one: Number = 1 << 0
    static let two: Number = 1 << 1
    static let three: Number = 1 << 2

    init(integerLiteral: Int) {
        rawValue = integerLiteral
    }

    init(rawValue: Int) {
        self.rawValue = rawValue
    }
}

if I use decimal instead of bitwise expression, everything is good

struct Number: OptionSet, ExpressibleByIntegerLiteral {
    let rawValue: Int

    static let zero: Number = 0
    static let one: Number = 1
    static let two: Number = 2
    static let three: Number = 4

    init(integerLiteral: Int) {
        rawValue = integerLiteral
    }

    init(rawValue: Int) {
        self.rawValue = rawValue
    }
}

Please let me know why!!!

Body:
Why it doesn't work

This doesn't work because what you have is a constant expression (an expression whose subexpressions are exclusively other constant expressions, or literals), which itself is not literal.

"Literals" are very narrow: literally only literal forms, like 0xABCD, 0b1010, 123, etc. The intent of ExpressibleByIntegerLiteral is to make Integer's "preferential treatment" over custom types like MyInt be non-preferential, and available to custom types. It's not intended to be a way to define implicit casts for arbitrary expressions.

The straight-forward fix

To fix this, you can either explicitly wrap your expressions like Number(rawValue: 1 << 2).

The "clever" fix

This works, though it's not typical, and I wouldn't recommend it. I add it here just because I think it's kinda interesting.

You can actually achieve this by making a << operator of type (Number, Number) -> Number. The expression1 << 2could then be evaluated asNumber(integerLiteral: 1) << Number(integerLiteral: 2), resulting in aNumber`.

Pro tip: If you don't define any initializes in the main declaration of the struct, and instead define them in extensions (such as for conformance to ExpressibleByIntegerLiteral), you get to keep the "default memberwise initializer, in this case,Number.init(rawValue:)`, that the compiler automatically synthesizes for you.

struct Number {
    let rawValue: Int
}

extension Number {
    static func << (lhs: Number, rhs: Number) -> Number {
        return Number(rawValue: lhs.rawValue << rhs.rawValue)
    }
}

extension Number: ExpressibleByIntegerLiteral {
    init(integerLiteral: Int) {
        rawValue = integerLiteral
    }
}

extension Number: OptionSet {
    static let zero: Number = 0
    static let one: Number = 1 << 0
    static let two: Number = 1 << 1
    static let three: Number = 1 << 2
}


问:
React app production build shows js errors
I've created a client react application using create-react-app. It talks to a node server running an express api. In development everything is working great and was getting ready to deploy.

When running npm run build I get no errors whatsoever either, everything seems to be working great. When build finishes it suggest to run serve -s build , I do this and navigate to my localhost:5000, the first console.logs from my app show up but then suddenly i throws a seemingly simple javascript error:

```<code>TypeError: "e.forEach is not a function"
    me InboundTab.js:27
    me InboundTab.js:36
    React 7
    unstable_runWithPriority scheduler.production.min.js:270
    React 5
    getArrivals ArrivalState.js:39
    l runtime.js:45
    _invoke runtime.js:264
    t runtime.js:98
    l runtime.js:45
    t runtime.js:137
    t runtime.js:147
react-dom.production.min.js:4636:12
    React 5
    unstable_runWithPriority scheduler.production.min.js:270
    React 4
    unstable_runWithPriority scheduler.production.min.js:270
    React 5
    getArrivals ArrivalState.js:39
    l runtime.js:45
    _invoke runtime.js:264
    t runtime.js:98
    l runtime.js:45
    t runtime.js:137
    t runtime.js:147
</code>```

I've been looking all over the internet but can't find any clues on what's going on here. Most sites talk about errors during the build process or a site not showing at all but this is neither. Googling the error seems to say this is some ES6 issue, but I'm running firefox 73 so I'd expect no issues on that front.

As extra info this is my first time trying to deploy react. Funny enough I'd only done small projects so far running locally so I am pretty sure I'm missing something obvious in the build process.

Any help, tips on where to loop will be most appreciated. Thanks!

答:
Answering my own question. I guess I just needed to re-read this error with the nice syntax highlight because the filename and line location took me to the right place.

On my client's api calls I set up the server url as:

```<code>const API_SERVER =
  process.env.NODE_ENV === "development"
    ? "http://localhost:4200"
    : "http://example.com";
</code>```

but my example.com isn't setup yet so the error came from not being able to reach the server. Changing the example.com to localhost and re-building made things work.

Body:
I've created a client react application using create-react-app. It talks to a node server running an express api. In development everything is working great and was getting ready to deploy.

When running npm run build I get no errors whatsoever either, everything seems to be working great. When build finishes it suggest to run serve -s build , I do this and navigate to my localhost:5000, the first console.logs from my app show up but then suddenly i throws a seemingly simple javascript error:

TypeError: "e.forEach is not a function"
    me InboundTab.js:27
    me InboundTab.js:36
    React 7
    unstable_runWithPriority scheduler.production.min.js:270
    React 5
    getArrivals ArrivalState.js:39
    l runtime.js:45
    _invoke runtime.js:264
    t runtime.js:98
    l runtime.js:45
    t runtime.js:137
    t runtime.js:147
react-dom.production.min.js:4636:12
    React 5
    unstable_runWithPriority scheduler.production.min.js:270
    React 4
    unstable_runWithPriority scheduler.production.min.js:270
    React 5
    getArrivals ArrivalState.js:39
    l runtime.js:45
    _invoke runtime.js:264
    t runtime.js:98
    l runtime.js:45
    t runtime.js:137
    t runtime.js:147

I've been looking all over the internet but can't find any clues on what's going on here. Most sites talk about errors during the build process or a site not showing at all but this is neither. Googling the error seems to say this is some ES6 issue, but I'm running firefox 73 so I'd expect no issues on that front.

As extra info this is my first time trying to deploy react. Funny enough I'd only done small projects so far running locally so I am pretty sure I'm missing something obvious in the build process.

Any help, tips on where to loop will be most appreciated. Thanks!

Body:
Answering my own question. I guess I just needed to re-read this error with the nice syntax highlight because the filename and line location took me to the right place.

On my client's api calls I set up the server url as:

const API_SERVER =
  process.env.NODE_ENV === "development"
    ? "http://localhost:4200"
    : "http://example.com";

but my example.com isn't setup yet so the error came from not being able to reach the server. Changing the example.com to localhost and re-building made things work.


问:
How do I transform Apache Ignite Java Based Config to Spring XML Config?
How would I transform below ignite Java Config to Spring XML Config given below ?

答:
The above Java config in Spring XML Config is given below :</p>

```<code><bean class="org.apache.ignite.configuration.IgniteConfiguration">
  <property name="dataStorageConfiguration">
    <bean class="org.apache.ignite.configuration.DataStorageConfiguration">
      <property name="dataRegionConfigurations">
          <bean class="org.apache.ignite.configuration.DataRegionConfiguration">
            <property name="maxSize" value="#{45L * 1024 * 1024}"/>
            <property name="persistenceEnabled" value="true"/>
            <property name="name" value="cold"/>
          </bean>
      </property>
    </bean>
  </property>
</bean>
</code>```

Body:
The above Java config in Spring XML Config is given below :

<bean class="org.apache.ignite.configuration.IgniteConfiguration">
  <property name="dataStorageConfiguration">
    <bean class="org.apache.ignite.configuration.DataStorageConfiguration">
      <property name="dataRegionConfigurations">
          <bean class="org.apache.ignite.configuration.DataRegionConfiguration">
            <property name="maxSize" value="#{45L * 1024 * 1024}"/>
            <property name="persistenceEnabled" value="true"/>
            <property name="name" value="cold"/>
          </bean>
      </property>
    </bean>
  </property>
</bean>


问:
Filter Dataframe with MultiIndex by specific index value
I'm working in forecasting the demand of a product using many scenarios per year. I have a MulitiIndexed dataframe (Simulation, Year, Month) and need to filter by one of them (let's say Simulation).

```<code>import pandas as pd
idx = pd.MultiIndex.from_tuples([(1,2020,1), (1,2020,2), (2,2020,1), (2,2020,2)],
                                 names=['Simulation', 'Year', 'Month'])
d = {'Apples': [1,2,3,4], 'Organes': [4,5,6,8], 'Lemons': [9,10,11,12]}
df = pd.DataFrame(d, index=idx)
print(df)
</code>```

```<code>Simulation   Year    Month     Apples  Oranges  Lemons
1            2020    1         1       4        9
1                    2         2       5        10
2            2020    1         3       6        11
2                    2         4       8        12

</code>```

How can I filter by Simulation?

Expected output for filtering by simulation number 1 only

```<code>Simulation   Year    Month     Apples  Oranges  Lemons
1            2020    1         1       4        9
1                    2         2       5        10
</code>```

答:
Say you want to index where Simulation is 1, you can use index.get_level_values as:

```<code>df[df.index.get_level_values(0) == 1]

                        Apples  Oranges  Lemons
Simulation Year Month
1          2020 1          10       30      10
                2          25       50       5
           2030 12         30       70       5
</code>```

For multiple values, you can add an isin at the end to values in a list:

```<code>df.loc[df.index.get_level_values(0).isin([1, 2])]

                        Apples  Oranges  Lemons
Simulation Year Month
1          2020 1          10       30      10
                2          25       50       5
           2030 12         30       70       5
2          2020 1          15       25      10
                2          20       50      15
</code>```

get_level_values is basically returning a Int64Index containing all indices along the first axis:

```<code>df.index.get_level_values(0)
# Int64Index([1, 1, 1, 2, 2, 50], dtype='int64', name='Simulation')
</code>```

We can then use the result to perform boolean indexing on the dataframe along the axis of interest.

Or you can also use pd.IndexSlice:

```<code>df.loc[pd.IndexSlice[[1,2], :, :]]

                        Apples  Oranges  Lemons
Simulation Year Month
1          2020 1          10       30      10
                2          25       50       5
           2030 12         30       70       5
2          2020 1          15       25      10
                2          20       50      15
</code>```

Body:
I'm working in forecasting the demand of a product using many scenarios per year. I have a MulitiIndexed dataframe (Simulation, Year, Month) and need to filter by one of them (let's say Simulation).

import pandas as pd
idx = pd.MultiIndex.from_tuples([(1,2020,1), (1,2020,2), (2,2020,1), (2,2020,2)],
                                 names=['Simulation', 'Year', 'Month'])
d = {'Apples': [1,2,3,4], 'Organes': [4,5,6,8], 'Lemons': [9,10,11,12]}
df = pd.DataFrame(d, index=idx)
print(df)

Simulation   Year    Month     Apples  Oranges  Lemons
1            2020    1         1       4        9
1                    2         2       5        10
2            2020    1         3       6        11
2                    2         4       8        12

How can I filter by Simulation?

Expected output for filtering by simulation number 1 only

Simulation   Year    Month     Apples  Oranges  Lemons
1            2020    1         1       4        9
1                    2         2       5        10

Body:
Say you want to index where Simulation is 1, you can use index.get_level_values as:

df[df.index.get_level_values(0) == 1]

                        Apples  Oranges  Lemons
Simulation Year Month
1          2020 1          10       30      10
                2          25       50       5
           2030 12         30       70       5

For multiple values, you can add an isin at the end to values in a list:

df.loc[df.index.get_level_values(0).isin([1, 2])]

                        Apples  Oranges  Lemons
Simulation Year Month
1          2020 1          10       30      10
                2          25       50       5
           2030 12         30       70       5
2          2020 1          15       25      10
                2          20       50      15

get_level_values is basically returning a Int64Index containing all indices along the first axis:

df.index.get_level_values(0)
# Int64Index([1, 1, 1, 2, 2, 50], dtype='int64', name='Simulation')

We can then use the result to perform boolean indexing on the dataframe along the axis of interest.

Or you can also use pd.IndexSlice:

df.loc[pd.IndexSlice[[1,2], :, :]]

                        Apples  Oranges  Lemons
Simulation Year Month
1          2020 1          10       30      10
                2          25       50       5
           2030 12         30       70       5
2          2020 1          15       25      10
                2          20       50      15


问:
How does terraform handle mounting an AWS Elastic Block Store (EBS) with regards to partitioning?
Sample terraform code snippet for mounting an EBS (just for context):

```<code>resource "aws_ebs_volume" "ebs-volume-1" {
  availability_zone = "eu-central-1a"
  size              = 20
  type              = "gp2"
  tags = {
    Name = "extra volume data"
  }
}

resource "aws_volume_attachment" "ebs-volume-1-attachment" {
  device_name = "/dev/xvdh"
  volume_id   = aws_ebs_volume.ebs-volume-1.id
  instance_id = aws_instance.example.id
}
</code>```

I have read through the terraform documentation on attributes it has for mounting EBS here; however, it is not clear to me how does that block device gets partitioned (or if partitioning here is relevant at all.

Explanation of what is EBS: here

答:
The "aws_ebs_volume" resource will create the EBS volume, the "aws_volume_attachment" puts it on an EC2 instance.

Keep in mind, you can do this in an "aws_instance" resource as well.

Body:
Sample terraform code snippet for mounting an EBS (just for context):

resource "aws_ebs_volume" "ebs-volume-1" {
  availability_zone = "eu-central-1a"
  size              = 20
  type              = "gp2"
  tags = {
    Name = "extra volume data"
  }
}

resource "aws_volume_attachment" "ebs-volume-1-attachment" {
  device_name = "/dev/xvdh"
  volume_id   = aws_ebs_volume.ebs-volume-1.id
  instance_id = aws_instance.example.id
}

I have read through the terraform documentation on attributes it has for mounting EBS here; however, it is not clear to me how does that block device gets partitioned (or if partitioning here is relevant at all.

Explanation of what is EBS: here


问:
Return updated values from sequelize raw query
I have an operation that uses a raw query to update the database, i'd like to get the rows affected by the query as the output. Is this possible?</p>

```<code>const op = (replacements, pgdb) {
  const query = q(replacements);
  const args = [query, { replacements, type: Sequelize.QueryTypes.UPDATE, raw: true }];
  const results = await pgdb.query(...args);
  console.log(results);
  return results;
};
</code>```

答:
Yes you can. I'm using Sequelize with a PostgreSQL database. My specs are as follows:

"pg": "^7.12.1"

"sequelize": "^5.21.2"

"sequelize-cli": "^5.5.1"

I ran an update query in the following code block:

```<code>const query = `UPDATE bookings b
    SET "isPaid" = :isPaid,
        "paymentType" = :paymentType
    FROM trips t,
         requests r
    WHERE "b"."tripId" = t.id
      AND r.id = "t"."requestId"
      AND r.id = :requestId
      AND "r"."userId" = :userId
    RETURNING b.id, "isPaid", "paymentType"`;

    return db.sequelize.query(
      query, {
        replacements: {
          isPaid, paymentType, requestId, userId
        }
      }
    );
</code>```

I logged the result:

```<code>console.log('resultFromQuery', resultFromQuery);
</code>```

and got the following:

```<code>resultFromQuery [
  [
    { id: 7, isPaid: true, paymentType: 'paypal' },
    { id: 8, isPaid: true, paymentType: 'paypal' }
  ],
  Result {
    command: 'UPDATE',
    rowCount: 2,
    oid: null,
    rows: [ [Object], [Object] ],
    fields: [ [Field], [Field], [Field] ],
    _parsers: [ [Function: parser], [Function: parser], [Function: parser] ],
    _types: TypeOverrides { _types: [Object], text: {}, binary: {} },
    RowCtor: null,
    rowAsArray: false
  }
]
</code>```

I was then able to get the rowCount as follows:

```<code>console.log('resultFromQuery', resultFromQuery[1].rowCount);
</code>```

I was also able to get the updated rows themselves as follows (you can select the entire row like you did with '*' or specify the fields you want):

```<code>console.log('resultFromQuery', resultFromQuery[0]);
</code>```

Body:
I have an operation that uses a raw query to update the database, i'd like to get the rows affected by the query as the output. Is this possible?

const op = (replacements, pgdb) {
  const query = q(replacements);
  const args = [query, { replacements, type: Sequelize.QueryTypes.UPDATE, raw: true }];
  const results = await pgdb.query(...args);
  console.log(results);
  return results;
};

Body:
Yes you can. I'm using Sequelize with a PostgreSQL database. My specs are as follows:

"pg": "^7.12.1"

"sequelize": "^5.21.2"

"sequelize-cli": "^5.5.1"

I ran an update query in the following code block:

const query = `UPDATE bookings b
    SET "isPaid" = :isPaid,
        "paymentType" = :paymentType
    FROM trips t,
         requests r
    WHERE "b"."tripId" = t.id
      AND r.id = "t"."requestId"
      AND r.id = :requestId
      AND "r"."userId" = :userId
    RETURNING b.id, "isPaid", "paymentType"`;

    return db.sequelize.query(
      query, {
        replacements: {
          isPaid, paymentType, requestId, userId
        }
      }
    );

I logged the result:

console.log('resultFromQuery', resultFromQuery);

and got the following:

resultFromQuery [
  [
    { id: 7, isPaid: true, paymentType: 'paypal' },
    { id: 8, isPaid: true, paymentType: 'paypal' }
  ],
  Result {
    command: 'UPDATE',
    rowCount: 2,
    oid: null,
    rows: [ [Object], [Object] ],
    fields: [ [Field], [Field], [Field] ],
    _parsers: [ [Function: parser], [Function: parser], [Function: parser] ],
    _types: TypeOverrides { _types: [Object], text: {}, binary: {} },
    RowCtor: null,
    rowAsArray: false
  }
]

I was then able to get the rowCount as follows:

console.log('resultFromQuery', resultFromQuery[1].rowCount);

I was also able to get the updated rows themselves as follows (you can select the entire row like you did with '*' or specify the fields you want):

console.log('resultFromQuery', resultFromQuery[0]);