问:
Convert JPG to PNG
I have used the below code to

convert JPG into PNG file:

But when i am running this code from the command line terminal using: python a.py "C:\Users\nishant.gupta2\PycharmProjects\jpgtopngconverter\photo" new

The system is giving me the error:

```<code> PermissionError: [Errno 13] Permission denied: 'C:\\Users\\nishant.gupta2\\PycharmProjects\\jpgtopngconverter\\photo'
</code>```

My code is below:

```<code>import sys
import os
from PIL import Image

image_folder=sys.argv[1]

output_folder=sys.argv[2]

if not os.path.exists(output_folder):
    os.mkdir(output_folder)

for items in os.listdir(image_folder):

    im= Image.open(f'{image_folder}')
    im.save(f'{output_folder}.png','png')
</code>```

答:
You are trying to open a folder here : </p>

```<code>im= Image.open(f'{image_folder}')
</code>```

<p>rather then image. You should specify the path of image. </p>

Title: Convert JPG to PNG

Body:
I have used the below code to

convert JPG into PNG file:

But when i am running this code from the command line terminal using: python a.py "C:\Users\nishant.gupta2\PycharmProjects\jpgtopngconverter\photo" new

The system is giving me the error:

 PermissionError: [Errno 13] Permission denied: 'C:\\Users\\nishant.gupta2\\PycharmProjects\\jpgtopngconverter\\photo'

My code is below:

import sys
import os
from PIL import Image

image_folder=sys.argv[1]

output_folder=sys.argv[2]

if not os.path.exists(output_folder):
    os.mkdir(output_folder)

for items in os.listdir(image_folder):

    im= Image.open(f'{image_folder}')
    im.save(f'{output_folder}.png','png')

Body:
You are trying to open a folder here :

im= Image.open(f'{image_folder}')

rather then image. You should specify the path of image.


来源: stackexchange

答:
I hope this will help to.
I place all your list elements in a separate file named lista.txt
In this example I will get your list from file... I like to be more organizated and to have separate files you can do in on python as well, but the idea is you need to get all elements from list one by one (while function or for function) and to add them to a temporary list by checking if the new items already exist, if is exist pass and then you can sample use .sort() because will do the trick and with numbers.

```<code># Global variables
file = "lista.txt"
tempList = []

# Logic get items from file
def GetListFromFile(fileName):
    # Local variables
    showDoneMsg = True

    # Try to run this code
    try:
        # Open file and try to read it
        with open(fileName, mode="r") as f:
            # Define line
            line = f.readline()
            # For every line in file
            while line:
                # Get out all end white space (\n, \r)
                item = line.rstrip()

                # Check if this item is not allready in the list
                if item not in tempList:
                    # Append item to a temporar list
                    tempList.append(item)
                # Show me if a itmes allready exist
                else:
                    print("Dublicate >>", item)

                # Go to new line
                line = f.readline()
        # This is optional because is callet automatical
        # but I like to be shore
        f.close()

    # Execptions
    except FileNotFoundError:
        print("ERROR >> File do not exist!")
        showDoneMsg = False

    # Sort the list
    tempList.sort()
    # Show me when is done if file exist
    if showDoneMsg == True:
        print("\n>>> DONE <<<\n")

# Logic show list items
def ShowListItems(thisList):
    if len(thisList) == 0:
        print("Temporary list is empty...")
    else:
        print("This is new items list:")
        for i in thisList:
            print(i)

# Execute function
GetListFromFile(file)
# Testing if items was sorted
ShowListItems(tempList)
</code>```

Out put:

```<code>========================= RESTART: D:\Python\StackOverflow\help.py =========================
Dublicate >> 43273,-166.666666666667,4,3,1,100,0,0

>>> DONE <<<

21082,-250,4,3,1,100,0,0
21082,410.958904109589,4,3,1,60,1,0
22725,-142.857142857143,4,3,1,100,0,0
...
474434,-166.666666666667,4,3,1,100,0,0
481477,-100,4,3,1,100,0,1
531564,259.011439671919,4,3,1,60,1,0
>>>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sort list of strings numerically and filter duplicates?

Body:
Given a list of strings in the following format:

[
    "464782,-100,4,3,1,100,0,0"
    "465042,-166.666666666667,4,3,1,100,0,0",
    "465825,-250.000000000001,4,3,1,100,0,0",
    "466868,-166.666666666667,4,3,1,100,0,0",
    "467390,-200.000000000001,4,3,1,100,0,0",
    "469999,-100,4,3,1,100,0,0",
    "470260,-166.666666666667,4,3,1,100,0,0",
    "474173,-100,4,3,1,100,0,0",
    "474434,-166.666666666667,4,3,1,100,0,0",
    "481477,-100,4,3,1,100,0,1",
    "531564,259.011439671919,4,3,1,60,1,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "21082,410.958904109589,4,3,1,60,1,0",
    "21082,-250,4,3,1,100,0,0",
    "22725,-142.857142857143,4,3,1,100,0,0",
    "23547,-166.666666666667,4,3,1,100,0,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "27657,-200.000000000001,4,3,1,100,0,0",
    "29301,-142.857142857143,4,3,1,100,0,0",
    "30123,-166.666666666667,4,3,1,100,0,0",
    "30945,-250,4,3,1,100,0,0",
    "32588,-166.666666666667,4,3,1,100,0,0",
    "34232,-250,4,3,1,100,0,0",
    "35876,-142.857142857143,4,3,1,100,0,0",
    "36698,-166.666666666667,4,3,1,100,0,0",
    "37520,-250,4,3,1,100,0,0",
    "42451,-142.857142857143,4,3,1,100,0,0",
    "43273,-166.666666666667,4,3,1,100,0,0",
]

How can I sort the list based on the first number in each line with python?
And then, once sorted, remove all duplicates, if any are there?

The sorting criteria for the list is the number before the first comma in each line, which is always an integer.

I tried using list.sort() , however, this sorts the items in lexical order, not numerically.

Body:
I hope this will help to.
I place all your list elements in a separate file named lista.txt
In this example I will get your list from file... I like to be more organizated and to have separate files you can do in on python as well, but the idea is you need to get all elements from list one by one (while function or for function) and to add them to a temporary list by checking if the new items already exist, if is exist pass and then you can sample use .sort() because will do the trick and with numbers.

# Global variables
file = "lista.txt"
tempList = []

# Logic get items from file
def GetListFromFile(fileName):
    # Local variables
    showDoneMsg = True

    # Try to run this code
    try:
        # Open file and try to read it
        with open(fileName, mode="r") as f:
            # Define line
            line = f.readline()
            # For every line in file
            while line:
                # Get out all end white space (\n, \r)
                item = line.rstrip()

                # Check if this item is not allready in the list
                if item not in tempList:
                    # Append item to a temporar list
                    tempList.append(item)
                # Show me if a itmes allready exist
                else:
                    print("Dublicate >>", item)

                # Go to new line
                line = f.readline()
        # This is optional because is callet automatical
        # but I like to be shore
        f.close()

    # Execptions
    except FileNotFoundError:
        print("ERROR >> File do not exist!")
        showDoneMsg = False

    # Sort the list
    tempList.sort()
    # Show me when is done if file exist
    if showDoneMsg == True:
        print("\n>>> DONE <<<\n")

# Logic show list items
def ShowListItems(thisList):
    if len(thisList) == 0:
        print("Temporary list is empty...")
    else:
        print("This is new items list:")
        for i in thisList:
            print(i)

# Execute function
GetListFromFile(file)
# Testing if items was sorted
ShowListItems(tempList)

Out put:

========================= RESTART: D:\Python\StackOverflow\help.py =========================
Dublicate >> 43273,-166.666666666667,4,3,1,100,0,0

>>> DONE <<<

21082,-250,4,3,1,100,0,0
21082,410.958904109589,4,3,1,60,1,0
22725,-142.857142857143,4,3,1,100,0,0
...
474434,-166.666666666667,4,3,1,100,0,0
481477,-100,4,3,1,100,0,1
531564,259.011439671919,4,3,1,60,1,0
>>>


问:
Can you embed a whole webpage into c++ source?
Is there an equivalent to go.rice for c++ that can embed a react app into c++ source so it can be compiled into the binary? I know things like xxd can embed a single file into a c array, but I need something that works on multiple files and preserves paths and whatnot for use with an embedded htttp server.</p>

答: I wrote a more efficient alternative to xxd -i (here) and a shell script that uses it (here) that generate a header included in the server source file here, and it works great. The c program is extremely unpolished and the script is specific to my directory structure (which is not commited to github right now), but this solution could easily be adapted for other projects.</p>


问:
How to set a dynamic RoleMappings key for a IndentityPoolRoleAttachment in CloudFormation
I am building a stack to initialize a Cognito installation. As part of this I have setup user groups with associated roles. I need to set the Choose role from token option, allowing identities to use roles from the group(s) to which they are assigned.

This is done through the RoleMappings object in the IndentityPoolRoleAttachment object. This mappings object is a string -> object map, where the string represents the identity provider. In my case, this is:

cognito-idp.${some-region}.amazonaws.com/${some-userpool-id}:${some-pool-client-id}

Obviously, this needs to be dynamically built based on values in the stack, but I havent found a way to do this in a syntactically correct manner. Using Ref and Fn::Sub both result in syntactical errors. I have tried in both yaml and json syntax.

Am I missing something obvious?

答:
Got stuck on this problem recently and I visited the thread from @AkkarinZA's comment.

In that thread, @mikef's response worked for me. We can use cognitoProvider key.

```<code>RoleMappings:
     cognitoProvider:
       IdentityProvider:
        Fn::Join:
          - ''
          - - "cognito-idp.${self:provider.region}.amazonaws.com/"
            - !Ref CustomerUserPool
            - ':'
            - !Ref CustomerUserPoolClient
       AmbiguousRoleResolution: Deny
       Type: Rules
       RulesConfiguration:
          Rules:
            - Claim: cognito:groups
              MatchType: Contains
              Value: "clients"
              RoleARN:
                { Fn::GetAtt: [UserIdentityPoolClientRole, Arn] }

</code>```

ContentLicense: CC BY-SA 3.0

Body:
Got stuck on this problem recently and I visited the thread from @AkkarinZA's comment.

In that thread, @mikef's response worked for me. We can use cognitoProvider key.

RoleMappings:
     cognitoProvider:
       IdentityProvider:
        Fn::Join:
          - ''
          - - "cognito-idp.${self:provider.region}.amazonaws.com/"
            - !Ref CustomerUserPool
            - ':'
            - !Ref CustomerUserPoolClient
       AmbiguousRoleResolution: Deny
       Type: Rules
       RulesConfiguration:
          Rules:
            - Claim: cognito:groups
              MatchType: Contains
              Value: "clients"
              RoleARN:
                { Fn::GetAtt: [UserIdentityPoolClientRole, Arn] }


问:
Parent-Child Gridview in ASP.net
I have two GridView in ASP.net 3.5 page. I have HyperLink field as one of the fields in the First GridView.

On click of this hyperlink I need to call display the 2nd grid by passing some values to a method showAllRecords(value from hyperlink)

How do I do this?

Thanks

答:
Maybe the following blog post could give you a hint;

http://www.tugberkugurlu.com/archive/parent-child-view-in-a-single-table-with-gridview-control-on-asp-net-web-forms

ContentLicense: CC BY-SA 2.5

Title: Parent-Child Gridview in ASP.net


问:
looping with if condition versus ternary operator which is more faster any why
which of the below if more efficient and why

Looping through a list and checking the greatest and summing into a integer

```<code>    public List<Integer> returnComparision(List<Integer> a, List<Integer> b){

        List<Integer> resultLoop = null;
        int aResult = 0;
        int bResult=0;
        for(int i=0; i <a.size() ; i++){
            if(a.get(0) > b.get(0)){
                aResult += 1;
            }
            else {
                bResult += 1;
            }

        }
        resultLoop.add(aResult);
        resultLoop.add(bResult);

        return resultLoop;
    }
</code>```

or using ternary to push the total into List

```<code>public List<Integer> returnComparision(List<Integer> a, List<Integer> b){

        List<Integer> result = null;

        result.add( ((a.get(0) > b.get(0)?1:0)  + ((a.get(1) > b.get(1))?1:0)) + ((a.get(2) > b.get(2))?1:0) );
        result.add( ((b.get(0) > a.get(0)?1:0)  + ((b.get(1) > a.get(1))?1:0)) + ((b.get(2) > a.get(2))?1:0) );

        return result;
    }
</code>```

答: Neither is faster. They will compile to the same bytecode - a ternary operation is the same as an if/else statement. It is just syntactical sugar.

Body:
which of the below if more efficient and why

Looping through a list and checking the greatest and summing into a integer

    public List<Integer> returnComparision(List<Integer> a, List<Integer> b){

        List<Integer> resultLoop = null;
        int aResult = 0;
        int bResult=0;
        for(int i=0; i  b.get(0)){
                aResult += 1;
            }
            else {
                bResult += 1;
            }

        }
        resultLoop.add(aResult);
        resultLoop.add(bResult);

        return resultLoop;
    }

or using ternary to push the total into List

public List<Integer> returnComparision(List<Integer> a, List<Integer> b){

        List<Integer> result = null;

        result.add( ((a.get(0) > b.get(0)?1:0)  + ((a.get(1) > b.get(1))?1:0)) + ((a.get(2) > b.get(2))?1:0) );
        result.add( ((b.get(0) > a.get(0)?1:0)  + ((b.get(1) > a.get(1))?1:0)) + ((b.get(2) > a.get(2))?1:0) );

        return result;
    }


问:
Is it possible to pass username and password in makefile?
Hi I'm using makefile to do lots of compiling and remote works.

In many occasion I would need to type in username and password for remote connection, VPN, code upload and other stuffs.

May it be possible to use makefile to auto type in the credential information?

Thanks a lot!

答:
It is not the role of make to do this kind of thing.  So there is no special support in a Makefile for handling credentials.

However, if you can get a shell script to do the "auto-typing" or provide the required credentials some other way, then you should be able to use the same approach in a Makefile.

We can't advise you on how the script would work, because you have given no actual details of the commands etc that you are using for remote access.

But if you are using ssh from a Linux box, you could use public key authentication and ssh-agent and avoid the problem entirely.  This would be a lot more secure than:

using user / password auth at all, and

embedding passwords in your makefiles ... for someone else to find when they steal your laptop or whatever.


问:
Lottery program c# saving and comparing winning numbers in lists
I have seemed to hit a dead-end in my coding of a lottery program in c# and I am looking for some pointer. What I am trying to do is let the user enter 7 numbers, which will be their lottery "ticket" then I want to draw one or multiple 7 digits winning numbers and compare it to the user's number and see how many times they had 5 correct answers, 6 correct answers and so on. This is what I currently am doing

```<code>while(a counter < the number of times I want to draw a winning number )
{
 add the users 7 numbers to a list

 add 7 random numbers to a list

 compare and see how many winnings

 track how many times 5 correct, 6 correct, etc

 loop until number of times I want to draw a winning number

}
</code>```

this does work, but if I draw a winning number 100 000 times, some of the lots will repeat so to say, and i don't want that

this is what I would want to do

add the users 7 digits to some sort of list (easy)

add 1000(for example) unique winning lots to a list (2, 1, 16, 32, 5, 9, 17 could be a winner for example)

compare the users 7 numbers to the 1000 winning lots and see how many times I got a certain amount of numbers correct

can I get some pointers or ideas of how I should accomplish this? maybe I can use a HashSet? since they only allow unique numbers, but how would I add the lots to the list since I don't want to add them like this 7321114181923 but rather 7 32 11 14 18 19 23

答:
Create array list or a int list: Of entered numbers, and of random numbers

"add the users 7 numbers to a list ~
get system input 7 times with loop.

add 7 random numbers to a list ~
Use Math > Random to add numbers to a list

compare and see how many winnings ~
Compare each number of the list to an entered list, array comparison.

track how many times 5 correct, 6 correct, etc ~
this is where a second counter comes in

loop until number of times I want to draw a winning number ~
this can be tracked with another counter"

Sorry, for a text explanation, you gave me text, so I gave you some text, you gave me nothing to work with.

Also, you can use string manipulation functions to add a " " to each printed number.

Body:
I have seemed to hit a dead-end in my coding of a lottery program in c# and I am looking for some pointer. What I am trying to do is let the user enter 7 numbers, which will be their lottery "ticket" then I want to draw one or multiple 7 digits winning numbers and compare it to the user's number and see how many times they had 5 correct answers, 6 correct answers and so on. This is what I currently am doing

while(a counter < the number of times I want to draw a winning number )
{
 add the users 7 numbers to a list

 add 7 random numbers to a list

 compare and see how many winnings

 track how many times 5 correct, 6 correct, etc

 loop until number of times I want to draw a winning number

}

this does work, but if I draw a winning number 100 000 times, some of the lots will repeat so to say, and i don't want that

this is what I would want to do

add the users 7 digits to some sort of list (easy)

add 1000(for example) unique winning lots to a list (2, 1, 16, 32, 5, 9, 17 could be a winner for example)

compare the users 7 numbers to the 1000 winning lots and see how many times I got a certain amount of numbers correct

can I get some pointers or ideas of how I should accomplish this? maybe I can use a HashSet? since they only allow unique numbers, but how would I add the lots to the list since I don't want to add them like this 7321114181923 but rather 7 32 11 14 18 19 23


问:
Lift a key’s values to top level whilst preserving rest of object using Ramda
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

```<code>{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}
</code>```

The result I am after:

```<code>{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}
</code>```

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

答:
You can use the spread operator.

const startingWithAllProps = {
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}

const startingWithoutRecord = {
  tag_ids: [
    2091
  ]
}

const startingWithoutTagIds = {
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  }
}

const moveRecordUpOneLevel = (startingObject) => {
  const temp = {
    ...startingObject.record,
    tag_ids: startingObject.tag_ids
  }
  return JSON.parse(JSON.stringify(temp)) // To remove any undefined props
}

const afterTransformWithAllProps = moveRecordUpOneLevel(startingWithAllProps)
const afterTransformWithoutRecord = moveRecordUpOneLevel(startingWithoutRecord)
const afterTransformWithoutTagIds = moveRecordUpOneLevel(startingWithoutTagIds)

console.log('afterTransformWithAllProps', afterTransformWithAllProps)
console.log('afterTransformWithoutRecord', afterTransformWithoutRecord)
console.log('afterTransformWithoutTagIds', afterTransformWithoutTagIds)```

Body:
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}

The result I am after:

{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.


问:
R: Subscripted assignments not overwriting values, or changing all values (halfway figured out)
I have had a problem in my R code that comes up from time to time, where I will try to overwrite values of a variable using a subscripted assignment, and some/all of the values do not get overwritten. (I have since figured out half of the problem, but the second half of the question still applies.)

Here is a simplified example of the code, which compares two variables to see which one is bigger, then finds places where they are equal and sets the "is bigger" variable to -1 to indicate that neither is bigger.

```<code>a <- rep(0:2,96)
b <- rep(0:3,72)
dataset <- data.frame(cbind(a,b))
dim(dataset) # Show dimensions

> [1] 288   2

# Add a few random NAs
dataset$a[15] <- NA
dataset$b[27] <- NA
dataset$a_bigger <- (dataset$a > dataset$b)
dataset$b_bigger <- (dataset$b > dataset$a)
table(dataset[,c('a_bigger','b_bigger')],useNA='ifany')

>        b_bigger
>a_bigger FALSE TRUE <NA>
>   FALSE    70  144    0
>   TRUE     72    0    0
>   <NA>      0    0    2

dataset$same <- (dataset$a == dataset$b) # Find values where they are the same and neither is bigger
table(dataset$same,useNA='ifany') # Show that there are NAs in dataset$same.

> FALSE  TRUE  <NA>
>  216    70     2

dataset$same[is.na(dataset$a) | is.na(dataset$b)] <- 0 # Fix the NAs. A and B can't be the same if one of them is NA.
table(dataset$same,useNA='ifany') # Show that there are no longer NAs

>   0   1
> 218  70

dataset$a_bigger[dataset$same] <- -1
dataset$b_bigger[dataset$same] <- -1
table(dataset[,c('a_bigger','b_bigger')],useNA='ifany') # Wait, there should be 70 changed, not 1...?

>         b_bigger
> a_bigger  -1   0   1 <NA>
>    -1     1   0   0    0
>    0      0  69 144    0
>    1      0  72   0    0
>    <NA>   0   0   0    2
</code>```

Up to this point, I have figured out what happened. Setting a few values of "same" to 0 changed it from logical true/false to 0/1, and then when I used it to index another variable, the "1s" were taken to mean "overwrite the first row" instead of as logical trues.

This had me confused since in other contexts R will treat 0/1 as equivalent to true/false (in fact, if I rewrite the assignment line as dataset$a_bigger[dataset$same & dataset$same] <- -1, that works) but at least I can understand what's happening now.

But I still don't understand why it does this:

```<code>dataset$even_weirder[dataset$same] <- -1 # But now if I do the assignment on a column/variable that's not initialized...
table(dataset[,'even_weirder'],useNA='ifany') # They all change!!!

>  -1
> 288
</code>```

If it really thinks that when I write dataset$somevar[dataset$same] I'm referring to position 0 (which it ignores) and position 1 (which it overwrites over and over), then when I do it with an uninitialized column why does it assign -1 to every row instead of assigning it to the first row and leaving the rest NA?

Body:
I have had a problem in my R code that comes up from time to time, where I will try to overwrite values of a variable using a subscripted assignment, and some/all of the values do not get overwritten. (I have since figured out half of the problem, but the second half of the question still applies.)

Here is a simplified example of the code, which compares two variables to see which one is bigger, then finds places where they are equal and sets the "is bigger" variable to -1 to indicate that neither is bigger.

a <- rep(0:2,96)
b <- rep(0:3,72)
dataset <- data.frame(cbind(a,b))
dim(dataset) # Show dimensions

> [1] 288   2

# Add a few random NAs
dataset$a[15] <- NA
dataset$b[27] <- NA
dataset$a_bigger <- (dataset$a > dataset$b)
dataset$b_bigger <- (dataset$b > dataset$a)
table(dataset[,c('a_bigger','b_bigger')],useNA='ifany')

>        b_bigger
>a_bigger FALSE TRUE <NA>
>   FALSE    70  144    0
>   TRUE     72    0    0
>   <NA>      0    0    2

dataset$same <- (dataset$a == dataset$b) # Find values where they are the same and neither is bigger
table(dataset$same,useNA='ifany') # Show that there are NAs in dataset$same.

> FALSE  TRUE  <NA>
>  216    70     2

dataset$same[is.na(dataset$a) | is.na(dataset$b)] <- 0 # Fix the NAs. A and B can't be the same if one of them is NA.
table(dataset$same,useNA='ifany') # Show that there are no longer NAs

>   0   1
> 218  70

dataset$a_bigger[dataset$same] <- -1
dataset$b_bigger[dataset$same] <- -1
table(dataset[,c('a_bigger','b_bigger')],useNA='ifany') # Wait, there should be 70 changed, not 1...?

>         b_bigger
> a_bigger  -1   0   1 <NA>
>    -1     1   0   0    0
>    0      0  69 144    0
>    1      0  72   0    0
>    <NA>   0   0   0    2

Up to this point, I have figured out what happened. Setting a few values of "same" to 0 changed it from logical true/false to 0/1, and then when I used it to index another variable, the "1s" were taken to mean "overwrite the first row" instead of as logical trues.

This had me confused since in other contexts R will treat 0/1 as equivalent to true/false (in fact, if I rewrite the assignment line as dataset$a_bigger[dataset$same & dataset$same] <- -1, that works) but at least I can understand what's happening now.

But I still don't understand why it does this:

dataset$even_weirder[dataset$same] <- -1 # But now if I do the assignment on a column/variable that's not initialized...
table(dataset[,'even_weirder'],useNA='ifany') # They all change!!!

>  -1
> 288

If it really thinks that when I write dataset$somevar[dataset$same] I'm referring to position 0 (which it ignores) and position 1 (which it overwrites over and over), then when I do it with an uninitialized column why does it assign -1 to every row instead of assigning it to the first row and leaving the rest NA?

Body:
The issue is basically

class(dataset$same)
#[1] "numeric"

which is not logical but binary i.e. 0 and 1

head(dataset$same)
#[1] 1 1 1 0 0 0

Instead it should be

as.logical(dataset$same)

Because the assignment is haappening at index position 1 i.e. the value -1 is getting updated on the 1st element and not anywhere else

dataset$a_bigger[as.logical(dataset$same)] <- -1
dataset$b_bigger[as.logical(dataset$same)] <- -1

table(dataset[,c('a_bigger','b_bigger')],useNA='ifany')
#        b_bigger
#a_bigger  -1   0   1 <NA>
#    -1    70   0   0    0   #### 70 is showing up now
#    0      0   0 144    0
#    1      0  72   0    0
#    <NA>   0   0   0    2

Regarding the 'even_weider', it is created on the fly and because of that the first element when it gets assigned to -1, gets recycled to the entire length of the column

dataset$even_weirder[dataset$same]
#NULL
dataset$even_weirder[dataset$same] <- -1
sum(dataset$same)
#[1] 70
table(dataset[,'even_weirder'],useNA='ifany')

# -1
#288
dataset$even_weirder
#  [1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
# [39] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
# [77] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
#[115] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
#[153] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
#[191] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
#[229] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
#[267] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1


问:
How to set HOMEDRIVE from H drive to C drive
I have been looking at examples in SO but I think some of the answers are outdated and some I don't seem I can apply.

Basically I want to set my HOMEDRIVE to point to the C drive from the H drive but when I try to change this, it reverts back to H Drive after I open up command window. This maybe due to login but can somebody give me a guide in order to point my HOMEDRIVE correctly?

I cannot see HOMEDRIVE in the environment variables by the way. I tried changing in regedit earlier but no luck.

Thanks

答:
This issue had been really frustrating me trying to find a solution, but I have found what I think is the definitive answer. The computer I usually use has Windows 10 Pro installed and setting a home folder for a user is a trivial task using lusrmgr.msc. However, I also sometimes use another computer that has Windows 10 Home installed, and you can't run lusrmgr.msc on that edition (trying to run it displays an error message saying 'This snapin may not be used with this edition of Windows 10').

Various methods for setting a home folder are described at https://support.microsoft.com/en-us/help/816313/how-to-assign-a-home-folder-to-a-user. The answer turned out to be to open a command prompt with administrator privileges and then use the command line method described on that webpage.

First, run 'net user' to get a list of the usernames known on the local system.

Then, run 'net user USERNAME /homedir:PATH' where USERNAME is the name of the user you are trying to change and PATH is the drive letter and full path to the desired home folder, which must already exist.

For example, to set the home folder for user Fred to H:\Users\Fred type:

net user Fred /homedir:H:\Users\Fred

After Fred next logs in, the HOMEDRIVE volatile environment variable will be set to H: and HOMEPATH will be set to \Users\Fred


问:
How to add a 'default using' to all cshtml pages?
I'm creating my first MVC.Net application and I find myself including @using Gideon.Core.Mvc; on almost every page. Is it possible to add it by default to all pages?

In Asp.Net I'm able to add default stuff for controls to the web.config, hopefully it can be done for MVC.Net as well.

答:
You can add them in the <system.web.webPages.razor> section in Views/Web.config.

Here is the default:

```<code><system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
        </namespaces>
    </pages>
</system.web.webPages.razor>
</code>```

Body:
You can add them in the <system.web.webPages.razor> section in Views/Web.config.

Here is the default:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
        </namespaces>
    </pages>
</system.web.webPages.razor>


问:
Writing basic test code for my Postgres objects
I'd like to build up some test code for various objects in my Postgres 11.5 database, and am wondering if there is a straightforward way to implement simple checks in straight SQL. As an example, I've got a simple domain that accepts any of three values, case-blind. This is just one example I've picked because the test cases are finite and simple.

```<code>DROP DOMAIN IF EXISTS domains.test_outcome;

CREATE DOMAIN domains.test_outcome AS
    citext
    NOT NULL
    CONSTRAINT test_outcome_legal_values
        CHECK(
            VALUE IN ('pass','warning','fail')
     );

COMMENT ON DOMAIN domains.test_outcome IS
    'The test_outcome must be pass, warning, or fail, case-insensitive.';
</code>```

Below are some simple test statements that exercise good and bad values:

```<code>-- Good values
select 'warning'::test_outcome;
select 'fail'::test_outcome;
select 'PASS'::test_outcome;
select 'WARNING'::test_outcome;
select 'FAIL'::test_outcome;

-- Bad values
select NULL::test_outcome;
select ''::test_outcome;
select 'foo'::test_outcome;
</code>```

What I'd like to do, is get a single line for each case, and not blow up on an error. I've tried using a DO block, and could use a PL/PgSQL function. Here's the DO code I've tried:

```<code>DO $TESTS$

BEGIN
-- Good values
    select 'warning'::test_outcome;
    select 'fail'::test_outcome;
    select 'PASS'::test_outcome;
    select 'WARNING'::test_outcome;
    select 'FAIL'::test_outcome;

-- Bad values
    select NULL::test_outcome;
    select ''::test_outcome;
    select 'foo'::test_outcome;

EXCEPTION WHEN OTHERS THEN
      RAISE NOTICE 'Error Name:%',  SQLERRM;
      RAISE NOTICE 'Error State:%', SQLSTATE;
END;
$TESTS$
</code>```

What I get back are a couple of notices. I can't tie those back to the specific statement, as far as I can tell, and I get nothing for success cases.

```<code>NOTICE:  Error Name:query has no destination for result data
NOTICE:  Error State:42601
DO
Command completed successfully. (Line 20)
</code>```

I've seen that there are some unit testing frameworks for PG around, using languages we don't use. Is there any way to do simple tests like the ones above in straight SQL or PL/PgSQL?

答:
There is nothing that I know of, but perhaps the following can provide a template for you.

I needed to modify your domain definition slightly removing the NOT NULL constraint in it. The script below declares a working variable of the test_outcome. However Postgres enforces the NOT NULL thus not allowing the declaration. (A bug if you ask me, but ...). In this case not a great loss as NULL in not in the list of valid values at any rate.

```<code>CREATE DOMAIN test_outcome AS
    citext
   -- NOT NULL
    CONSTRAINT test_outcome_legal_values
        CHECK(
            VALUE IN ('pass','warning','fail')
     );
</code>```

The idea is to create an array of test items and iterate that array assigning each value to the the declared domain variable and capture any exception. Note this part is within an inner begin...end block. That prevents script termination when the errors are generated.  For this type/level of testing I like to record successful test as well as failures so I have a raise notice for those as well.

```<code>do $$
declare
   -- list items to be tested
   test_set text[] = $Q${warning,Fail,pass,WARNING,FAIL,null,'',foo}$Q$;

   -- define variable of data type being testes
   indx_val test_outcome;

   -- variable to contain text value
   indx     text;
begin
    -- loop through test set,
    -- Note the index variable must of same base type as array
    foreach indx in array test_set
    loop

        begin
            indx_val = indx;  -- assign test
            raise notice 'Testing: <%>. Successful.',indx;

            -- capture error in assign above
            exception when others then
                raise notice 'Testing: <%>. Failed.',indx;
                raise notice '  *Error Name:%',  sqlerrm;
                raise notice '  *Error State:%', sqlstate;
        end ;
    end loop;

exception when others then
      raise notice 'Error Name:%',  sqlerrm;
      raise notice 'Error State:%', sqlstate;
END;
$$;
</code>```

You should be able to adapt this general format other type definitions. Good Luck!

Body:
I'd like to build up some test code for various objects in my Postgres 11.5 database, and am wondering if there is a straightforward way to implement simple checks in straight SQL. As an example, I've got a simple domain that accepts any of three values, case-blind. This is just one example I've picked because the test cases are finite and simple.

DROP DOMAIN IF EXISTS domains.test_outcome;

CREATE DOMAIN domains.test_outcome AS
    citext
    NOT NULL
    CONSTRAINT test_outcome_legal_values
        CHECK(
            VALUE IN ('pass','warning','fail')
     );

COMMENT ON DOMAIN domains.test_outcome IS
    'The test_outcome must be pass, warning, or fail, case-insensitive.';

Below are some simple test statements that exercise good and bad values:

-- Good values
select 'warning'::test_outcome;
select 'fail'::test_outcome;
select 'PASS'::test_outcome;
select 'WARNING'::test_outcome;
select 'FAIL'::test_outcome;

-- Bad values
select NULL::test_outcome;
select ''::test_outcome;
select 'foo'::test_outcome;

What I'd like to do, is get a single line for each case, and not blow up on an error. I've tried using a DO block, and could use a PL/PgSQL function. Here's the DO code I've tried:

DO $TESTS$

BEGIN
-- Good values
    select 'warning'::test_outcome;
    select 'fail'::test_outcome;
    select 'PASS'::test_outcome;
    select 'WARNING'::test_outcome;
    select 'FAIL'::test_outcome;

-- Bad values
    select NULL::test_outcome;
    select ''::test_outcome;
    select 'foo'::test_outcome;

EXCEPTION WHEN OTHERS THEN
      RAISE NOTICE 'Error Name:%',  SQLERRM;
      RAISE NOTICE 'Error State:%', SQLSTATE;
END;
$TESTS$

What I get back are a couple of notices. I can't tie those back to the specific statement, as far as I can tell, and I get nothing for success cases.

NOTICE:  Error Name:query has no destination for result data
NOTICE:  Error State:42601
DO
Command completed successfully. (Line 20)

I've seen that there are some unit testing frameworks for PG around, using languages we don't use. Is there any way to do simple tests like the ones above in straight SQL or PL/PgSQL?

Body:
There is nothing that I know of, but perhaps the following can provide a template for you.

I needed to modify your domain definition slightly removing the NOT NULL constraint in it. The script below declares a working variable of the test_outcome. However Postgres enforces the NOT NULL thus not allowing the declaration. (A bug if you ask me, but ...). In this case not a great loss as NULL in not in the list of valid values at any rate.

CREATE DOMAIN test_outcome AS
    citext
   -- NOT NULL
    CONSTRAINT test_outcome_legal_values
        CHECK(
            VALUE IN ('pass','warning','fail')
     );

The idea is to create an array of test items and iterate that array assigning each value to the the declared domain variable and capture any exception. Note this part is within an inner begin...end block. That prevents script termination when the errors are generated.  For this type/level of testing I like to record successful test as well as failures so I have a raise notice for those as well.

do $$
declare
   -- list items to be tested
   test_set text[] = $Q${warning,Fail,pass,WARNING,FAIL,null,'',foo}$Q$;

   -- define variable of data type being testes
   indx_val test_outcome;

   -- variable to contain text value
   indx     text;
begin
    -- loop through test set,
    -- Note the index variable must of same base type as array
    foreach indx in array test_set
    loop

        begin
            indx_val = indx;  -- assign test
            raise notice 'Testing: <%>. Successful.',indx;

            -- capture error in assign above
            exception when others then
                raise notice 'Testing: <%>. Failed.',indx;
                raise notice '  *Error Name:%',  sqlerrm;
                raise notice '  *Error State:%', sqlstate;
        end ;
    end loop;

exception when others then
      raise notice 'Error Name:%',  sqlerrm;
      raise notice 'Error State:%', sqlstate;
END;
$$;

You should be able to adapt this general format other type definitions. Good Luck!


问:
Array function for calculating Option prices
I'm trying to implement my first BS option model in Python.Instead of passing one Underlying price at a time however, I would like to pass an array. Here's the code and the error message:

```<code>xS=np.arange(10,110,10)

C=np.maximum(xS-K,0)

def bsm_call(S,K,T,r,sigma):

    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]

    d2=[d1-sigma*pow(T,0.5)]

    vC=[S * stats.norm.cdf(d1,0,1) - K * exp(-r*T) * stats.norm.cdf(d2,0,1)]

    return np.array(vC)

extC=bsm_call(xS,K,T,r,sigma)
</code>```

generates: TypeError: unsupported operand type(s) for -: 'list' and 'float'

Not sure what this means, but I think it doesn't like the way I'm passing the xS array. So just to test, I tried:

```<code>def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    return np.array(d1)

test1=test(xS,K,T,r,sigma)
print(test1)
</code>```

This gave me some values for d1 (not sure if they are correct....but at-least the code worked). So, encouraged by this, I tried adding a second line:

```<code>def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    d2=[d1-sigma*pow(T,0.5) for S in xS]
    return np.array(d1+d2)

test1=test(xS,K,T,r,sigma)
print(test1)
</code>```

The error message is now:

I'm trying to avoid looping through the xS array "directly". Obviously, not nuanced enough in Python to to do it....would appreciate some suggestions. Thanks,C

答:
I tried the suggestion from @Prune...coudln't get the syntax to work. So i tried this -

```<code>def bsm_call(S,K,T,r,sigma):
    d1=(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5))
    d2=d1-sigma*pow(T,0.5)
    vC=S * stats.norm.cdf(d1,0,1) - K * exp(-r*T) * stats.norm.cdf(d2,0,1)
    return vC

extC=[]
for i in xS:
   #print(i)
   extC.append(bsm_call(i,K,T,r,sigma))
   print(i)
print(extC)
</code>```

and was able to pass elements of the stock price array into the BS call function. I was trying to do it one step...but I guess this works for now.

Body:
I'm trying to implement my first BS option model in Python.Instead of passing one Underlying price at a time however, I would like to pass an array. Here's the code and the error message:

xS=np.arange(10,110,10)

C=np.maximum(xS-K,0)

def bsm_call(S,K,T,r,sigma):

    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]

    d2=[d1-sigma*pow(T,0.5)]

    vC=[S * stats.norm.cdf(d1,0,1) - K * exp(-r*T) * stats.norm.cdf(d2,0,1)]

    return np.array(vC)

extC=bsm_call(xS,K,T,r,sigma)

generates: TypeError: unsupported operand type(s) for -: 'list' and 'float'

Not sure what this means, but I think it doesn't like the way I'm passing the xS array. So just to test, I tried:

def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    return np.array(d1)

test1=test(xS,K,T,r,sigma)
print(test1)

This gave me some values for d1 (not sure if they are correct....but at-least the code worked). So, encouraged by this, I tried adding a second line:

def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    d2=[d1-sigma*pow(T,0.5) for S in xS]
    return np.array(d1+d2)

test1=test(xS,K,T,r,sigma)
print(test1)

The error message is now:

I'm trying to avoid looping through the xS array "directly". Obviously, not nuanced enough in Python to to do it....would appreciate some suggestions. Thanks,C

Body:
I tried the suggestion from @Prune...coudln't get the syntax to work. So i tried this -

def bsm_call(S,K,T,r,sigma):
    d1=(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5))
    d2=d1-sigma*pow(T,0.5)
    vC=S * stats.norm.cdf(d1,0,1) - K * exp(-r*T) * stats.norm.cdf(d2,0,1)
    return vC

extC=[]
for i in xS:
   #print(i)
   extC.append(bsm_call(i,K,T,r,sigma))
   print(i)
print(extC)

and was able to pass elements of the stock price array into the BS call function. I was trying to do it one step...but I guess this works for now.


问:
Scroll down until invisible element becomes visible using Selenium
I want to scroll down on a page until a certain criteria is met.
The criteria is that the date of the latest visible soccer match is earlier than the reference date.
I wrote the following script:

```<code>from selenium import webdriver
from datetime import datetime
from time import sleep

if __name__ == '__main__':
   driver = webdriver.Chrome()
   driver.get('https://hdmatches.com/category/premier-league/')
   matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
   last_date = \
       matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
       -1].find_element_by_class_name('item-details').find_element_by_class_name(
       'td-module-meta-info').find_element_by_class_name('td-post-date').text
   last_date = datetime.strptime(last_date, '%B %d, %Y').date()
   start_season = datetime.strptime('2017-8-11', '%Y-%m-%d').date()

   while last_date > start_season:
      load_more = matches.find_element_by_xpath('//div[@class="td-load-more-wrap td-load-more-infinite-wrap"]')
      driver.execute_script("arguments[0].scrollIntoView();", load_more)
      matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
      last_date = \
          matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
          -1].find_element_by_class_name('item-details').find_element_by_class_name(
          'td-module-meta-info').find_element_by_class_name('td-post-date').text
      last_date = datetime.strptime(last_date, '%B %d, %Y').date()
</code>```

My script doesn't work sofar (nothing happens) and I think it because of the below element:

While scrolling down, this element is two times visible when the page is loading. Afterwards, the following element is the one that loads the page:

Please advice/help. Much appreciated

答:
You can scroll to the bottom of the page, click the Load More button and repeat until you hit your date.  It appears the game dates don't go that far back and your start season date wasn't hit, so I changed it to a year later and it worked.  I, also, used javascript to click the Load More button because there was something else blocking it using webdriver.  Here are the code changes:</p>

```<code>start_season = datetime.strptime('2018-8-11', '%Y-%m-%d').date()

   while last_date > start_season:
      driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
      load_more = matches.find_element_by_xpath('//div[@class="td-load-more-wrap td-load-more-infinite-wrap"]')
      driver.execute_script("arguments[0].click();", load_more)
      matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
      last_date = \
          matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
          -1].find_element_by_class_name('item-details').find_element_by_class_name(
          'td-module-meta-info').find_element_by_class_name('td-post-date').text
      last_date = datetime.strptime(last_date, '%B %d, %Y').date()
</code>```

Body:
I want to scroll down on a page until a certain criteria is met.
The criteria is that the date of the latest visible soccer match is earlier than the reference date.
I wrote the following script:

from selenium import webdriver
from datetime import datetime
from time import sleep

if __name__ == '__main__':
   driver = webdriver.Chrome()
   driver.get('https://hdmatches.com/category/premier-league/')
   matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
   last_date = \
       matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
       -1].find_element_by_class_name('item-details').find_element_by_class_name(
       'td-module-meta-info').find_element_by_class_name('td-post-date').text
   last_date = datetime.strptime(last_date, '%B %d, %Y').date()
   start_season = datetime.strptime('2017-8-11', '%Y-%m-%d').date()

   while last_date > start_season:
      load_more = matches.find_element_by_xpath('//div[@class="td-load-more-wrap td-load-more-infinite-wrap"]')
      driver.execute_script("arguments[0].scrollIntoView();", load_more)
      matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
      last_date = \
          matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
          -1].find_element_by_class_name('item-details').find_element_by_class_name(
          'td-module-meta-info').find_element_by_class_name('td-post-date').text
      last_date = datetime.strptime(last_date, '%B %d, %Y').date()

My script doesn't work sofar (nothing happens) and I think it because of the below element:

While scrolling down, this element is two times visible when the page is loading. Afterwards, the following element is the one that loads the page:

Please advice/help. Much appreciated

Body:
You can scroll to the bottom of the page, click the Load More button and repeat until you hit your date.  It appears the game dates don't go that far back and your start season date wasn't hit, so I changed it to a year later and it worked.  I, also, used javascript to click the Load More button because there was something else blocking it using webdriver.  Here are the code changes:

start_season = datetime.strptime('2018-8-11', '%Y-%m-%d').date()

   while last_date > start_season:
      driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
      load_more = matches.find_element_by_xpath('//div[@class="td-load-more-wrap td-load-more-infinite-wrap"]')
      driver.execute_script("arguments[0].click();", load_more)
      matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
      last_date = \
          matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
          -1].find_element_by_class_name('item-details').find_element_by_class_name(
          'td-module-meta-info').find_element_by_class_name('td-post-date').text
      last_date = datetime.strptime(last_date, '%B %d, %Y').date()


问:
Create new variable using a lookup table
I want to create a new variable using a lookup table. The dataframe looks like this:

```<code>  id    sex     age length
   1    Female  1   45
   2    Female  2   54
   3    Female  3   56
   4    Female  4   60
   5    Female  5   60
   6    Female  6   61
   7    Female  7   63
   8    Male    1   55
   9    Male    2   54
   10   Male    3   58
   11   Male    4   61
   12   Male    5   65
   13   Male    6   63
   14   Male    7   65
   15   Male    8   67
   16   Male    9   68
   17   Male    10  69
</code>```

and the lookup table looks like this

```<code>sex    age  length
Female  1   50
Female  2   53
Female  3   56
Female  4   58
Female  5   60
Female  6   61
Female  7   63
Male    1   50
Male    2   54
Male    3   57
Male    4   60
Male    5   62
Male    6   63
Male    7   65
Male    8   66
Male    9   67
Male    10  69
</code>```

I want to create a new variable growth.rate with two levels: "Normal" and "Low", so the final data frame looks like this ,

```<code>id   sex   age  length  growth.rate
1   Female  1   45  Low
2   Female  2   54  Normal
3   Female  3   56  Low
4   Female  4   60  Normal
5   Female  5   60  Low
6   Female  6   61  Low
7   Female  7   63  Low
8   Male    1   55  Normal
9   Male    2   54  Low
10  Male    3   58  Normal
11  Male    4   61  Normal
12  Male    5   65  Normal
13  Male    6   63  Low
14  Male    7   65  Low
15  Male    8   67  Normal
16  Male    9   68  Normal
17  Male    10  69  Low
</code>```

In this example, the growth.rate for id 1 is "Low" because her length is lower than the value in the lookup table for females age 1.

Conversely, the growth.rate for id 2 is "Normal" because her length is higher than the value in the lookup table for females age 2.

I tried to adapt this solution without success  Getting contextstack overflow error - too many nested ifelse statements within for loop?

any help is much appreciated

答:
In base R, we can use merge to join the two dataframes by sex and age and create a new column by checking the condition with ifelse.

```<code>transform(merge(df, lookup, all.x = TRUE, by = c("sex", "age")),
          growth.rate = ifelse(length.x > length.y, "Normal", "Low"))

#      sex age id length.x length.y growth.rate
#1  Female   1  1       45       50         Low
#2  Female   2  2       54       53      Normal
#3  Female   3  3       56       56         Low
#4  Female   4  4       60       58      Normal
#5  Female   5  5       60       60         Low
#6  Female   6  6       61       61         Low
#7  Female   7  7       63       63         Low
#8    Male   1  8       55       50      Normal
#9    Male  10 17       69       69         Low
#10   Male   2  9       54       54         Low
#11   Male   3 10       58       57      Normal
#12   Male   4 11       61       60      Normal
#13   Male   5 12       65       62      Normal
#14   Male   6 13       63       63         Low
#15   Male   7 14       65       65         Low
#16   Male   8 15       67       66      Normal
#17   Male   9 16       68       67      Normal
</code>```

You can remove the columns which you don't need.

Body:
I want to create a new variable using a lookup table. The dataframe looks like this:

  id    sex     age length
   1    Female  1   45
   2    Female  2   54
   3    Female  3   56
   4    Female  4   60
   5    Female  5   60
   6    Female  6   61
   7    Female  7   63
   8    Male    1   55
   9    Male    2   54
   10   Male    3   58
   11   Male    4   61
   12   Male    5   65
   13   Male    6   63
   14   Male    7   65
   15   Male    8   67
   16   Male    9   68
   17   Male    10  69

and the lookup table looks like this

sex    age  length
Female  1   50
Female  2   53
Female  3   56
Female  4   58
Female  5   60
Female  6   61
Female  7   63
Male    1   50
Male    2   54
Male    3   57
Male    4   60
Male    5   62
Male    6   63
Male    7   65
Male    8   66
Male    9   67
Male    10  69

I want to create a new variable growth.rate with two levels: "Normal" and "Low", so the final data frame looks like this ,

id   sex   age  length  growth.rate
1   Female  1   45  Low
2   Female  2   54  Normal
3   Female  3   56  Low
4   Female  4   60  Normal
5   Female  5   60  Low
6   Female  6   61  Low
7   Female  7   63  Low
8   Male    1   55  Normal
9   Male    2   54  Low
10  Male    3   58  Normal
11  Male    4   61  Normal
12  Male    5   65  Normal
13  Male    6   63  Low
14  Male    7   65  Low
15  Male    8   67  Normal
16  Male    9   68  Normal
17  Male    10  69  Low

In this example, the growth.rate for id 1 is "Low" because her length is lower than the value in the lookup table for females age 1.

Conversely, the growth.rate for id 2 is "Normal" because her length is higher than the value in the lookup table for females age 2.

I tried to adapt this solution without success  Getting contextstack overflow error - too many nested ifelse statements within for loop?

any help is much appreciated

Body:
In base R, we can use merge to join the two dataframes by sex and age and create a new column by checking the condition with ifelse.

transform(merge(df, lookup, all.x = TRUE, by = c("sex", "age")),
          growth.rate = ifelse(length.x > length.y, "Normal", "Low"))

#      sex age id length.x length.y growth.rate
#1  Female   1  1       45       50         Low
#2  Female   2  2       54       53      Normal
#3  Female   3  3       56       56         Low
#4  Female   4  4       60       58      Normal
#5  Female   5  5       60       60         Low
#6  Female   6  6       61       61         Low
#7  Female   7  7       63       63         Low
#8    Male   1  8       55       50      Normal
#9    Male  10 17       69       69         Low
#10   Male   2  9       54       54         Low
#11   Male   3 10       58       57      Normal
#12   Male   4 11       61       60      Normal
#13   Male   5 12       65       62      Normal
#14   Male   6 13       63       63         Low
#15   Male   7 14       65       65         Low
#16   Male   8 15       67       66      Normal
#17   Male   9 16       68       67      Normal

You can remove the columns which you don't need.


问:
How to install iOS simulators from command line
It's a common case to run tests against different versions of iOS simulators/SDKs on CI. However, only the latest iOS simulator is installed by Xcode on default.

So I need install other missing iOS simulators from command line in CI environment. But I cannot find a way to install those simulators from command line.

答:
```<code>xcrun simctl create <name> <device type> <runtime>
</code>```

For example:

```<code>xcrun simctl create "ry" "iPhone 11 Pro Max" iOS13.3
</code>```

xcrun simctl is command utils to control iOS simulator, just like adb for Android. You can also run xcrun simctl help, there are a bundle of useful subcommands. When successful, most of these commands exit with 0; when failed, most exit with a non-zero number.

Personally, I have an article about how to use simulator from terminal.

Body:
xcrun simctl create <name> <device type> <runtime>

For example:

xcrun simctl create "ry" "iPhone 11 Pro Max" iOS13.3

xcrun simctl is command utils to control iOS simulator, just like adb for Android. You can also run xcrun simctl help, there are a bundle of useful subcommands. When successful, most of these commands exit with 0; when failed, most exit with a non-zero number.

Personally, I have an article about how to use simulator from terminal.


问:
How to find first element in a column by group, that fulfills a condition? If the condition is fulfilled start the counter from 0 in R
I have a large dataset similar to this. I have been trying to add a counter from zero based on a condition of the first element in a column by group.
I want to get liked this:

```<code>ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2
</code>```

I tried this code:

```<code>ov28<- ov27 %>% group_by(ID, idx = cumsum(STOf == 1L)) %>%
       mutate(counter = row_number()) %>%
       ungroup %>%
       select(-idx)
</code>```

The issue is: counter starts from 1 and the counter needs to start only based on condition as opposed to starting from the new id as well as condition. In short, I want the counter to start only if condition is satisfied, that too from 0.

Thanks!

Body:
I have a large dataset similar to this. I have been trying to add a counter from zero based on a condition of the first element in a column by group.
I want to get liked this:

ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2

I tried this code:

ov28<- ov27 %>% group_by(ID, idx = cumsum(STOf == 1L)) %>%
       mutate(counter = row_number()) %>%
       ungroup %>%
       select(-idx)

The issue is: counter starts from 1 and the counter needs to start only based on condition as opposed to starting from the new id as well as condition. In short, I want the counter to start only if condition is satisfied, that too from 0.

Thanks!

Body:
Another data.table option:

DT[, cnt := DT[, pmax(seq(.N) - match(1L, STOf), 0L), ID]$V1]

data:

library(data.table)
DT <- fread("ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2")


问:
Access EC2 instance from internet?
I have an EC2 instance running Apex Oracle.

On the virtual machine I can access Apex by typing : localhost:8080/apex

I'm trying to access the same URL but from internet.

I use : ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com:8080/apex but it's not working.

In my security attributes I have the following inbound rule :

Customized TCP Rule

Protocol : TCP

Ports : 8080

Source : MyIP address

My virtual machine's firewall doesn't block any connexion on this port.

What am I doing wrong ?

Thanks.
Cheers,

答: It could be the NACLs as well. Most often when you create a VPC you end up with some subnets that are not accessible via the internet. If your instance is in one of those subnets the security groups won't matter.</p>

Title: Access EC2 instance from internet?


问:
In C++ what is the point of std::array if the size has to be determined at compile time?
Pardon my ignorance, it appears to me that std::array is meant to be an STL replacement for your regular arrays. But because the array size has to be passed as a template parameter, it prevents us from creating std::array with a size known only at runtime.

```<code>std::array<char,3> nums {1,2,3}; // Works.

constexpr size_t size = 3;
std::array<char,size> nums {1,2,3}; // Works.

const buf_size = GetSize();
std::array<char, buf_size> nums; // Doesn't work.
</code>```

I would assume that one very important use case for an array in C++ is to create a fixed size data structure based on runtime inputs (say allocating buffer for reading files).

The workarounds I use for this are:

```<code>// Create a array pointer for on-the-spot usecases like reading from a file.
char *data = new char[size];
...
delete[] data;
</code>```

or:

```<code>// Use unique_ptr as a class member and I don't want to manage the memory myself.
std::unique_ptr<char[]> myarr_ = std::unique_ptr<char[]>(new char[size]);
</code>```

If I don't care about fixed size, I am aware that I can use std::vector<char> with the size pre-defined as follows:

```<code>std::vector<char> my_buf (buf_size);
</code>```

Why did the designers of std::array choose to ignore this use case? Perhaps I don't understand the real usecase for std::array.

EDIT: I guess another way to phrase my question could also be - Why did the designers choose to have the size passed as a template param and not as a constructor param? Would opting for the latter have made it difficult to provide the functionality that std::array currently has? To me it seems like a deliberate design choice and I don't understand why.

答:
std::array is a replacement for C-style arrays.

The C++ standards don't allow C-style arrays to be declared without compile-time defined sizes.

Body:
Pardon my ignorance, it appears to me that std::array is meant to be an STL replacement for your regular arrays. But because the array size has to be passed as a template parameter, it prevents us from creating std::array with a size known only at runtime.

std::array<char,3> nums {1,2,3}; // Works.

constexpr size_t size = 3;
std::array<char,size> nums {1,2,3}; // Works.

const buf_size = GetSize();
std::array<char, buf_size> nums; // Doesn't work.

I would assume that one very important use case for an array in C++ is to create a fixed size data structure based on runtime inputs (say allocating buffer for reading files).

The workarounds I use for this are:

// Create a array pointer for on-the-spot usecases like reading from a file.
char *data = new char[size];
...
delete[] data;

or:

// Use unique_ptr as a class member and I don't want to manage the memory myself.
std::unique_ptr<char[]> myarr_ = std::unique_ptr<char[]>(new char[size]);

If I don't care about fixed size, I am aware that I can use std::vector<char> with the size pre-defined as follows:

std::vector<char> my_buf (buf_size);

Why did the designers of std::array choose to ignore this use case? Perhaps I don't understand the real usecase for std::array.

EDIT: I guess another way to phrase my question could also be - Why did the designers choose to have the size passed as a template param and not as a constructor param? Would opting for the latter have made it difficult to provide the functionality that std::array currently has? To me it seems like a deliberate design choice and I don't understand why.


问:
Javascript ES6 array loop that populates code only when on certain pages
i'm in school currently learning how to program using javascript (forgive me if my terminology is bad. feel free to correct me.) Myself and a team of four are creating a site. the requirements are that we must have 4 pages and each page needs to have a loop of some kind, we must use bootstrap, and we can only use one js file for all the pages. We are using a printToDom function to populate bootstrap cards on separate pages, and for some reason i can't get mine to work. i'm wondering if this has something to do with how our code is set up, specifically the for loops we're using. is there a way that i can incorporate an if statement that makes it to where our printToDom will print certain pieces of the for loop when on different pages? If so is there a term for it or something i can look up to get more insight?

EDIT: I probably should have said this in my original post, but I'm considering merging the two for loops that are seen in my code below because currently i have 2 separate for loops, but only one gets populated when on the tours page, the other one is supposed to populate some recent events from the array recentEvents but it doesn't. I tested it in JS fiddle and the code works there so i'm just wondering why it won't work when in the js file along side the rest of the code and I'm not sure how to phrase what i'm looking for.

javascript below for more context

```<code>    const tourStops=[
    {           location: "Denver, Colorado ",
                venue: " Pepsi Center ",
                date: "MON 04/20/2020",
                id: 1
    },
    {
                location: "Las Vegas, Nevada",
                venue: " Flamingo Hotel",
                date: "FRI 04/24/2020",
                id: 2
    },
    {
                location: "Hollywood, California",
                venue: " Troubadour ",
                date: "SAT  05/02/2020",
                id: 3
    },
    {
                location: "Portland,Oregon",
                venue: " Moda Center ",
                date: "FRI  05/15/2020",
                id: 4
    },
    {
                location: "Washington, D.C. ",
                venue: " Capital One Arena",
                date: "FRI  05/22/2020",
                id: 5
    },
    {
                location: "Bangor, Maine ",
                venue: " Darlings Waterfront",
                date: "FRI  06/05/2020",
                id: 6
    },
    {
                location: "Boston, Massachusetts",
                venue: " Wilbur Theater ",
                date: "SAT  06/20/2020",
                id: 7
    },
    {
                location: "Anchorage, Alaska ",
                venue: "Atwood Concert Hall",
                date: "THU  07/09/2020",
                id: 8
    }
    ];

    const printToDom =(divId,textToPrint)=>{
    const selectedDiv= document.getElementById(divId);
    selectedDiv.innerHTML= textToPrint;
    };

    const buildTourDates=()=>{
        let domString='';
        for(let i = 0; i <tourStops.length;i++){
            domString += '<div class="container px-lg-5">';
            domString += '<div class="row mx-lg-n5">';
            domString += `<div class="col py-3 px-lg-5 border">${tourStops[i].date}</div>`;
            domString += `<div class="col py-3 px-lg-5 border">${tourStops[i].location}</div>`;
            domString += `<div class="col py-3 px-lg-5 border">${tourStops[i].venue}</div>`;
            domString += `<a class="btn btn-success border" href="https://www.ticketnetwork.com/en/concerts" role="button" id= "tickets" onclick= "btnPurchase(${tourStops[i].id})" class="btn btn-success border">Purchase Tickets</a>`;
            domString += '</div>';
            domString += '</div>';
    }
    printToDom('tourdates',domString)
    };

    const btnPurchase= (id)=>{
     for(let i=0; i < tourStops.length; i++){
         if(tourStops[i].id === id) {
    return;
}
  }
    };

    const eventsForTickets = () => {
        document.getElementById("tickets").addEventListener('click', btnPurchase);
    };

    const recentEvents = [
        {
            event: "New Tour!",
            para: "text to be inserted into this event. Lorum ipsum to see how more text looks.",
            img: ""
        },
        {
            event: "New Album",
            para: "text to be inserted into this event. Lorum ipsum to see how more text looks.",
            img: ""
        },
        {
            event: "Something",
            para: "text to be inserted into this event. Lorum ipsum to see how more text looks.",
            img: ""
        },

    ];

    const buildEvents = () => {
        let domString='';
        for(let i = 0; i < recentEvents.length; i++){
            domString += `<div class="media">`;
            domString += `<img src="..." class="mr-3" alt="...">`;
            domString += `<div class="media-body">`;
            domString += ` <h5 class="mt-0">${recentEvents[i].event}</h5>`;
            domString += `${recentEvents[i].para}`;
            domString += `</div>`;
            domString += `</div>`;
        }
    printToDom('newEvents',domString)
    };

    const initTour=()=> {
     buildTourDates(tourStops);
     eventsForTickets();
    };

    const initIndex=()=>{
        buildEvents(recentEvents);
    }

    initTour();
    initIndex();
</code>```

答:
You can use the method window.location.pathname that get the name of the specific page in which you are, according to it then you can do something like that

```<code>const pageRoute = window.location.pathname

if(pageRoute == "page-one"){
    buildTourDates()
} else if(pageRoute == "page-two"){
    buildEvents()
}//so on...
</code>```

Body:
i'm in school currently learning how to program using javascript (forgive me if my terminology is bad. feel free to correct me.) Myself and a team of four are creating a site. the requirements are that we must have 4 pages and each page needs to have a loop of some kind, we must use bootstrap, and we can only use one js file for all the pages. We are using a printToDom function to populate bootstrap cards on separate pages, and for some reason i can't get mine to work. i'm wondering if this has something to do with how our code is set up, specifically the for loops we're using. is there a way that i can incorporate an if statement that makes it to where our printToDom will print certain pieces of the for loop when on different pages? If so is there a term for it or something i can look up to get more insight?

EDIT: I probably should have said this in my original post, but I'm considering merging the two for loops that are seen in my code below because currently i have 2 separate for loops, but only one gets populated when on the tours page, the other one is supposed to populate some recent events from the array recentEvents but it doesn't. I tested it in JS fiddle and the code works there so i'm just wondering why it won't work when in the js file along side the rest of the code and I'm not sure how to phrase what i'm looking for.

javascript below for more context

    const tourStops=[
    {           location: "Denver, Colorado ",
                venue: " Pepsi Center ",
                date: "MON 04/20/2020",
                id: 1
    },
    {
                location: "Las Vegas, Nevada",
                venue: " Flamingo Hotel",
                date: "FRI 04/24/2020",
                id: 2
    },
    {
                location: "Hollywood, California",
                venue: " Troubadour ",
                date: "SAT  05/02/2020",
                id: 3
    },
    {
                location: "Portland,Oregon",
                venue: " Moda Center ",
                date: "FRI  05/15/2020",
                id: 4
    },
    {
                location: "Washington, D.C. ",
                venue: " Capital One Arena",
                date: "FRI  05/22/2020",
                id: 5
    },
    {
                location: "Bangor, Maine ",
                venue: " Darlings Waterfront",
                date: "FRI  06/05/2020",
                id: 6
    },
    {
                location: "Boston, Massachusetts",
                venue: " Wilbur Theater ",
                date: "SAT  06/20/2020",
                id: 7
    },
    {
                location: "Anchorage, Alaska ",
                venue: "Atwood Concert Hall",
                date: "THU  07/09/2020",
                id: 8
    }
    ];

    const printToDom =(divId,textToPrint)=>{
    const selectedDiv= document.getElementById(divId);
    selectedDiv.innerHTML= textToPrint;
    };

    const buildTourDates=()=>{
        let domString='';
        for(let i = 0; i <tourStops.length;i++){
            domString += '
';
            domString += '
';
            domString += `<div class="col py-3 px-lg-5 border">${tourStops[i].date}</div>`;
            domString += `<div class="col py-3 px-lg-5 border">${tourStops[i].location}</div>`;
            domString += `<div class="col py-3 px-lg-5 border">${tourStops[i].venue}</div>`;
            domString += `Purchase Tickets`;
            domString += '
';
            domString += '
';
    }
    printToDom('tourdates',domString)
    };

    const btnPurchase= (id)=>{
     for(let i=0; i < tourStops.length; i++){
         if(tourStops[i].id === id) {
    return;
}
  }
    };

    const eventsForTickets = () => {
        document.getElementById("tickets").addEventListener('click', btnPurchase);
    };

    const recentEvents = [
        {
            event: "New Tour!",
            para: "text to be inserted into this event. Lorum ipsum to see how more text looks.",
            img: ""
        },
        {
            event: "New Album",
            para: "text to be inserted into this event. Lorum ipsum to see how more text looks.",
            img: ""
        },
        {
            event: "Something",
            para: "text to be inserted into this event. Lorum ipsum to see how more text looks.",
            img: ""
        },

    ];

    const buildEvents = () => {
        let domString='';
        for(let i = 0; i < recentEvents.length; i++){
            domString += `<div class="media">`;
            domString += `<img src="..." class="mr-3" alt="...">`;
            domString += `<div class="media-body">`;
            domString += ` <h5 class="mt-0">${recentEvents[i].event}</h5>`;
            domString += `${recentEvents[i].para}`;
            domString += `</div>`;
            domString += `</div>`;
        }
    printToDom('newEvents',domString)
    };

    const initTour=()=> {
     buildTourDates(tourStops);
     eventsForTickets();
    };

    const initIndex=()=>{
        buildEvents(recentEvents);
    }

    initTour();
    initIndex();

Body:
You can use the method window.location.pathname that get the name of the specific page in which you are, according to it then you can do something like that

const pageRoute = window.location.pathname

if(pageRoute == "page-one"){
    buildTourDates()
} else if(pageRoute == "page-two"){
    buildEvents()
}//so on...


问:
c# linq: how to submit object to database as a new record
I have the following object:

```<code>namespace LearnLINQ1
{
    [Table(Name="testMe")]
    public class SubmitTest
    {
        [Column(Name="FirstName")]
        public string FirstName { get; set; }

        [Column(Name = "LastName")]
        public string LastName { get; set; }

        [Column(Name = "PhoneNumber")]
        public int PhoneNumber { get; set; }

        linqLayerDataContext db;
    }
}
</code>```

And i've used the same thing with a constructor:

```<code>namespace LearnLINQ1
{
    [Table(Name="testMe")]
    public class SubmitTest
    {
        [Column(Name="FirstName")]
        public string FirstName { get; set; }

        [Column(Name = "LastName")]
        public string LastName { get; set; }

        [Column(Name = "PhoneNumber")]
        public int PhoneNumber { get; set; }

        linqLayerDataContext db;

        //constructor
        public SubmitTest(string first, string last, int phone, linqLayerDataContext db)
        {
            this.FirstName = first;
            this.LastName = last;
            this.PhoneNumber = phone;
            this.db = db;
        }

    }
}
</code>```

I'm using the following code to instantiate the object and attempt to add it to the database as a new record:

```<code>SubmitTest test = new SubmitTest { FirstName = "Jeremy", LastName = "Stafford", PhoneNumber = 23 };
db.testMes.InsertOnSubmit(test);
</code>```

But im getting the error:

Error 1   The best overloaded method
  match for
  'System.Data.Linq.Table.InsertOnSubmit(LearnLINQ1.testMe)'
  has some invalid
  arguments C:\Users\Jeremy\Documents\Visual
  Studio
  2010\Projects\LearnLINQ1\LearnLINQ1\Form1.cs  42  13  LearnLINQ1

Error 2   Argument 1: cannot convert
  from 'LearnLINQ1.SubmitTest' to
  'LearnLINQ1.testMe'   C:\Users\Jeremy\Documents\Visual
  Studio
  2010\Projects\LearnLINQ1\LearnLINQ1\Form1.cs  42  39  LearnLINQ1

I'm not sure if there was something im missing in the class definition... kinda new to the concept. Can someone point me in the right direction?

================================
UPDATE: Ok so i made some changes

the customer class:

```<code>namespace LearnLINQ1
{

    public class Customer
    {
        [Table(Name = "testMe")]
        public class SubmitTest
        {
            [Column(Name = "FirstName")]
            public string FirstName { get; set; }

            [Column(Name = "LastName")]
            public string LastName { get; set; }

            [Column(Name = "PhoneNumber")]
            public int PhoneNumber { get; set; }
        }
    }
}
</code>```

And the test code:

```<code>namespace LearnLINQ1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            linqTestDataContext db = new linqTestDataContext();

            Table<Customer> Customers = db.GetTable<Customer>();
            var cus = new Customer { FirstName = "Jeremy", Lastname = "Stafford", Age = 31 };
            db.Customers.InsertOnSubmit(cus);

            db.SubmitChanges();
        }
    }
}
</code>```

Now the problem is with the customer class. it is giving the following error:

Error 1   Missing partial modifier on
  declaration of type
  'LearnLINQ1.Customer'; another partial
  declaration of this type
  exists    C:\Users\Jeremy\Documents\Visual
  Studio
  2010\Projects\LearnLINQ1\LearnLINQ1\Customer.cs   11  18  LearnLINQ1

答: LearnLINQ1.testMe is the object you need to create not LearnLINQ1.SubmitTest</p>

Body:
I have the following object:

namespace LearnLINQ1
{
    [Table(Name="testMe")]
    public class SubmitTest
    {
        [Column(Name="FirstName")]
        public string FirstName { get; set; }

        [Column(Name = "LastName")]
        public string LastName { get; set; }

        [Column(Name = "PhoneNumber")]
        public int PhoneNumber { get; set; }

        linqLayerDataContext db;
    }
}

And i've used the same thing with a constructor:

namespace LearnLINQ1
{
    [Table(Name="testMe")]
    public class SubmitTest
    {
        [Column(Name="FirstName")]
        public string FirstName { get; set; }

        [Column(Name = "LastName")]
        public string LastName { get; set; }

        [Column(Name = "PhoneNumber")]
        public int PhoneNumber { get; set; }

        linqLayerDataContext db;

        //constructor
        public SubmitTest(string first, string last, int phone, linqLayerDataContext db)
        {
            this.FirstName = first;
            this.LastName = last;
            this.PhoneNumber = phone;
            this.db = db;
        }

    }
}

I'm using the following code to instantiate the object and attempt to add it to the database as a new record:

SubmitTest test = new SubmitTest { FirstName = "Jeremy", LastName = "Stafford", PhoneNumber = 23 };
db.testMes.InsertOnSubmit(test);

But im getting the error:

Error 1   The best overloaded method
  match for
  'System.Data.Linq.Table.InsertOnSubmit(LearnLINQ1.testMe)'
  has some invalid
  arguments C:\Users\Jeremy\Documents\Visual
  Studio
  2010\Projects\LearnLINQ1\LearnLINQ1\Form1.cs  42  13  LearnLINQ1

Error 2   Argument 1: cannot convert
  from 'LearnLINQ1.SubmitTest' to
  'LearnLINQ1.testMe'   C:\Users\Jeremy\Documents\Visual
  Studio
  2010\Projects\LearnLINQ1\LearnLINQ1\Form1.cs  42  39  LearnLINQ1

I'm not sure if there was something im missing in the class definition... kinda new to the concept. Can someone point me in the right direction?

================================
UPDATE: Ok so i made some changes

the customer class:

namespace LearnLINQ1
{

    public class Customer
    {
        [Table(Name = "testMe")]
        public class SubmitTest
        {
            [Column(Name = "FirstName")]
            public string FirstName { get; set; }

            [Column(Name = "LastName")]
            public string LastName { get; set; }

            [Column(Name = "PhoneNumber")]
            public int PhoneNumber { get; set; }
        }
    }
}

And the test code:

namespace LearnLINQ1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            linqTestDataContext db = new linqTestDataContext();

            Table<Customer> Customers = db.GetTable<Customer>();
            var cus = new Customer { FirstName = "Jeremy", Lastname = "Stafford", Age = 31 };
            db.Customers.InsertOnSubmit(cus);

            db.SubmitChanges();
        }
    }
}

Now the problem is with the customer class. it is giving the following error:

Error 1   Missing partial modifier on
  declaration of type
  'LearnLINQ1.Customer'; another partial
  declaration of this type
  exists    C:\Users\Jeremy\Documents\Visual
  Studio
  2010\Projects\LearnLINQ1\LearnLINQ1\Customer.cs   11  18  LearnLINQ1


问:
PythonKit error "Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library"
I'm using PythonKit with XCode to call spaCy API from swift code. Installed PythonKit from Home-brew, imported it in my project and it built well; however, at runtime I got the error:

```<code>Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library.
</code>```

So I compiled PythonTools (within PythonKit dir, run swift package generate-xcodeproj and open PythonKit.xcodeproj file ) to see which paths of Python library it would find:

```<code>/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip
/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7
/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload
/Users/fernandabrum/Library/Python/3.7/lib/python/site-packages
/usr/local/lib/python3.7/site-packages
</code>```

If Python libraries are in my system, why I get an error of Python library not found? What am I doing wrong?

OBS.:I also tried to set PYTHON_LIBRARY with export PYTHON_LIBRARY= and the paths found above, but unsuccessful.

Thanks in advance!

答:
In "Hardened Runtime" under Signing and Capabilities: check "Disable Library Validation"
See the answer here: I can't import Python modules in Xcode 11 using PythonKit</p>

Body:
I'm using PythonKit with XCode to call spaCy API from swift code. Installed PythonKit from Home-brew, imported it in my project and it built well; however, at runtime I got the error:

Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library.

So I compiled PythonTools (within PythonKit dir, run swift package generate-xcodeproj and open PythonKit.xcodeproj file ) to see which paths of Python library it would find:

/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip
/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7
/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload
/Users/fernandabrum/Library/Python/3.7/lib/python/site-packages
/usr/local/lib/python3.7/site-packages

If Python libraries are in my system, why I get an error of Python library not found? What am I doing wrong?

OBS.:I also tried to set PYTHON_LIBRARY with export PYTHON_LIBRARY= and the paths found above, but unsuccessful.

Thanks in advance!


问:
UWP - How to get ListViewItem value with right click or right tapped wihout select none Listviewitem?
hello I have a list of data (sqlite) loaded to a listview and everything works marravilla if I select a listviewItem and right click on it, but I want to get the current listviewitem (under the pointer) without selecting any listviewitem

what I want is similar to the application of "Microsoft to DO"

and I have the following sample code:

MainPage.xaml

```<code><Grid>
    <ListView x:Name="myList">
        <ListViewItem>Item 1</ListViewItem>
        <ListViewItem>Item 2</ListViewItem>
        <ListViewItem>Item 3</ListViewItem>
        <ListViewItem>Item 4</ListViewItem>
        <ListViewItem>Item 5</ListViewItem>

        <ListView.ContextFlyout>
            <MenuFlyout x:Name="itemActual">
                <MenuFlyoutItem Text="see" Click="MenuFlyoutItem_Click"/>
            </MenuFlyout>
        </ListView.ContextFlyout>
    </ListView>

</Grid>
</code>```

MainPage.xaml.cs:

```<code> private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
    {
        ContentDialog dialog = new ContentDialog()
        {
            //Content = myList.item ????

            PrimaryButtonText = "ok"
        };
        dialog.ShowAsync();

    }
</code>```

Thanks in advance

答:
My original answer wasn't correct so I decided to edit it.

First, create a field called _selectedValue with the type of your ListView's ItemsSource items' type, I'll call it "MyClass":

```<code>private MyClass _selectedItem;
</code>```

Then, register the RightTapped event of your ListView:

```<code><ListView x:Name="myList" RightTapped="myList_RightTapped">
</code>```

From there, get the DataContext from the RightTappedRoutedEventArgs:

```<code>private void myList_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e) {
    _selectedItem = (e.OriginalSource as FrameworkElement).DataContext as MyClass;
}
</code>```

When your flyout's Click event is fired, use _selectedValue:

```<code>private void MenuFlyoutItem_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
    // Do stuff with _selectedValue
}
</code>```

Full example files:

MainPage.cs:

```<code> public sealed partial class MainPage : Page {
    #region Fields
    private List<MyClass> _items;
    private MyClass _selectedItem;
    #endregion

    public MainPage() {
        this.InitializeComponent();

        _items = new List<MyClass>();
        _items.Add(new MyClass() { Name = "O" });
        _items.Add(new MyClass() { Name = "P" });
        myList.ItemsSource = _items;
    }

    private void MenuFlyoutItem_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
        // Do stuff with _selectedValue
    }

    private void myList_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e) {
        _selectedItem = (e.OriginalSource as FrameworkElement).DataContext as MyClass;
    }

    public class MyClass {

        public string Name { get; set; }

        public override string ToString() => Name;

    }
}
</code>```

MainPage.xaml:

```<code><Page
    x:Class="UWP.Sandbox.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UWP.Sandbox"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <ListView x:Name="myList" RightTapped="myList_RightTapped">
            <ListView.ContextFlyout>
                <MenuFlyout x:Name="itemActual">
                    <MenuFlyoutItem Text="see" Click="MenuFlyoutItem_Click"/>
                </MenuFlyout>
            </ListView.ContextFlyout>
        </ListView>
    </Grid>
</Page>
</code>```

Body:
hello I have a list of data (sqlite) loaded to a listview and everything works marravilla if I select a listviewItem and right click on it, but I want to get the current listviewitem (under the pointer) without selecting any listviewitem

what I want is similar to the application of "Microsoft to DO"

and I have the following sample code:

MainPage.xaml

<Grid>
    <ListView x:Name="myList">
        <ListViewItem>Item 1</ListViewItem>
        <ListViewItem>Item 2</ListViewItem>
        <ListViewItem>Item 3</ListViewItem>
        <ListViewItem>Item 4</ListViewItem>
        <ListViewItem>Item 5</ListViewItem>

        <ListView.ContextFlyout>
            <MenuFlyout x:Name="itemActual">
                <MenuFlyoutItem Text="see" Click="MenuFlyoutItem_Click"/>
            </MenuFlyout>
        </ListView.ContextFlyout>
    </ListView>

</Grid>

MainPage.xaml.cs:

 private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
    {
        ContentDialog dialog = new ContentDialog()
        {
            //Content = myList.item ????

            PrimaryButtonText = "ok"
        };
        dialog.ShowAsync();

    }

Thanks in advance

Body:
My original answer wasn't correct so I decided to edit it.

First, create a field called _selectedValue with the type of your ListView's ItemsSource items' type, I'll call it "MyClass":

private MyClass _selectedItem;

Then, register the RightTapped event of your ListView:

<ListView x:Name="myList" RightTapped="myList_RightTapped">

From there, get the DataContext from the RightTappedRoutedEventArgs:

private void myList_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e) {
    _selectedItem = (e.OriginalSource as FrameworkElement).DataContext as MyClass;
}

When your flyout's Click event is fired, use _selectedValue:

private void MenuFlyoutItem_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
    // Do stuff with _selectedValue
}

Full example files:

MainPage.cs:

 public sealed partial class MainPage : Page {
    #region Fields
    private List<MyClass> _items;
    private MyClass _selectedItem;
    #endregion

    public MainPage() {
        this.InitializeComponent();

        _items = new List<MyClass>();
        _items.Add(new MyClass() { Name = "O" });
        _items.Add(new MyClass() { Name = "P" });
        myList.ItemsSource = _items;
    }

    private void MenuFlyoutItem_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
        // Do stuff with _selectedValue
    }

    private void myList_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e) {
        _selectedItem = (e.OriginalSource as FrameworkElement).DataContext as MyClass;
    }

    public class MyClass {

        public string Name { get; set; }

        public override string ToString() => Name;

    }
}

MainPage.xaml:

<Page
    x:Class="UWP.Sandbox.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UWP.Sandbox"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <ListView x:Name="myList" RightTapped="myList_RightTapped">
            <ListView.ContextFlyout>
                <MenuFlyout x:Name="itemActual">
                    <MenuFlyoutItem Text="see" Click="MenuFlyoutItem_Click"/>
                </MenuFlyout>
            </ListView.ContextFlyout>
        </ListView>
    </Grid>
</Page>


答:
Ease of programming

std::array facilitates several beneficial interfaces and idioms which are used in std::vector. With normal C-style arrays, one cannot have .size() (no sizeof hack), .at() (exception for out of range), front()/back(), iterators, so on. Everything has to be hand-coded.

Many programmers may choose std::vector even for compile time known sized arrays, just because they want to utilize above programming methodologies. But that snatches away the performance available with compile time fixed size arrays.

Hence std::array was provided by the library makers to discourage the C-style arrays, and yet avoid std::vectors when the size is known at the compile time.

Title: In C++ what is the point of std::array if the size has to be determined at compile time?