问:
How to turn a dict value that's a list into a tuple to then invert the dict
My assignment requires to create a dictionary with a list of values for each key. Then, it provides an invert function and asks to modify the function so that every item in the list is a new key. My understanding is this.
a={'a':['2','3','4'], 'b':['1','5','6']}
b={'2':'a', '3':'a','4':'a','1':'b','5':'b','6':'b'}

I created a test dictionary with tuples instead of lists and I was able to invert them but I don't know how to turn the lists in the dictionary into tuples and then into individual items that would correspond to the same value.
I watched youtube tutorials and tried googling it (including stack overflow) but cannot get how to complete it.
At this point, I don't even know anything - I would definitely appreciate any explanation as I feel completely confused.

```<code>
def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

#my initial dictionary
work_contacts={'Lauren' : '617-111-2222', 'Sana' : '781-234-1212', 'Kelly': '845-234-1515', 'Jose' : '946-999-3210', 'Sabrina' : '617-222-5656', 'Shirika' : '410-231-9090', 'Rachel': '823-432-2121'}

c=invert_dict(work_contacts)
c
{'617-111-2222': ['Lauren'], '781-234-1212': ['Sana'], '845-234-1515': ['Kelly'], '946-999-3210': ['Jose'], '617-222-5656': ['Sabrina'], '410-231-9090': ['Shirika'], '823-432-2121': ['Rachel']}
c['617-111-2222'] #calling the first key
['Lauren']

#the dictionary for the assignment
work_contacts={'Lauren' : ['617-111-2222', 'lauren@company.org'], 'Sana' : ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose' : ['946-999-3210', 'jose@company.org'], 'Sabrina' : ['617-222-5656', 'sabrina@company.org'], 'Shirika' : ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#the error comes back like this
invert_dict(work_contacts)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    invert_dict(work_contacts)
  File "<pyshell#2>", line 5, in invert_dict
    if val not in inverse:
TypeError: unhashable type: 'list'

#I tried to turn the lists into tuples
def l_t(s):
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return s

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

def l_t(s):
    p=s
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

`def l_t(s):
    p=s
    final = []
    for k, v in p.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#I then tried to tuple the values
tuple(work_contacts.values())
(['617-111-2222', 'lauren@company.org'], ['781-234-1212', 'sana@company.org'], ['845-234-1515', 'kelly@company.org'], ['946-999-3210', 'jose@company.org'], ['617-222-5656', 'sabrina@company.org'], ['410-231-9090', 'shirika@comoany.org'], ['823-432-2121', 'rachel@company.org'])

#I have generated much more code with error messages, as below
b=invert_dict(test)
b
{(2, 'al', 3): ['a'], ('we', 'as', 4): ['blue']}

b[2]
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    b[2]
KeyError: 2
b(2)
Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    b(2)
TypeError: 'dict' object is not callable
b(2, 'al', 3)
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
    b(2, 'al', 3)
TypeError: 'dict' object is not callable
b[1]
Traceback (most recent call last):
  File "<pyshell#148>", line 1, in <module>
    b[1]
KeyError: 1```
```

答:
I believe you're asking how to modify invert_dict into a function that will work on your second work_contacts dictionary, the one with lists as its values. If not, ignore this answer!

Let's look at the function:

```<code>def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse
</code>```

If d has lists as its values, then val will be a list. This line:

```<code>if val not in inverse:
</code>```

is where your function is throwing an error. Lists can't be used as keys in dictionaries; in the jargon of Python, list is an unhashable type. That's what the error is complaining about.

If you want the keys in the inverted dictionary to be the elements of the list, not the list itself, you just have to loop over the list and do the same thing with its elements that you were doing with the original val. Try something involving:

```<code>val_list = d[key]
for val_element in val_list:
     if val_element not in inverse:
          # you do the rest!
</code>```

Body:
My assignment requires to create a dictionary with a list of values for each key. Then, it provides an invert function and asks to modify the function so that every item in the list is a new key. My understanding is this.
a={'a':['2','3','4'], 'b':['1','5','6']}
b={'2':'a', '3':'a','4':'a','1':'b','5':'b','6':'b'}

I created a test dictionary with tuples instead of lists and I was able to invert them but I don't know how to turn the lists in the dictionary into tuples and then into individual items that would correspond to the same value.
I watched youtube tutorials and tried googling it (including stack overflow) but cannot get how to complete it.
At this point, I don't even know anything - I would definitely appreciate any explanation as I feel completely confused.

def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

#my initial dictionary
work_contacts={'Lauren' : '617-111-2222', 'Sana' : '781-234-1212', 'Kelly': '845-234-1515', 'Jose' : '946-999-3210', 'Sabrina' : '617-222-5656', 'Shirika' : '410-231-9090', 'Rachel': '823-432-2121'}

c=invert_dict(work_contacts)
c
{'617-111-2222': ['Lauren'], '781-234-1212': ['Sana'], '845-234-1515': ['Kelly'], '946-999-3210': ['Jose'], '617-222-5656': ['Sabrina'], '410-231-9090': ['Shirika'], '823-432-2121': ['Rachel']}
c['617-111-2222'] #calling the first key
['Lauren']

#the dictionary for the assignment
work_contacts={'Lauren' : ['617-111-2222', 'lauren@company.org'], 'Sana' : ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose' : ['946-999-3210', 'jose@company.org'], 'Sabrina' : ['617-222-5656', 'sabrina@company.org'], 'Shirika' : ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#the error comes back like this
invert_dict(work_contacts)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    invert_dict(work_contacts)
  File "<pyshell#2>", line 5, in invert_dict
    if val not in inverse:
TypeError: unhashable type: 'list'

#I tried to turn the lists into tuples
def l_t(s):
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return s

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

def l_t(s):
    p=s
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

`def l_t(s):
    p=s
    final = []
    for k, v in p.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#I then tried to tuple the values
tuple(work_contacts.values())
(['617-111-2222', 'lauren@company.org'], ['781-234-1212', 'sana@company.org'], ['845-234-1515', 'kelly@company.org'], ['946-999-3210', 'jose@company.org'], ['617-222-5656', 'sabrina@company.org'], ['410-231-9090', 'shirika@comoany.org'], ['823-432-2121', 'rachel@company.org'])

#I have generated much more code with error messages, as below
b=invert_dict(test)
b
{(2, 'al', 3): ['a'], ('we', 'as', 4): ['blue']}

b[2]
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    b[2]
KeyError: 2
b(2)
Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    b(2)
TypeError: 'dict' object is not callable
b(2, 'al', 3)
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
    b(2, 'al', 3)
TypeError: 'dict' object is not callable
b[1]
Traceback (most recent call last):
  File "<pyshell#148>", line 1, in <module>
    b[1]
KeyError: 1```

Body:
I believe you're asking how to modify invert_dict into a function that will work on your second work_contacts dictionary, the one with lists as its values. If not, ignore this answer!

Let's look at the function:

def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

If d has lists as its values, then val will be a list. This line:

if val not in inverse:

is where your function is throwing an error. Lists can't be used as keys in dictionaries; in the jargon of Python, list is an unhashable type. That's what the error is complaining about.

If you want the keys in the inverted dictionary to be the elements of the list, not the list itself, you just have to loop over the list and do the same thing with its elements that you were doing with the original val. Try something involving:

val_list = d[key]
for val_element in val_list:
     if val_element not in inverse:
          # you do the rest!


来源: stackexchange

问:
access to nested data
I need to access structured data in a nested way but I didn't understand how to do it.

The data is structured in this way:

```<code>{'function':'data_chip',
 'group_id': 172,
 'Types': [
    {'TMS0202':'SR-20',
     'TMS0207':'SR-22',
     'TMS0201': 'TI-4000',
     'TMS0203': 'TI-450'
    }
 ]
}
</code>```

答:
To access the top-level data, use a single dictionary index:

```<code>data['function'] —> 'data chip'
</code>```

To access the data in the Types key, you need to access the list first then the dictionary inside it:

```<code>data['Types'][0]['TMS0202'] —> 'SR-20'
</code>```

Each time you get a level deeper, consider what data type you now need to access. If it is a dict you need the keys, if it is a list you need the integer index. Each level you access is another retrieval using square brackets:

```<code>data[key][index][key]
</code>```

ContentLicense: CC BY-SA 4.0

Title: access to nested data

Body:
I need to access structured data in a nested way but I didn't understand how to do it.

The data is structured in this way:

{'function':'data_chip',
 'group_id': 172,
 'Types': [
    {'TMS0202':'SR-20',
     'TMS0207':'SR-22',
     'TMS0201': 'TI-4000',
     'TMS0203': 'TI-450'
    }
 ]
}

Body:
To access the top-level data, use a single dictionary index:

data['function'] —> 'data chip'

To access the data in the Types key, you need to access the list first then the dictionary inside it:

data['Types'][0]['TMS0202'] —> 'SR-20'

Each time you get a level deeper, consider what data type you now need to access. If it is a dict you need the keys, if it is a list you need the integer index. Each level you access is another retrieval using square brackets:

data[key][index][key]


问:
How can loading factors from PCA be used to calculate an index that can be applied for each individual in a data frame in R?
I am using principal component analysis (PCA) based on ~30 variables to compose an index that classifies individuals in 3 different categories (top, middle, bottom) in R.

I have a dataframe of ~2000 individuals with 28 binary and 2 continuous variables.

Now, I would like to use the loading factors from PC1 to construct an
index that classifies my 2000 individuals for these 30 variables in 3 different groups.

Problem: Despite extensive research, I could not find out how to extract the loading factors from PCA_loadings, give each individual a score (based on the loadings of the 30 variables), which would subsequently allow me to rank each individual (for further classification). Does it make sense to display the loading factors in a graph?

I've performed the following steps:

a) Ran a PCA using PCA_outcome <- prcomp(na.omit(df1), scale = T)

b) Extracted the loadings using PCA_loadings <- PCA_outcome$rotation

c) Removed all the variables for which the loading factors were close to 0.

I have considered creating 30 new variable, one for each loading factor, which I would sum up for each binary variable == 1 (though, I am not sure how to proceed with the continuous variables). Consequently, I would assign each individual a score. However, I would not know how to assemble the 30 values from the loading factors to a score for each individual.

R code

```<code>df1 <- read.table(text="
          educ     call      house  merge_id    school  members
A           1        0          1      12_3        0      0.9
B           0        0          0      13_3        1      0.8
C           1        1          1      14_3        0      1.1
D           0        0          0      15_3        1      0.8
E           1        1          1      16_3        3      3.2", header=T)

## Run PCA
PCA_outcome <- prcomp(na.omit(df1), scale = T)

## Extract loadings
PCA_loadings <- PCA_outcome$rotation

## Explanation: A-E are 5 of the 2000 individuals and the variables (education, call, house, school, members) represent my 30 variables (binary and continuous).

</code>```

Expected results:
- Get a rank score for each individual
- Subsequently, assign a category 1-3 to each individual.

答:
I'm not 100% sure what you're asking, but here's an answer to the question I think you're asking.

First of all, PC1 of a PCA won't necessarily provide you with an index of socio-economic status. As explained here, PC1 simply "accounts for as much of the variability in the data as possible". PC1 may well work as a good metric for socio-economic status for your data set, but you'll have to critically examine the loadings and see if this makes sense. Depending on the signs of the loadings, it could be that a very negative PC1 corresponds to a very positive socio-economic status. As I say: look at the results with a critical eye. An explanation of how PC scores are calculated can be found here. Anyway, that's a discussion that belongs on Cross Validated, so let's get to the code.

It sounds like you want to perform the PCA, pull out PC1, and associate it with your original data frame (and merge_ids). If that's your goal, here's a solution.

# Create data frame
df <- read.table(text = "educ     call      house  merge_id    school  members
A           1        0          1      12_3        0      0.9
B           0        0          0      13_3        1      0.8
C           1        1          1      14_3        0      1.1
D           0        0          0      15_3        1      0.8
E           1        1          1      16_3        3      3.2", header = TRUE)

# Perform PCA
PCA <- prcomp(df[, names(df) != "merge_id"], scale = TRUE, center = TRUE)

# Add PC1
df$PC1 <- PCA$x[, 1]

# Look at new data frame
print(df)
#>   educ call house merge_id school members        PC1
#> A    1    0     1     12_3      0     0.9  0.1000145
#> B    0    0     0     13_3      1     0.8  1.6610864
#> C    1    1     1     14_3      0     1.1 -0.8882381
#> D    0    0     0     15_3      1     0.8  1.6610864
#> E    1    1     1     16_3      3     3.2 -2.5339491
```

Created on 2019-05-30 by the reprex package (v0.2.1.9000)

As you say you have to use PCA, I'm assuming this is for a homework question, so I'd recommend reading up on PCA so that you get a feel of what it does and what it's useful for.

Body:
I am using principal component analysis (PCA) based on ~30 variables to compose an index that classifies individuals in 3 different categories (top, middle, bottom) in R.

I have a dataframe of ~2000 individuals with 28 binary and 2 continuous variables.

Now, I would like to use the loading factors from PC1 to construct an
index that classifies my 2000 individuals for these 30 variables in 3 different groups.

Problem: Despite extensive research, I could not find out how to extract the loading factors from PCA_loadings, give each individual a score (based on the loadings of the 30 variables), which would subsequently allow me to rank each individual (for further classification). Does it make sense to display the loading factors in a graph?

I've performed the following steps:

a) Ran a PCA using PCA_outcome <- prcomp(na.omit(df1), scale = T)

b) Extracted the loadings using PCA_loadings <- PCA_outcome$rotation

c) Removed all the variables for which the loading factors were close to 0.

I have considered creating 30 new variable, one for each loading factor, which I would sum up for each binary variable == 1 (though, I am not sure how to proceed with the continuous variables). Consequently, I would assign each individual a score. However, I would not know how to assemble the 30 values from the loading factors to a score for each individual.

R code

df1 <- read.table(text="
          educ     call      house  merge_id    school  members
A           1        0          1      12_3        0      0.9
B           0        0          0      13_3        1      0.8
C           1        1          1      14_3        0      1.1
D           0        0          0      15_3        1      0.8
E           1        1          1      16_3        3      3.2", header=T)

## Run PCA
PCA_outcome <- prcomp(na.omit(df1), scale = T)

## Extract loadings
PCA_loadings <- PCA_outcome$rotation

## Explanation: A-E are 5 of the 2000 individuals and the variables (education, call, house, school, members) represent my 30 variables (binary and continuous).

Expected results:
- Get a rank score for each individual
- Subsequently, assign a category 1-3 to each individual.

Body:
I'm not 100% sure what you're asking, but here's an answer to the question I think you're asking.

First of all, PC1 of a PCA won't necessarily provide you with an index of socio-economic status. As explained here, PC1 simply "accounts for as much of the variability in the data as possible". PC1 may well work as a good metric for socio-economic status for your data set, but you'll have to critically examine the loadings and see if this makes sense. Depending on the signs of the loadings, it could be that a very negative PC1 corresponds to a very positive socio-economic status. As I say: look at the results with a critical eye. An explanation of how PC scores are calculated can be found here. Anyway, that's a discussion that belongs on Cross Validated, so let's get to the code.

It sounds like you want to perform the PCA, pull out PC1, and associate it with your original data frame (and merge_ids). If that's your goal, here's a solution.

# Create data frame
df <- read.table(text = "educ     call      house  merge_id    school  members
A           1        0          1      12_3        0      0.9
B           0        0          0      13_3        1      0.8
C           1        1          1      14_3        0      1.1
D           0        0          0      15_3        1      0.8
E           1        1          1      16_3        3      3.2", header = TRUE)

# Perform PCA
PCA <- prcomp(df[, names(df) != "merge_id"], scale = TRUE, center = TRUE)

# Add PC1
df$PC1 <- PCA$x[, 1]

# Look at new data frame
print(df)
#>   educ call house merge_id school members        PC1
#> A    1    0     1     12_3      0     0.9  0.1000145
#> B    0    0     0     13_3      1     0.8  1.6610864
#> C    1    1     1     14_3      0     1.1 -0.8882381
#> D    0    0     0     15_3      1     0.8  1.6610864
#> E    1    1     1     16_3      3     3.2 -2.5339491

Created on 2019-05-30 by the reprex package (v0.2.1.9000)

As you say you have to use PCA, I'm assuming this is for a homework question, so I'd recommend reading up on PCA so that you get a feel of what it does and what it's useful for.


问:
Laravel - Get value from an object
I have an PHP object coming back from an API. The following is dd($token):

```<code>OAuth2AccessToken {#559 ▼
  -accessTokenKey: "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxn8F2X3MBCZYY1g7Do66LIK"
  -tokenType: "bearer"
  -refresh_token: "Q01156b975259zYyAN03aS8lf6YfRcYFK26w2xCvPu75zf0B9F"
  -accessTokenExpiresAt: 1559257067
  -refreshTokenExpiresAt: 1567975300
  -accessTokenValidationPeriod: 3600
  -refreshTokenValidationPeriod: 8751833
  -clientID: "Q06uUceuP2dpIJVmmqbWztlZ73dtb9Qd2shjbiKhkGt7lsimR"
  -clientSecret: "RD0fS7xiRNsmbwSBBXvgU3wsqtyNPy63DfoGq2"
  -realmID: "1385384240"
  -baseURL: "https://quickbooks.api.intuit.com/"
}
</code>```

How do I get the key "accessTokenKey" into a variable?

I have tried:

```<code>$token->accessTokenKey;
</code>```

or

```<code>$token['accessTokenKey'];
</code>```

I get error "Cannot access private property"

答:
In this case, is a private propety. This propety cannot be called outside from Model/Class, because its private, can be only access by Class. You need to use some function to get this. Maybe you can get with
$token->getAccessToken(). I should you learn more about OOP Concepts. In very essential in Laravel.

public scope to make that variable/function available from anywhere, other classes and instances of the object.

private scope when you want your variable/function to be visible in its own class only.

protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

Title: Laravel - Get value from an object

Body:
I have an PHP object coming back from an API. The following is dd($token):

OAuth2AccessToken {#559 ▼
  -accessTokenKey: "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxn8F2X3MBCZYY1g7Do66LIK"
  -tokenType: "bearer"
  -refresh_token: "Q01156b975259zYyAN03aS8lf6YfRcYFK26w2xCvPu75zf0B9F"
  -accessTokenExpiresAt: 1559257067
  -refreshTokenExpiresAt: 1567975300
  -accessTokenValidationPeriod: 3600
  -refreshTokenValidationPeriod: 8751833
  -clientID: "Q06uUceuP2dpIJVmmqbWztlZ73dtb9Qd2shjbiKhkGt7lsimR"
  -clientSecret: "RD0fS7xiRNsmbwSBBXvgU3wsqtyNPy63DfoGq2"
  -realmID: "1385384240"
  -baseURL: "https://quickbooks.api.intuit.com/"
}

How do I get the key "accessTokenKey" into a variable?

I have tried:

$token->accessTokenKey;

or

$token['accessTokenKey'];

I get error "Cannot access private property"


问:
Counting particular words
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

```<code>def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))
</code>```

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

答:
Providing answer that doesn't involve list comprehension in case it may be easier to understand.</p>

```<code>def word5(wlist):
    cnt=0
    for word in wordList:
        cnt += 1 if len(word) == 5 else 0
    return cnt
</code>```

Title: Counting particular words

Body:
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

Body:
Providing answer that doesn't involve list comprehension in case it may be easier to understand.

def word5(wlist):
    cnt=0
    for word in wordList:
        cnt += 1 if len(word) == 5 else 0
    return cnt


问:
Trouble connecting to Oracle 18c XE on Windows Server 2012 r2
A few weeks ago I had installed Oracle 18c XE on my Win10 PC to test an app. Once everything checked out, we installed the same thing on Windows Server 2012r2. When connecting to SQLPlus we get an error message ORACLE is not available. Then after attempting startup we get Oracle DB XE memory parameters invalid or not specified.

I am unsure where this value is set or how to fix this issue. This worked fine on my PC and I have no outside experience of getting the database set up on a server. Any help would be greatly appreciated. Thanks

答: I posted this in haste after working a few hours trying to get this working. This was fixed by adding the an entry in the listener.ora file for the XE service instance. After this, I was able go execute the startup command in SQLPlus. I do need more help but will post my question in the DBA Stack Exchange server.


问:
slice modified between goroutines with mutex not showing correct synchronization
I am new to go, but have worked with concurrency before. I am having an issue sharing a slice between multiple goroutines not containing the same data between all of the goroutines. I use a mutex as well to lock the struct when I modify the slice, but it doesn't seem to help. I have attached my code and would like to know what I am doing wrong, thanks for any help!

type State struct {
    waiting int32
    processing int32
    completed int32
}

type Scheduler struct {
    sync.Mutex
    items chan interface{}
    backPressure []interface{}
    capacity int
    canceler context.CancelFunc
    state State
}

func NewScheduler(capacity int, handler func(interface {}) (interface{}, error)) Scheduler {
    ctx, cancel := context.WithCancel(context.Background())

    state := State{}

    atomic.StoreInt32(&state.waiting, 0)
    atomic.StoreInt32(&state.processing, 0)
    atomic.StoreInt32(&state.completed, 0)

    scheduler := Scheduler{
        items: make(chan interface{}, capacity),
        backPressure: make([]interface{}, 0),
        capacity: capacity,
        canceler: cancel,
        state: state,
    }

    scheduler.initializeWorkers(ctx, handler)

    return scheduler
}

func (s *Scheduler) initializeWorkers(ctx context.Context, handler func(interface {}) (interface{}, error)) {
    for i := 0; i < 5; i++ {
        go s.newWorker(ctx, handler)
    }
}

func (s *Scheduler) newWorker(ctx context.Context, handler func(interface {}) (interface{}, error)) {
    backoff := 0

    for {
        select {
        case <-ctx.Done():
            return
        case job := <- s.items:
            atomic.AddInt32(&s.state.waiting, -1)
            atomic.AddInt32(&s.state.processing, 1)
            job, _ = handler(job)
            backoff = 0
            atomic.AddInt32(&s.state.processing, -1)
            atomic.AddInt32(&s.state.completed, 1)
        default:
            backoff += 1
            s.CheckBackPressure()
            time.Sleep(time.Duration(backoff * 10) * time.Millisecond)
        }
    }
}

func (s *Scheduler) AddItem(item interface{}) {
    atomic.AddInt32(&s.state.waiting, 1)

    if len(s.items) < s.capacity {
        select {
        case s.items <- item:
            return
        }
    }

    s.Lock()
    defer s.Unlock()

    s.backPressure = append(s.backPressure, item)

    fmt.Printf("new backpressure len %v \n", len(s.backPressure))

    return
}

func (s *Scheduler) Process() {
    var wg sync.WaitGroup

    wg.Add(1)

    go func() {
        defer wg.Done()

        for {
            if atomic.LoadInt32(&s.state.waiting) == 0 && atomic.LoadInt32(&s.state.processing) == 0 {
                return
            }
            runtime.Gosched()
        }
    }()

    wg.Wait()
}

func (s *Scheduler) CheckBackPressure() {
    s.Lock()
    defer s.Unlock()

    if len(s.backPressure) == 0 || s.capacity <= len(s.items) {
        fmt.Printf("backpressure = %d  :: len = %d cap = %d \n", len(s.backPressure), len(s.items), s.capacity)
        return
    }

    fmt.Printf("releasing backpressure \n")

    job, tmp := s.backPressure[0], s.backPressure[1:]

    s.backPressure = tmp

    s.items <- job
    return
}

func (s *Scheduler) Stop() {
    s.canceler()
}
```

<p>This is the code that I am using to test the functionality:</p>

<pre class="lang-golang prettyprint-override"><code>type Job struct {
    Value int
}

func TestSchedulerExceedingCapacity(t *testing.T) {

    handler := func (ptr interface{}) (interface{}, error) {
        job, ok := (ptr).(*Job)

        if ok != true {
            return nil, errors.New("failed to convert job")
        }

        // simulate work
        time.Sleep(50 * time.Millisecond)

        return job, nil
    }

    scheduler := NewScheduler(5, handler)

    for i := 0; i < 25; i++ {
        scheduler.AddItem(&(Job { Value: i }))
    }

    fmt.Printf("PROCESSING\n")
    scheduler.Process()
    fmt.Printf("FINISHED\n")
}
</code>```

When I update the slice that holds the back pressure, it seems to indicate that it was correctly updated by printing new backpressure len 1 for 1-16.

However, when I check the back pressure from the worker, it indicates that the backpressure slice is empty. backpressure = 0  :: len = 0 cap = 5.

Also "releasing backpressure" is never printed to stdout either.

Here is some additional output...

```<code>=== RUN   TestSchedulerExceedingCapacity
new backpressure len 1
new backpressure len 2
new backpressure len 3
new backpressure len 4
new backpressure len 5
new backpressure len 6
new backpressure len 7
new backpressure len 8
backpressure = 0  :: len = 0 cap = 5
new backpressure len 9
new backpressure len 10
new backpressure len 11
new backpressure len 12
new backpressure len 13
new backpressure len 14
new backpressure len 15
new backpressure len 16
PROCESSING
backpressure = 0  :: len = 0 cap = 5
backpressure = 0  :: len = 0 cap = 5
backpressure = 0  :: len = 0 cap = 5
...
</code>```

If I don't kill the test it indefinitely prints backpressure = 0  :: len = 0 cap = 5

I am assuming that I am not correctly synchronizing the changes, I would REALLY appreciate any insights, thanks!

答:
Okay I was able to figure this out of course once I posted the question...

I saw somewhere that suggested to run the test with the -race option which enables the data race detector. I immediately got errors which helped make the problem easier to debug.

It turns out that the problem was related to returning the value of NewScheduler rather than the pointer of new scheduler. I changed that function to the following code, which fixed the issue.

func NewScheduler(capacity int, handler func(interface {}) (interface{}, error)) *Scheduler {
    ctx, cancel := context.WithCancel(context.Background())

    state := State{}

    atomic.StoreInt32(&state.waiting, 0)
    atomic.StoreInt32(&state.processing, 0)
    atomic.StoreInt32(&state.completed, 0)
    atomic.StoreInt32(&state.errors, 0)

    scheduler := Scheduler{
        items: make(chan interface{}, capacity),
        backPressure: make([]interface{}, 0),
        capacity: capacity,
        canceler: cancel,
        state: state,
    }

    scheduler.initializeWorkers(ctx, handler)

    return &scheduler
}
```

Body:
I am new to go, but have worked with concurrency before. I am having an issue sharing a slice between multiple goroutines not containing the same data between all of the goroutines. I use a mutex as well to lock the struct when I modify the slice, but it doesn't seem to help. I have attached my code and would like to know what I am doing wrong, thanks for any help!

type State struct {
    waiting int32
    processing int32
    completed int32
}

type Scheduler struct {
    sync.Mutex
    items chan interface{}
    backPressure []interface{}
    capacity int
    canceler context.CancelFunc
    state State
}

func NewScheduler(capacity int, handler func(interface {}) (interface{}, error)) Scheduler {
    ctx, cancel := context.WithCancel(context.Background())

    state := State{}

    atomic.StoreInt32(&state.waiting, 0)
    atomic.StoreInt32(&state.processing, 0)
    atomic.StoreInt32(&state.completed, 0)

    scheduler := Scheduler{
        items: make(chan interface{}, capacity),
        backPressure: make([]interface{}, 0),
        capacity: capacity,
        canceler: cancel,
        state: state,
    }

    scheduler.initializeWorkers(ctx, handler)

    return scheduler
}

func (s *Scheduler) initializeWorkers(ctx context.Context, handler func(interface {}) (interface{}, error)) {
    for i := 0; i < 5; i++ {
        go s.newWorker(ctx, handler)
    }
}

func (s *Scheduler) newWorker(ctx context.Context, handler func(interface {}) (interface{}, error)) {
    backoff := 0

    for {
        select {
        case <-ctx.Done():
            return
        case job := <- s.items:
            atomic.AddInt32(&s.state.waiting, -1)
            atomic.AddInt32(&s.state.processing, 1)
            job, _ = handler(job)
            backoff = 0
            atomic.AddInt32(&s.state.processing, -1)
            atomic.AddInt32(&s.state.completed, 1)
        default:
            backoff += 1
            s.CheckBackPressure()
            time.Sleep(time.Duration(backoff * 10) * time.Millisecond)
        }
    }
}

func (s *Scheduler) AddItem(item interface{}) {
    atomic.AddInt32(&s.state.waiting, 1)

    if len(s.items) < s.capacity {
        select {
        case s.items <- item:
            return
        }
    }

    s.Lock()
    defer s.Unlock()

    s.backPressure = append(s.backPressure, item)

    fmt.Printf("new backpressure len %v \n", len(s.backPressure))

    return
}

func (s *Scheduler) Process() {
    var wg sync.WaitGroup

    wg.Add(1)

    go func() {
        defer wg.Done()

        for {
            if atomic.LoadInt32(&s.state.waiting) == 0 && atomic.LoadInt32(&s.state.processing) == 0 {
                return
            }
            runtime.Gosched()
        }
    }()

    wg.Wait()
}

func (s *Scheduler) CheckBackPressure() {
    s.Lock()
    defer s.Unlock()

    if len(s.backPressure) == 0 || s.capacity <= len(s.items) {
        fmt.Printf("backpressure = %d  :: len = %d cap = %d \n", len(s.backPressure), len(s.items), s.capacity)
        return
    }

    fmt.Printf("releasing backpressure \n")

    job, tmp := s.backPressure[0], s.backPressure[1:]

    s.backPressure = tmp

    s.items <- job
    return
}

func (s *Scheduler) Stop() {
    s.canceler()
}

This is the code that I am using to test the functionality:

type Job struct {
    Value int
}

func TestSchedulerExceedingCapacity(t *testing.T) {

    handler := func (ptr interface{}) (interface{}, error) {
        job, ok := (ptr).(*Job)

        if ok != true {
            return nil, errors.New("failed to convert job")
        }

        // simulate work
        time.Sleep(50 * time.Millisecond)

        return job, nil
    }

    scheduler := NewScheduler(5, handler)

    for i := 0; i < 25; i++ {
        scheduler.AddItem(&(Job { Value: i }))
    }

    fmt.Printf("PROCESSING\n")
    scheduler.Process()
    fmt.Printf("FINISHED\n")
}

When I update the slice that holds the back pressure, it seems to indicate that it was correctly updated by printing new backpressure len 1 for 1-16.

However, when I check the back pressure from the worker, it indicates that the backpressure slice is empty. backpressure = 0  :: len = 0 cap = 5.

Also "releasing backpressure" is never printed to stdout either.

Here is some additional output...

=== RUN   TestSchedulerExceedingCapacity
new backpressure len 1
new backpressure len 2
new backpressure len 3
new backpressure len 4
new backpressure len 5
new backpressure len 6
new backpressure len 7
new backpressure len 8
backpressure = 0  :: len = 0 cap = 5
new backpressure len 9
new backpressure len 10
new backpressure len 11
new backpressure len 12
new backpressure len 13
new backpressure len 14
new backpressure len 15
new backpressure len 16
PROCESSING
backpressure = 0  :: len = 0 cap = 5
backpressure = 0  :: len = 0 cap = 5
backpressure = 0  :: len = 0 cap = 5
...

If I don't kill the test it indefinitely prints backpressure = 0  :: len = 0 cap = 5

I am assuming that I am not correctly synchronizing the changes, I would REALLY appreciate any insights, thanks!


问:
Remove files and foldes on Azure before a new deploy from VSTS
As part of my build process in VSTS I want to delete all files and folders (except af few) from my azure site before a new deploy. My guess is, that using a Azure Powershell script would be a good idea and I would prefer making an inline script.

I am using Azure Resource Manager as connection type, I have selected my subscription and script type (Inline Script) but then I am lost, how do i select my app service and, for a start, list my files?

Trying just, this for a test, only gives my files in my VSTS environment

```<code>Get-ChildItem -Path $(build.sourcesDirectory)
</code>```

答:
This is how you can test your settings that you use in the PowerShell scripts above using Postman.

I found it useful to play with the REST API using Postman to understand what the PowerShell scripts above were doing and understand what status codes I could expect back from the API.  I also noticed that the recursive logic for deleting a directory returns a 409 Conflict error even though is DOES delete the files.

In the examples below, my app service is called "YatesDeleteMe"

Create a base 64 encoded username and password string to use below in your authorization header OR run the PowerShell scripts above and it will output one for you

Download your app service's publish file, which can be downloaded from the Overview tab in the Azure portal.

Open the file with a text editor

Find the username (user name example:  $YatesDeleteMe  ) and password (password example: ch222cDlpCjx4Glq333qo4QywGPMs1cK2Rjrn6phqZ9HswtgEEE12CrhDmcn )

Create a string out of them and separate them with a colon (should look something like this:  $YatesDeleteMe:ch222cDlpCjx4Glq333qo4QywGPMs1cK2Rjrn6phqZ9HswtgEEE12CrhDmcn )

Base 64 encode them using your own program a site.   The result should look something like this: JFlhdGVzRGVsZXRlTWU6Y2gyMjJjRGxwQ2p4NEdscTMzM3FvNFF5d0dQTXMxY0syUmpybjZwaHFaOUhzd3RnRUVFMTJDcmhEbWNu

Retrieve a single file

Open Postman

Change the verb to GET

Enter your URL to the file you want to retrieve (e.g., https://YatesDeleteMe.scm.azurewebsites.net/api/vfs/site/wwwroot/web.config).  For more info on paths see this

Added a header-->

Key: Authorization

Value:  Basic YourBase64EncodedStringFromAbove

Left-click the "Send" button and the file will download

Delete a single file

Open Postman

Change the verb to DELETE

Enter your URL to the file you want to delete (e.g., https://YatesDeleteMe.scm.azurewebsites.net/api/vfs/site/wwwroot/web.config)

Added a header-->

Key: Authorization

Value:  Basic YourBase64EncodedStringFromAbove

Added a header-->

Key: If-Match

Value: *

Left-click the "Send" button and the file will deleted

Delete all the files in a directory

Open Postman

Change the verb to DELETE

Enter your URL to the folder you want to delete PLUST add slash and then the query string ?recursive=true (e.g., https://YatesDeleteMe.scm.azurewebsites.net/api/vfs/site/wwwroot/?recursive=true)

Added a header-->

Key: Authorization

Value:  Basic YourBase64EncodedStringFromAbove

Added a header-->

Key: If-Match

Value: *

Left-click the "Send" button and the folder will deleted.  I always get a 409 error back, but the folder is deleted.

Reference

Blog post with pictures here.

ContentLicense: CC BY-SA 3.0

Body:
As part of my build process in VSTS I want to delete all files and folders (except af few) from my azure site before a new deploy. My guess is, that using a Azure Powershell script would be a good idea and I would prefer making an inline script.

I am using Azure Resource Manager as connection type, I have selected my subscription and script type (Inline Script) but then I am lost, how do i select my app service and, for a start, list my files?

Trying just, this for a test, only gives my files in my VSTS environment

Get-ChildItem -Path $(build.sourcesDirectory)


问:
ctc_loss error "No valid path found."
Training a model with tf.nn.ctc_loss produces an error every time the train op is run:

```<code>tensorflow/core/util/ctc/ctc_loss_calculator.cc:144] No valid path found.
</code>```

Unlike in previous questions about this function, this is not due to divergence. I have a low learning rate, and the error occurs on even the first train op.

The model is a CNN -> LSTM -> CTC. Here is the model creation code:

```<code># Build Graph
self.videoInput = tf.placeholder(shape=(None, self.maxVidLen, 50, 100, 3), dtype=tf.float32)
self.videoLengths = tf.placeholder(shape=(None), dtype=tf.int32)
self.keep_prob = tf.placeholder(dtype=tf.float32)
self.targets = tf.sparse_placeholder(tf.int32)
self.targetLengths = tf.placeholder(shape=(None), dtype=tf.int32)

conv1 = tf.layers.conv3d(self.videoInput ...)
pool1 = tf.layers.max_pooling3d(conv1 ...)
conv2 = ...
pool2 = ...
conv3 = ...
pool3 = ...

cnn_out = tf.reshape(pool3, shape=(-1, self.maxVidLength, 4*7*96))

fw_cell = tf.nn.rnn_cell.MultiRNNCell(self.cell(), for _ in range(3))
bw_cell = tf.nn.rnn_cell.MultiRNNCell(self.cell(), for _ in range(3))
outputs, _ = tf.nn.bidirectional_dynamic_rnn(
            fw_cell, bw_cell, cnn_out, sequence_length=self.videoLengths, dtype=tf.float32)

outputs = tf.concat(outputs, 2)
outputs = tf.reshape(outputs, [-1, self.hidden_size * 2])

w = tf.Variable(tf.random_normal((self.hidden_size * 2, len(self.char2index) + 1), stddev=0.2))
b = tf.Variable(tf.zeros(len(self.char2index) + 1))

out = tf.matmul(outputs, w) + b
out = tf.reshape(out, [-1, self.maxVidLen, len(self.char2index) + 1])
out = tf.transpose(out, [1, 0, 2])

cost = tf.reduce_mean(tf.nn.ctc_loss(self.targets, out, self.targetLengths))
self.train_op = tf.train.AdamOptimizer(0.0001).minimize(cost)
</code>```

And here is the feed dict creation code:

```<code>indices = []
values = []
shape = [len(vids) * 2, self.maxLabelLen]
vidInput = np.zeros((len(vids) * 2, self.maxVidLen, 50, 100, 3), dtype=np.float32)

# Actual video, then left-right flip
for j in range(len(vids) * 2):

    # K is video index
    k = j if j < len(vids) else j - len(vids)

    # convert video and label to input format
    vidInput[j, 0:len(vids[k])] = vids[k] if k == j else vids[k][:,::-1,:]
    indices.extend([j, i] for i in range(len(labelList[k])))
    values.extend(self.char2index[c] for c in labelList[k])

fd[self.targets] = (indices, values, shape)
fd[self.videoInput] = vidInput

# Collect video lengths and label lengths
vidLengths = [len(j) for j in vids] + [len(j) for j in vids]
labelLens = [len(l) for l in labelList] + [len(l) for l in labelList]
fd[self.videoLengths] = vidLengths
fd[self.targetLengths] = labelLens
</code>```

答:
I had the same issue but I soon realized it was just because I was using glob and my label was in the filename so it was exceeding.

You can fix this issue by using:

```<code>os.path.join(*(filename.split(os.path.sep)[noOfDir:]))
</code>```

Title: ctc_loss error "No valid path found."

Body:
Training a model with tf.nn.ctc_loss produces an error every time the train op is run:

tensorflow/core/util/ctc/ctc_loss_calculator.cc:144] No valid path found.

Unlike in previous questions about this function, this is not due to divergence. I have a low learning rate, and the error occurs on even the first train op.

The model is a CNN -> LSTM -> CTC. Here is the model creation code:

# Build Graph
self.videoInput = tf.placeholder(shape=(None, self.maxVidLen, 50, 100, 3), dtype=tf.float32)
self.videoLengths = tf.placeholder(shape=(None), dtype=tf.int32)
self.keep_prob = tf.placeholder(dtype=tf.float32)
self.targets = tf.sparse_placeholder(tf.int32)
self.targetLengths = tf.placeholder(shape=(None), dtype=tf.int32)

conv1 = tf.layers.conv3d(self.videoInput ...)
pool1 = tf.layers.max_pooling3d(conv1 ...)
conv2 = ...
pool2 = ...
conv3 = ...
pool3 = ...

cnn_out = tf.reshape(pool3, shape=(-1, self.maxVidLength, 4*7*96))

fw_cell = tf.nn.rnn_cell.MultiRNNCell(self.cell(), for _ in range(3))
bw_cell = tf.nn.rnn_cell.MultiRNNCell(self.cell(), for _ in range(3))
outputs, _ = tf.nn.bidirectional_dynamic_rnn(
            fw_cell, bw_cell, cnn_out, sequence_length=self.videoLengths, dtype=tf.float32)

outputs = tf.concat(outputs, 2)
outputs = tf.reshape(outputs, [-1, self.hidden_size * 2])

w = tf.Variable(tf.random_normal((self.hidden_size * 2, len(self.char2index) + 1), stddev=0.2))
b = tf.Variable(tf.zeros(len(self.char2index) + 1))

out = tf.matmul(outputs, w) + b
out = tf.reshape(out, [-1, self.maxVidLen, len(self.char2index) + 1])
out = tf.transpose(out, [1, 0, 2])

cost = tf.reduce_mean(tf.nn.ctc_loss(self.targets, out, self.targetLengths))
self.train_op = tf.train.AdamOptimizer(0.0001).minimize(cost)

And here is the feed dict creation code:

indices = []
values = []
shape = [len(vids) * 2, self.maxLabelLen]
vidInput = np.zeros((len(vids) * 2, self.maxVidLen, 50, 100, 3), dtype=np.float32)

# Actual video, then left-right flip
for j in range(len(vids) * 2):

    # K is video index
    k = j if j < len(vids) else j - len(vids)

    # convert video and label to input format
    vidInput[j, 0:len(vids[k])] = vids[k] if k == j else vids[k][:,::-1,:]
    indices.extend([j, i] for i in range(len(labelList[k])))
    values.extend(self.char2index[c] for c in labelList[k])

fd[self.targets] = (indices, values, shape)
fd[self.videoInput] = vidInput

# Collect video lengths and label lengths
vidLengths = [len(j) for j in vids] + [len(j) for j in vids]
labelLens = [len(l) for l in labelList] + [len(l) for l in labelList]
fd[self.videoLengths] = vidLengths
fd[self.targetLengths] = labelLens

Body:
I had the same issue but I soon realized it was just because I was using glob and my label was in the filename so it was exceeding.

You can fix this issue by using:

os.path.join(*(filename.split(os.path.sep)[noOfDir:]))


问:
number of letters to be deleted from a string so that it is divisible by another string
I am doing this problem https://www.spoj.com/problems/DIVSTR/

We are given two strings S and T.
S is divisible by string T if there is some non-negative integer k, which satisfies the equation S=k*T

What is the minimum number of characters which should be removed from S, so that S is divisible by T?

The main idea was to match T with S using a pointer and count the number of instances of T occurring in S when the count is done, bring the pointer to the start of T and if there's a mismatch, compare T's first letter with S's present letter.

This code is working totally fine with test cases they provided and custom test cases I gave, but it could not get through hidden test cases.

this is the code

def no_of_letters(string1,string2):
#     print(len(string1),len(string2))
    count = 0
    pointer = 0
    if len(string1)<len(string2):
        return len(string1)
    if (len(string1)==len(string2)) and (string1!=string2):
        return len(string1)
    for j in range(len(string1)):
        if (string1[j]==string2[pointer]) and pointer<(len(string2)-1):
            pointer+=1
        elif (string1[j]==string2[pointer]) and pointer == (len(string2)-1):
            count+=1
            pointer=0
        elif (string1[j]!=string2[pointer]):
            if string1[j]==string2[0]:
                pointer=1
            else:
                pointer = 0
    return len(string1)-len(string2)*count
```

One place where I think there should be confusion is when same letters can be parts of two counts, but it should not be a problem, because our answer doesn't need to take overlapping into account.

for example, S = 'akaka' T= 'aka' will give the output 2, irrespective of considering first 'aka',ka as count or second ak,'aka'.

答:
I believe that the solution is much more straightforward that you make it.  You're simply trying to find how many times the characters of T appear, in order, in S.  Everything else is the characters you remove.  For instance, given RobertBaron's example of S="akbaabka" and T="aka", you would write your routine to locate the characters a, k, a, in that order, from the start of S:

```<code>akbaabka
ak a^
# with some pointer, ptr, now at position 4, marked with a caret above
</code>```

With that done, you can now recur on the remainder of the string:

```<code>find_chars(S[ptr:], T)
</code>```

With each call, you look for T in S; if you find it, count 1 repetition and recur on the remainder of S; if not, return 0 (base case).  As you crawl back up your recursion stack, accumulate all the 1 counts, and there is your value of k.

The quantity of chars to remove is len(s) - k*len(T).

Can you take it from there?

Body:
I am doing this problem https://www.spoj.com/problems/DIVSTR/

We are given two strings S and T.
S is divisible by string T if there is some non-negative integer k, which satisfies the equation S=k*T

What is the minimum number of characters which should be removed from S, so that S is divisible by T?

The main idea was to match T with S using a pointer and count the number of instances of T occurring in S when the count is done, bring the pointer to the start of T and if there's a mismatch, compare T's first letter with S's present letter.

This code is working totally fine with test cases they provided and custom test cases I gave, but it could not get through hidden test cases.

this is the code

def no_of_letters(string1,string2):
#     print(len(string1),len(string2))
    count = 0
    pointer = 0
    if len(string1)<len(string2):
        return len(string1)
    if (len(string1)==len(string2)) and (string1!=string2):
        return len(string1)
    for j in range(len(string1)):
        if (string1[j]==string2[pointer]) and pointer<(len(string2)-1):
            pointer+=1
        elif (string1[j]==string2[pointer]) and pointer == (len(string2)-1):
            count+=1
            pointer=0
        elif (string1[j]!=string2[pointer]):
            if string1[j]==string2[0]:
                pointer=1
            else:
                pointer = 0
    return len(string1)-len(string2)*count

One place where I think there should be confusion is when same letters can be parts of two counts, but it should not be a problem, because our answer doesn't need to take overlapping into account.

for example, S = 'akaka' T= 'aka' will give the output 2, irrespective of considering first 'aka',ka as count or second ak,'aka'.

Body:
I believe that the solution is much more straightforward that you make it.  You're simply trying to find how many times the characters of T appear, in order, in S.  Everything else is the characters you remove.  For instance, given RobertBaron's example of S="akbaabka" and T="aka", you would write your routine to locate the characters a, k, a, in that order, from the start of S:

akbaabka
ak a^
# with some pointer, ptr, now at position 4, marked with a caret above

With that done, you can now recur on the remainder of the string:

find_chars(S[ptr:], T)

With each call, you look for T in S; if you find it, count 1 repetition and recur on the remainder of S; if not, return 0 (base case).  As you crawl back up your recursion stack, accumulate all the 1 counts, and there is your value of k.

The quantity of chars to remove is len(s) - k*len(T).

Can you take it from there?


答:
Is there a particular part you're trying to access?

Here are a few examples:

```<code>$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data = {'function':'data_chip',
...  'group_id': 172,
...  'Types': [
...     {'TMS0202':'SR-20',
...      'TMS0207':'SR-22',
...      'TMS0201': 'TI-4000',
...      'TMS0203': 'TI-450'
...     }
...  ]
... }
>>> data['function']
'data_chip'
>>> data['Types'][0]['TMS0202']
'SR-20'
>>> data['group_id']
172
</code>```

Title: access to nested data

Body:
Is there a particular part you're trying to access?

Here are a few examples:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data = {'function':'data_chip',
...  'group_id': 172,
...  'Types': [
...     {'TMS0202':'SR-20',
...      'TMS0207':'SR-22',
...      'TMS0201': 'TI-4000',
...      'TMS0203': 'TI-450'
...     }
...  ]
... }
>>> data['function']
'data_chip'
>>> data['Types'][0]['TMS0202']
'SR-20'
>>> data['group_id']
172


问:
Matlab kalman filter in python
is there a filter function of kalman in Python that works in the same way as the Kalman function of matlab?

```<code>[kest] = kalman(sys,Qn,Rn)
</code>```

The idea is that the function receives as parameters a space of states and the respective weight matrices (it is to implement an LQR controller)

答: I finally found the ovtave source code for the kalman filter and implemented it in python. Anyway, thank you very much</p>

Title: Matlab kalman filter in python

Body:
is there a filter function of kalman in Python that works in the same way as the Kalman function of matlab?

[kest] = kalman(sys,Qn,Rn)

The idea is that the function receives as parameters a space of states and the respective weight matrices (it is to implement an LQR controller)


问:
How to display data in ejs view from ajax resultset when called in the view
I have an empty ejs view but I would like to display the result set of the ajax call that I am calling in the ejs view

```<code><script>
 // Fetch
  $.ajax(`/x`).done(function(data, textStatus, xhr){
console.log(data);
console.log(textStatus);
console.log(xhr);
  });

</script>
<!-- how do I loop the data received from above and display the content here? -->
</code>```

I am not sure how to do this.

UPDATE

here is what I have now. Is there any neater way to do this instead of appending as html?

```<code><script>
  const gId = '<%= gId %>';

  // Fetch the current users c here from `/g/${gId }/c `
  $.ajax(`/g/${gId }/c `).done(function(data, textStatus, xhr){
    var c = '';
    $.each(data, function(index, value){
      console.log(index);
      console.log(value)
      c += '<div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="'+value.image+'" /></div><div class="text-center"><input name="card" id="card" type="checkbox" value="'+value.value+'" /> Discard</div></div>';
    });

    $('#c ').append('<div class="row"><div class="row col-sm-12">'+c +'</div><div class="col-xs-2"></div></div>');

    $('#c ').append('<button type="submit">c </button>');
  });

  const checkExchangeStatus = function(){
    $.ajax(`/g/${gId}/allExchanged`).done(function(data, textStatus, xhr){
      if (xhr.status !== 202) { // not pending
        document.location = `/g/${gId}/result`;
      }
    })
  }

  setInterval(checkExchangeStatus, 1000);
</script>
<form method="POST" action="/g/<%= gId %>/exchange">
<div id="c ">
</div>
<div>
<br/>gId : <%= gId %>
</div>
</form>
</code>```

答:
"ejs code like <% %> is executed on server and rendered as html. So you can't use ejs code with ajax requests."

What you can do is make an ajax call, then alter your html page with jQuery.

I have an empty ejs view but I would like to display the result set of the ajax call that I am calling in the ejs view.

```<code><script>
  $.ajax(`/x`).done(function(data, textStatus, xhr){
    console.log(data); //I am assuming this prints
      $('#someID').html(data);
  });
</script>
</code>```

I don't know what results you are expecting, or what your html looks like. If you update your question with more code I can assist you further.

Body:
I have an empty ejs view but I would like to display the result set of the ajax call that I am calling in the ejs view

I am not sure how to do this.

UPDATE

here is what I have now. Is there any neater way to do this instead of appending as html?

<form method="POST" action="/g/<%= gId %>/exchange">

gId : <%= gId %>

</form>

Body:
"ejs code like <% %> is executed on server and rendered as html. So you can't use ejs code with ajax requests."

What you can do is make an ajax call, then alter your html page with jQuery.

I have an empty ejs view but I would like to display the result set of the ajax call that I am calling in the ejs view.

<script>
  $.ajax(`/x`).done(function(data, textStatus, xhr){
    console.log(data); //I am assuming this prints
      $('#someID').html(data);
  });
</script>

I don't know what results you are expecting, or what your html looks like. If you update your question with more code I can assist you further.


问:
Read column values to variable in SSIS using for each loop
I want to read the resultset of a table using the following stmt:

```<code>Select col1 as A,col2 as B from tablename;
</code>```

Then, I want to read each row of the result set into local variables of the SSIS package and for each row I have to pass the values to the script task.

I want to use foreach loop in SSIS. I took Foreach Item Enumerator.

The question: How to read the values into the variable using the For each Item enumerator and how can i iterator can i use select count(*) from table; pass that value to a variable and asssign the count value in the foreach loop.

I'm stuck at how to assign the count value and read columns to variables. Can anyone help with these?

Thanks in advance.

答:
I'm not exactly sure what it is that you're trying to do, but it would seem that you're trying to process data in your control flow.  The foreach iterator is not made for processing data sets, it's made for iterating over multiple data sets and doing something to each of them, usually passing them to a data flow.

You might find it more useful to create a data flow.  Start with a data source component that gets the data that you want and then pass the data to a Script Component to do the processing.

Body:
I want to read the resultset of a table using the following stmt:

Select col1 as A,col2 as B from tablename;

Then, I want to read each row of the result set into local variables of the SSIS package and for each row I have to pass the values to the script task.

I want to use foreach loop in SSIS. I took Foreach Item Enumerator.

The question: How to read the values into the variable using the For each Item enumerator and how can i iterator can i use select count(*) from table; pass that value to a variable and asssign the count value in the foreach loop.

I'm stuck at how to assign the count value and read columns to variables. Can anyone help with these?

Thanks in advance.


问:
Regex to put missing quotes around keys of arrays
I try to correct my PHP-code and add to the quotes ' around the keys of the arrays in my source-code.

I have like 10,000 files to correct. Can I use some regular expressions to achieve that?

I tried to use this regular expression, but it is not perfect:

```<code>\$([0-9a-zA-z_\-]+)\[([0-9a-zA-z_\-]+)\]\[([0-9a-zA-z_\-]+)\]
</code>```

to

```<code>\$$1['$2']['$3']
</code>```

Example of what I want to change:

```<code>$_SESSION[Name][name_2] to $_SESSION['Name']['name_2']
$_POST[Name][na-me_2] to $_SESSION['Name']['na-me_2']
$_GET[Name][na-me_2] to $_GET['Name']['na-me_2']
$tab[name_one] to $tab['name_one']
</code>```

答:
We can most likely capture our indices with a group, then preg_replace it, maybe with an expression similar to:

```<code>\[(.+?)\]
</code>```

Test

```<code>$re = '/\[(.+?)\]/m';
$str = '$_SESSION[Name][name_2]
$_POST[Name][na-me_2]
$_GET[Name][na-me_2]
$tab[name_one]';
$subst = '[\'$1\']';

$result = preg_replace($re, $subst, $str);

echo $result;
</code>```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

If we wish to have more constraints, we can surely update this expression. For example, if we would have already had keys with ' or ", then we can just add a new boundary such as all chars except ' and " in a char class:

```<code>[^'"]*
</code>```

and our expression would become:

```<code>\[([^'"]*?)\]
</code>```

Demo

Test

```<code>$re = '/\[([^\'"]*?)\]/m';
$str = '$_SESSION[Name][name_2]
$_POST[Name][na-me_2]
$_GET[\'Name\'][na-me_2]
$tab[name_one]
$_POST[Name]["na-me_2"]
$_POST[\'Name\']["na-me_2"]';
$subst = '[\'$1\']';

$result = preg_replace($re, $subst, $str);

echo $result;
</code>```

Output

```<code>$_SESSION['Name']['name_2']
$_POST['Name']['na-me_2']
$_GET['Name']['na-me_2']
$tab['name_one']
$_POST['Name']["na-me_2"]
$_POST['Name']["na-me_2"]
</code>```

Body:
I try to correct my PHP-code and add to the quotes ' around the keys of the arrays in my source-code.

I have like 10,000 files to correct. Can I use some regular expressions to achieve that?

I tried to use this regular expression, but it is not perfect:

\$([0-9a-zA-z_\-]+)\[([0-9a-zA-z_\-]+)\]\[([0-9a-zA-z_\-]+)\]

to

\$$1['$2']['$3']

Example of what I want to change:

$_SESSION[Name][name_2] to $_SESSION['Name']['name_2']
$_POST[Name][na-me_2] to $_SESSION['Name']['na-me_2']
$_GET[Name][na-me_2] to $_GET['Name']['na-me_2']
$tab[name_one] to $tab['name_one']

Body:
We can most likely capture our indices with a group, then preg_replace it, maybe with an expression similar to:

\[(.+?)\]

Test

$re = '/\[(.+?)\]/m';
$str = '$_SESSION[Name][name_2]
$_POST[Name][na-me_2]
$_GET[Name][na-me_2]
$tab[name_one]';
$subst = '[\'$1\']';

$result = preg_replace($re, $subst, $str);

echo $result;

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

If we wish to have more constraints, we can surely update this expression. For example, if we would have already had keys with ' or ", then we can just add a new boundary such as all chars except ' and " in a char class:

[^'"]*

and our expression would become:

\[([^'"]*?)\]

Demo

Test

$re = '/\[([^\'"]*?)\]/m';
$str = '$_SESSION[Name][name_2]
$_POST[Name][na-me_2]
$_GET[\'Name\'][na-me_2]
$tab[name_one]
$_POST[Name]["na-me_2"]
$_POST[\'Name\']["na-me_2"]';
$subst = '[\'$1\']';

$result = preg_replace($re, $subst, $str);

echo $result;

Output

$_SESSION['Name']['name_2']
$_POST['Name']['na-me_2']
$_GET['Name']['na-me_2']
$tab['name_one']
$_POST['Name']["na-me_2"]
$_POST['Name']["na-me_2"]


问:
can php limit actions based on ip address
i have 2 links that display notifications on my website and its being abused. is there a way to limit the amount of times a user can click the links based on ip address i dont want to block anyone i just want to reduce the amount of times a person can click this link. essentially limiting the requests that can be made </p>

答:
Definitely, on the pre-set variables (I think $_SERVER array, REMOTE_ADDR) you can see:

The IP address from which the user is viewing the current page.

http://php.net/manual/en/reserved.variables.server.php


问:
How to fix ' missing google-api-python-client'? Using Python, Jupyter Notebook and SpeechRecognition
I'm trying to perform speech recognition on some audio files I have using python 3.x, jupyter notebook and SpeechRecognition library but I get:

```<code>'RequestError: missing google-api-python-client module: ensure that google-api-python-client is set up correctly.'
</code>```

when using recognize_google_cloud even though I already installed it and see 'google-api-python-client when running

```<code>conda list
</code>```

Things run smoothly when using the default google speech API key.

Code being used is as follows:

```<code>import speech_recognition as sr

r = sr.Recognizer()

with open('file_with_keys.json') as f:
GOOGLE_CLOUD_SPEECH_CREDENTIALS = f.read()

test_audio = sr.AudioFile('audio_file.wav')
with test_audio as source:
    audio = r.record(source)

r.recognize_google_cloud(audio, language = 'es-MX',
credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS)
</code>```

Expected result consists of transcription of my current file.

Thanks a lot in advance.

答:
Can you publicly share the notebook?  Did you try this in a console rather than notebook, and what are the results if you do?

Also, when you say

"Things run smoothly when using the default google speech API key."

Can you be more specific as to what that means or how it relates to the problem?  Your not getting an API key error.

For me, I could only get my python code working if I was running in a virtual environment.  Is that happening for your notebook?

See: https://cloud.google.com/python/setup
And: https://anbasile.github.io/programming/2017/06/25/jupyter-venv/

Body:
I'm trying to perform speech recognition on some audio files I have using python 3.x, jupyter notebook and SpeechRecognition library but I get:

'RequestError: missing google-api-python-client module: ensure that google-api-python-client is set up correctly.'

when using recognize_google_cloud even though I already installed it and see 'google-api-python-client when running

conda list

Things run smoothly when using the default google speech API key.

Code being used is as follows:

import speech_recognition as sr

r = sr.Recognizer()

with open('file_with_keys.json') as f:
GOOGLE_CLOUD_SPEECH_CREDENTIALS = f.read()

test_audio = sr.AudioFile('audio_file.wav')
with test_audio as source:
    audio = r.record(source)

r.recognize_google_cloud(audio, language = 'es-MX',
credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS)

Expected result consists of transcription of my current file.

Thanks a lot in advance.


问:
Deserialize Json string to Enum C#
I am writing a test on a custom version of stringEnumConverter. But my test keeps throwing when I deserialize. I searched over stack overflow, but could not find what I did wrong. Following is a sample of what I'm doing:

```<code>namespace ConsoleApp2
{
    [Flags]
    [JsonConverter(typeof(StringEnumConverter))]
    enum TestEnum
    {
        none = 0,
        obj1 = 1,
        obj2 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{none}";
            var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        }
    }
}
</code>```

The exception I get on the deserialize line is Unexpected token StartObject when parsing enum.

I suspect it might be because I am representing the json string wrong, I also tried "{\"none\"}", "{\"TestEnum\":\"none\"}", "{TestEnum:none}", "{none}" and "none".

答:
{none} is not valid JSON, but 'none' is valid!

You should try the following:

```<code>public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var jsonString = "'none'";
        var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        Console.WriteLine(deserializedObject);
    }
}
</code>```

Cheers!

Title: Deserialize Json string to Enum C#

Body:
I am writing a test on a custom version of stringEnumConverter. But my test keeps throwing when I deserialize. I searched over stack overflow, but could not find what I did wrong. Following is a sample of what I'm doing:

namespace ConsoleApp2
{
    [Flags]
    [JsonConverter(typeof(StringEnumConverter))]
    enum TestEnum
    {
        none = 0,
        obj1 = 1,
        obj2 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{none}";
            var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        }
    }
}

The exception I get on the deserialize line is Unexpected token StartObject when parsing enum.

I suspect it might be because I am representing the json string wrong, I also tried "{\"none\"}", "{\"TestEnum\":\"none\"}", "{TestEnum:none}", "{none}" and "none".

Body:
{none} is not valid JSON, but 'none' is valid!

You should try the following:

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var jsonString = "'none'";
        var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        Console.WriteLine(deserializedObject);
    }
}

Cheers!


问:
How to create an AWS codecommit repo using Cloudformation from code in an S3 bucket
Within AWS Cloudformation, I have a template file in YAML in which I am trying to create a new stack that builds a new Codecommit repo with code that is pulled from a zipped up folder in an S3 bucket.

Looking through the official AWS documentation, this seems possible. However, the documentation seems terse and I cannot for the life of me figure out how to do this.

AWS documentation reference - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-s3.html

```<code>Resources:
    CodeRepository:
        Type: AWS::CodeCommit::Repository
        Properties:
            RepositoryName: "repo-name"
            RepositoryDescription: "This is a Description"
            S3:
              Bucket: "S3-bucket-name"
</code>```

The stack does not build, and I get the following rollback message --> 'Property validation failure: [Encountered unsupported properties in {/}: [Bucket]]'

Am I doing something wrong in my YAML, or is this an unsupported feature with Codecommit?

答:
The Properties structure is a bit off and you are missing the required Key property for your S3 config

```<code>
Properties:
    RepositoryName: "repo-name"
    RepositoryDescription: "This is a Description"
    Code
        S3:
            Bucket: "S3-bucket-name"
            Key: "my-initial-code.zip"
</code>```

Body:
Within AWS Cloudformation, I have a template file in YAML in which I am trying to create a new stack that builds a new Codecommit repo with code that is pulled from a zipped up folder in an S3 bucket.

Looking through the official AWS documentation, this seems possible. However, the documentation seems terse and I cannot for the life of me figure out how to do this.

AWS documentation reference - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-s3.html

Resources:
    CodeRepository:
        Type: AWS::CodeCommit::Repository
        Properties:
            RepositoryName: "repo-name"
            RepositoryDescription: "This is a Description"
            S3:
              Bucket: "S3-bucket-name"

The stack does not build, and I get the following rollback message --> 'Property validation failure: [Encountered unsupported properties in {/}: [Bucket]]'

Am I doing something wrong in my YAML, or is this an unsupported feature with Codecommit?

Body:
The Properties structure is a bit off and you are missing the required Key property for your S3 config

Properties:
    RepositoryName: "repo-name"
    RepositoryDescription: "This is a Description"
    Code
        S3:
            Bucket: "S3-bucket-name"
            Key: "my-initial-code.zip"


问:
Trouble Creating Canvas for Emulator
I'm trying to display text on a Lua Canvas in the BizHawk emulator but I keep getting the same error at the line of my 'LuaCanvas.drawText' command.

I haven't found any example scripts for Bizhawk that make use of the canvas

```<code>gui.createcanvas(640, 480);
while true do
    LuaCanvas.drawText(100, 100, message);
    emu.frameadvance();
end
</code>```

The script opens two canvas windows instead of the desired one canvas, and doesn't have the 'message' string that I provided.

Error message reads:
NLua.Exceptions.LuaScriptException: [string "main"]:3: attempt to index global 'LuaCanvas' (a nil value)

答:
I think the code should more look like this.

```<code>drawSpace = gui.createcanvas(192,160)
drawSpace.drawBox(5,5,50,50)
</code>```

or try

```<code>local c = gui.createCanvas(60, 60, 300, 200);
c:onPaint = function(params)
  self:clear(1, 0, 0, 1);
  self:moveTo(10, 10);
  self:lineTo(100, 100);
end
</code>```

Nonetheless, there seems to be a lack of documentation.

Title: Trouble Creating Canvas for Emulator

Body:
I'm trying to display text on a Lua Canvas in the BizHawk emulator but I keep getting the same error at the line of my 'LuaCanvas.drawText' command.

I haven't found any example scripts for Bizhawk that make use of the canvas

gui.createcanvas(640, 480);
while true do
    LuaCanvas.drawText(100, 100, message);
    emu.frameadvance();
end

The script opens two canvas windows instead of the desired one canvas, and doesn't have the 'message' string that I provided.

Error message reads:
NLua.Exceptions.LuaScriptException: [string "main"]:3: attempt to index global 'LuaCanvas' (a nil value)

Body:
I think the code should more look like this.

drawSpace = gui.createcanvas(192,160)
drawSpace.drawBox(5,5,50,50)

or try

local c = gui.createCanvas(60, 60, 300, 200);
c:onPaint = function(params)
  self:clear(1, 0, 0, 1);
  self:moveTo(10, 10);
  self:lineTo(100, 100);
end

Nonetheless, there seems to be a lack of documentation.


问:
Need help interpreting/converting math formula for javascript
I have a math formula that I need to convert to Javascript readable format.

```<code> const result = (100 × w) / (52.2 + (41.9 × e-0.055 × r))
</code>```

I have no problem with most of it. The part that is holding me up is
     e-0.055

I am assuming that it's referring to Euler's number but am unsure how to get it to work.

I tried:

```<code> const result = (100 * w) / (52.2 + (41.9 * Math.E(-0.055 * r)));
</code>```

but that throws an error.

Another form of the same formula written for some server side language is:
     1 RM = {:frac{100* "w" }{52.2+41.9*e^{-0.055* "r" }}:}

but again, the "e^" part eludes me.

答:
Are you looking for the exponentiation operator ** to raise E to the (-0.055 * r) power?

```<code> const result = (100 * w) / (52.2 + (41.9 * Math.E**(-0.055 * r)));
</code>```

also there is Math.pow available if you aren't using es6+

```<code>const result = (100 * w) / (52.2 + (41.9 * Math.pow(Math.E,(-0.055 * r))));
</code>```

and interestingly enough there is also a combined function Math.exp which raise E to x

```<code>const result = (100 * w) / (52.2 + (41.9 * Math.exp(-0.055 * r)));
</code>```

Body:
I have a math formula that I need to convert to Javascript readable format.

 const result = (100 × w) / (52.2 + (41.9 × e-0.055 × r))

I have no problem with most of it. The part that is holding me up is
     e-0.055

I am assuming that it's referring to Euler's number but am unsure how to get it to work.

I tried:

 const result = (100 * w) / (52.2 + (41.9 * Math.E(-0.055 * r)));

but that throws an error.

Another form of the same formula written for some server side language is:
     1 RM = {:frac{100* "w" }{52.2+41.9*e^{-0.055* "r" }}:}

but again, the "e^" part eludes me.

Body:
Are you looking for the exponentiation operator ** to raise E to the (-0.055 * r) power?

 const result = (100 * w) / (52.2 + (41.9 * Math.E**(-0.055 * r)));

also there is Math.pow available if you aren't using es6+

const result = (100 * w) / (52.2 + (41.9 * Math.pow(Math.E,(-0.055 * r))));

and interestingly enough there is also a combined function Math.exp which raise E to x

const result = (100 * w) / (52.2 + (41.9 * Math.exp(-0.055 * r)));


问:
MPMoviePlayerController plays after canceling in 3.1.2
I have encountered a problem with the MPMoviePlayerController in 3.1.2.

If I cancel the player while it is still loading, the player closes.  However, the video starts playing a few moments later in the background.  The only ways to stop it are to play another video or close the app.  This seems to work fine in 3.2+.

Here's what I'm doing:

```<code>- (void)loadMoviePlayer
{
    // Register to receive a notification when the movie has finished playing.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:nil];

    if ([NSClassFromString(@"MPMoviePlayerController") instancesRespondToSelector:@selector(view)])
    {

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
        // running iOS 3.2 or better
        MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:@"http://www.mysite.com/myvideo.m3u8"]];
        [moviePlayer.view setBackgroundColor:[UIColor blackColor]];
        [moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
        //      [moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleNone];
        [self presentMoviePlayerViewControllerAnimated:moviePlayer];
        [moviePlayer.moviePlayer prepareToPlay];
        [moviePlayer.moviePlayer play];
#endif
    }
    else
    {
        MPMoviePlayerController *mMPPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:@"http://www.mysite.com/myvideo.m3u8"]];
        mMPPlayer.scalingMode=MPMovieScalingModeFill;
        mMPPlayer.backgroundColor=[UIColor blackColor];
        [mMPPlayer play];
    }

}

- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];

    // Remove observer
    [[NSNotificationCenter  defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:nil];

    [self dismissModalViewControllerAnimated:YES];
}
</code>```

I added moviePlayBackDidFinish this morning.  It gets called when I hit cancel, but dismissModalViewControllerAnimated doesn't seem to do anything.  I also tried removeFromSuperView, but my player will not respond.

So, how can I make sure the player does not play after hitting "cancel"?

Thanks in advance.

答:
You may have come across an old bug in MPMoviePlayerController. Back in the days, we actually had to play an almost empty (black, silence) M4V after playing proper content to be sure the player does not attempt to continue playback in the background when stopping at certain stages. That bug manifests in audible sound but no picture of the aborted/stopped video.

There are however a few more things worth trying when stopping (assuming your instance of MPMoviePlayerController is called moviePlayer);

set the current playback position to the complete movie duration moviePlayer.currentPlaybackTime = moviePlayer.duration;

send another stop within your notification handler [moviePlayer stop];

Body:
I have encountered a problem with the MPMoviePlayerController in 3.1.2.

If I cancel the player while it is still loading, the player closes.  However, the video starts playing a few moments later in the background.  The only ways to stop it are to play another video or close the app.  This seems to work fine in 3.2+.

Here's what I'm doing:

- (void)loadMoviePlayer
{
    // Register to receive a notification when the movie has finished playing.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:nil];

    if ([NSClassFromString(@"MPMoviePlayerController") instancesRespondToSelector:@selector(view)])
    {

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
        // running iOS 3.2 or better
        MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:@"http://www.mysite.com/myvideo.m3u8"]];
        [moviePlayer.view setBackgroundColor:[UIColor blackColor]];
        [moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
        //      [moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleNone];
        [self presentMoviePlayerViewControllerAnimated:moviePlayer];
        [moviePlayer.moviePlayer prepareToPlay];
        [moviePlayer.moviePlayer play];
#endif
    }
    else
    {
        MPMoviePlayerController *mMPPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:@"http://www.mysite.com/myvideo.m3u8"]];
        mMPPlayer.scalingMode=MPMovieScalingModeFill;
        mMPPlayer.backgroundColor=[UIColor blackColor];
        [mMPPlayer play];
    }

}

- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];

    // Remove observer
    [[NSNotificationCenter  defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:nil];

    [self dismissModalViewControllerAnimated:YES];
}

I added moviePlayBackDidFinish this morning.  It gets called when I hit cancel, but dismissModalViewControllerAnimated doesn't seem to do anything.  I also tried removeFromSuperView, but my player will not respond.

So, how can I make sure the player does not play after hitting "cancel"?

Thanks in advance.


问:
Cannot query table from datalab
I have a dataset with tables set up within Big Query which I can query just fine using the BQ UI, however I am getting an error when attempting to run a standard query from datalab.

I can get the table schema returned when I run

```<code>%%bq tables describe --name "my-project.my_dataset.my_table"
</code>```

and also I can get access to the meta data

```<code>table1=bq.Table("my-project.my_dataset.my_table")
table1.metadata.rows

Result: 637043
</code>```

However when I run

```<code>%%bq query --name testQuery
SELECT * FROM `my-project.my_dataset.my_table`
</code>```

I receive the error

```<code>RequestException: HTTP request failed: Not found: Job my-project:job__SSPF9nCudKqIFZT8N4yvp_SUDb5
</code>```

I have tried using the various different ways of sending the same query as well as sampling but no joy.

Has anyone experienced a similar issue?

答:
Had the same problem and found the solution here:

https://cloud.google.com/bigquery/docs/visualize-jupyter

Try to install this library:

```<code>pip install google-cloud-bigquery[pandas]
</code>```

Call the magic notebook command:

```<code>%load_ext google.cloud.bigquery
</code>```

And then run the query this way:

```<code>%%bigquery
SELECT
    source_year AS year,
    COUNT(is_male) AS birth_count
FROM `bigquery-public-data.samples.natality`
GROUP BY year
ORDER BY year DESC
LIMIT 15
</code>```

Title: Cannot query table from datalab

Body:
I have a dataset with tables set up within Big Query which I can query just fine using the BQ UI, however I am getting an error when attempting to run a standard query from datalab.

I can get the table schema returned when I run

%%bq tables describe --name "my-project.my_dataset.my_table"

and also I can get access to the meta data

table1=bq.Table("my-project.my_dataset.my_table")
table1.metadata.rows

Result: 637043

However when I run

%%bq query --name testQuery
SELECT * FROM `my-project.my_dataset.my_table`

I receive the error

RequestException: HTTP request failed: Not found: Job my-project:job__SSPF9nCudKqIFZT8N4yvp_SUDb5

I have tried using the various different ways of sending the same query as well as sampling but no joy.

Has anyone experienced a similar issue?

Body:
Had the same problem and found the solution here:

https://cloud.google.com/bigquery/docs/visualize-jupyter

Try to install this library:

pip install google-cloud-bigquery[pandas]

Call the magic notebook command:

%load_ext google.cloud.bigquery

And then run the query this way:

%%bigquery
SELECT
    source_year AS year,
    COUNT(is_male) AS birth_count
FROM `bigquery-public-data.samples.natality`
GROUP BY year
ORDER BY year DESC
LIMIT 15