问:
transpose and rename dataframes in a for() loop in r
I have a list of files with the following pattern: sampleid_samplename_counts.csv representing count matrix with cellname in rows and genes in columns.

I'm trying to generate count matrix from these files to load in the Seurat package that need cellnames in columns and gene in rows.

I succeed in obtaining the matrix with the following where x is a vectors of all the .csv filenames (I needed to create a new name for the object as I couldn't reassign "i" within the loop):

```<code>for (i in x) {
  assign(paste0(i, ".counts"), t(read.table(i, sep = ",")))
  }
</code>```

But the obtained matrix does not have colnames (it's replaced with V1, V2, V3...)
Row 1 of each matrix contain the cellnames.

The following is creating the correct colnames:

```<code>colnames(file.counts) <- file.counts[1,]
file.counts <- file.counts[-1,]
</code>```

But this does not work in a for() loop. How can I implement this in the initial or in another loop?

EDIT:

Here is what the original .csv file looks like after a simple read.table:

```<code>structure(list(V1 = c(NA, 121270371765165, 121270372580596, 121270373898541,
121270374395228, 121270374676403, 121270375926581, 121270376000796,
121270376290589, 121270378289958, 121270378621156, 121347513957787,
121347516024694, 121347517659934, 121347518125797, 121347519671644,
121347519760734, 121347519921075, 121347520489203, 121896195804531
), V2 = c("DPM1", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", ""), V3 = c("SCYL3", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""
), V4 = c("FGR", "", "", "", "", "", "", "", "", "1.0", "", "",
"", "", "", "", "", "", "", ""), V5 = c("CFH", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
    V6 = c("FUCA2", "", "", "", "", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", ""), V7 = c("GCLC", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    ""), V8 = c("NFYA", "", "", "", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", ""), V9 = c("NIPAL3", "",
    "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    "", "", ""), V10 = c("LAS1L", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", "")), row.names = c(NA,
20L), class = "data.frame")
</code>```

And this is what looks like after the transpose t()

```<code>structure(c(NA, "DPM1", "SCYL3", "FGR", "CFH", "FUCA2", "GCLC",
"NFYA", "NIPAL3", "LAS1L", "ENPP4", "ANKIB1", "KRIT1", "RAD52",
"BAD", "LAP3", "CD99", "MAD1L1", "LASP1", "SNX11", "1.212704e+14",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "1.212704e+14", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "1.0", "", "", "", "1.212704e+14", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "1.212704e+14", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "1.212704e+14", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "1.0",
"", "1.212704e+14", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "1.212704e+14", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "1.212704e+14",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "1.212704e+14", "", "", "1.0", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", ""), .Dim = c(20L, 10L
), .Dimnames = list(c("V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16",
"V17", "V18", "V19", "V20"), NULL))
</code>```

答:
Perhaps this is helping...

```<code>library( data.table )

#build list of csv.gz files (I only kept two files in the dir)
files.to.read <- list.files( "./temp/GSE114725_RAW/", pattern = "\\.csv.gz$", full.names = TRUE )
</code>```

```<code>#build a list of read data
L <- lapply( files.to.read, data.table::fread )

#transpose each list element
L.transposed <- lapply( L, data.table::transpose, keep.names = "gene", make.names = "V1" )
#set list names based on filenames
names(L.transposed) <- basename( files.to.read )

#write list elements to individual data.tables
for(i in 1:length(L.transposed)) assign(names(L.transposed)[i], L.transposed[[i]])
</code>```

Body:
I have a list of files with the following pattern: sampleid_samplename_counts.csv representing count matrix with cellname in rows and genes in columns.

I'm trying to generate count matrix from these files to load in the Seurat package that need cellnames in columns and gene in rows.

I succeed in obtaining the matrix with the following where x is a vectors of all the .csv filenames (I needed to create a new name for the object as I couldn't reassign "i" within the loop):

for (i in x) {
  assign(paste0(i, ".counts"), t(read.table(i, sep = ",")))
  }

But the obtained matrix does not have colnames (it's replaced with V1, V2, V3...)
Row 1 of each matrix contain the cellnames.

The following is creating the correct colnames:

colnames(file.counts) <- file.counts[1,]
file.counts <- file.counts[-1,]

But this does not work in a for() loop. How can I implement this in the initial or in another loop?

EDIT:

Here is what the original .csv file looks like after a simple read.table:

structure(list(V1 = c(NA, 121270371765165, 121270372580596, 121270373898541,
121270374395228, 121270374676403, 121270375926581, 121270376000796,
121270376290589, 121270378289958, 121270378621156, 121347513957787,
121347516024694, 121347517659934, 121347518125797, 121347519671644,
121347519760734, 121347519921075, 121347520489203, 121896195804531
), V2 = c("DPM1", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", ""), V3 = c("SCYL3", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""
), V4 = c("FGR", "", "", "", "", "", "", "", "", "1.0", "", "",
"", "", "", "", "", "", "", ""), V5 = c("CFH", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
    V6 = c("FUCA2", "", "", "", "", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", ""), V7 = c("GCLC", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    ""), V8 = c("NFYA", "", "", "", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", ""), V9 = c("NIPAL3", "",
    "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    "", "", ""), V10 = c("LAS1L", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", "")), row.names = c(NA,
20L), class = "data.frame")

And this is what looks like after the transpose t()

structure(c(NA, "DPM1", "SCYL3", "FGR", "CFH", "FUCA2", "GCLC",
"NFYA", "NIPAL3", "LAS1L", "ENPP4", "ANKIB1", "KRIT1", "RAD52",
"BAD", "LAP3", "CD99", "MAD1L1", "LASP1", "SNX11", "1.212704e+14",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "1.212704e+14", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "1.0", "", "", "", "1.212704e+14", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "1.212704e+14", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "1.212704e+14", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "1.0",
"", "1.212704e+14", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "1.212704e+14", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "1.212704e+14",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "1.212704e+14", "", "", "1.0", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", ""), .Dim = c(20L, 10L
), .Dimnames = list(c("V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16",
"V17", "V18", "V19", "V20"), NULL))

Body:
Perhaps this is helping...

library( data.table )

#build list of csv.gz files (I only kept two files in the dir)
files.to.read <- list.files( "./temp/GSE114725_RAW/", pattern = "\\.csv.gz$", full.names = TRUE )

#build a list of read data
L <- lapply( files.to.read, data.table::fread )

#transpose each list element
L.transposed <- lapply( L, data.table::transpose, keep.names = "gene", make.names = "V1" )
#set list names based on filenames
names(L.transposed) <- basename( files.to.read )

#write list elements to individual data.tables
for(i in 1:length(L.transposed)) assign(names(L.transposed)[i], L.transposed[[i]])


来源: stackexchange

问:
BigQuery query result having variable number of columns?
I have a table in this form:

```<code>TIME  TYPE COUNT
00:01 DOG  4
00:04 CAT  5
00:07 DOG  2
00:30 BIRD 1
01:04 DOG  2
01:30 BIRD 3
01:40 DOG  1
02:01 BIRD 4
</code>```

I do a query like this that joins the sum of COUNT of each TYPE based on hour:

```<code>select HOUR(`TIME`), `TYPE`, sum(`COUNT`)
from `table`
where `TYPE` = 'DOG'
group by HOUR(`TIME`)
FULL JOIN
...(same query but... where `TYPE` = 'CAT')
ON hour...
FULL JOIN
...(same query again, but where `TYPE` = 'BIRD')
etc.
</code>```

The purpose being to get a result like this:

```<code>HOUR DOG CAT BIRD
00   6   5   1
01   5   0   3
02   0   0   4
</code>```

My question is: How can you do this without joins?
I want a query to work for any distinct TYPE values that happen to the be in the table and are not known upfront, so the table would grow in columns foreach distinct TYPE.

Is this something that could be done with BigQuery script?

答:
I haven't tried this, but one way I think will work is to interate over the distinct values and generate a query as per Gordon Linoff's answer:</p>

```<code># Get array of distinct types
DECLARE myTypes ARRAY<STRING>;
SET myTypes = ( select distinct(`TYPE`) form `table`);

# get size of array
DECLARE x INT64;
SET x = ARRAY_LENGTH(myTypes);

# start making query
DECLARE myQuery STRING;
SET myQuery = "select extract(hour from time),";

LOOP

    x = x-1;

    # Add column for each type
    SET myQuery = CONCAT(myQuery,format("sum(case when type = '%s' then count else 0 end) as %s,",myTypes[OFFSET(x)]);

    IF x == 0 THEN LEAVE;
    END IF;
END LOOP;

#finish up query
SET myQuery = CONCAT(myQuery,"from table group by extract(hour from time)")

EXECUTE IMMEDIATE myQuery;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table in this form:

TIME  TYPE COUNT
00:01 DOG  4
00:04 CAT  5
00:07 DOG  2
00:30 BIRD 1
01:04 DOG  2
01:30 BIRD 3
01:40 DOG  1
02:01 BIRD 4

I do a query like this that joins the sum of COUNT of each TYPE based on hour:

select HOUR(`TIME`), `TYPE`, sum(`COUNT`)
from `table`
where `TYPE` = 'DOG'
group by HOUR(`TIME`)
FULL JOIN
...(same query but... where `TYPE` = 'CAT')
ON hour...
FULL JOIN
...(same query again, but where `TYPE` = 'BIRD')
etc.

The purpose being to get a result like this:

HOUR DOG CAT BIRD
00   6   5   1
01   5   0   3
02   0   0   4

My question is: How can you do this without joins?
I want a query to work for any distinct TYPE values that happen to the be in the table and are not known upfront, so the table would grow in columns foreach distinct TYPE.

Is this something that could be done with BigQuery script?

Body:
I haven't tried this, but one way I think will work is to interate over the distinct values and generate a query as per Gordon Linoff's answer:

# Get array of distinct types
DECLARE myTypes ARRAY<STRING>;
SET myTypes = ( select distinct(`TYPE`) form `table`);

# get size of array
DECLARE x INT64;
SET x = ARRAY_LENGTH(myTypes);

# start making query
DECLARE myQuery STRING;
SET myQuery = "select extract(hour from time),";

LOOP

    x = x-1;

    # Add column for each type
    SET myQuery = CONCAT(myQuery,format("sum(case when type = '%s' then count else 0 end) as %s,",myTypes[OFFSET(x)]);

    IF x == 0 THEN LEAVE;
    END IF;
END LOOP;

#finish up query
SET myQuery = CONCAT(myQuery,"from table group by extract(hour from time)")

EXECUTE IMMEDIATE myQuery;


问:
iOS - Calendar standalone properies aren't capitalized
I need to set some headers with weekdays and month symbols, for that I'm using the calendar's properties weekdaySymbols and monthSymbols. However, I wand them to be capitalized, recently I notice the calendar also has the properties standaloneWeekdaySymbols and standaloneMonthSymbols, which are the symbols to use on headers, however, they don't seem to work as I expected:

```<code>var calendar = Calendar.init(identifier: .gregorian)
calendar.locale = Locale.init(identifier: "nl-NL")

print(calendar.weekdaySymbols)
/// OUTPUT: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]

print(calendar.standaloneWeekdaySymbols)
/// OUTPUT: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]

print(calendar.monthSymbols)
/// OUTPUT: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"]

print(calendar.standaloneMonthSymbols)
/// OUTPUT: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"]

</code>```

Shouldn't standalone properties be capitalized? Am I missing something here?

EDITED FOR pawello2222's answer:

Then I have to point out that there is some inconsistencies with Apple's date APIs, because using DateFormatter with standalone context does yield capitalized results:

```<code>let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("EEEE")
dateFormatter.formattingContext = .standalone
dateFormatter.locale = Locale.init(identifier: "nl_NL")

let date = Date()
print(dateFormatter.string(from: date))
/// OUTPUT: Dinsdag
</code>```

I would have expected that both DateFormatter and Calendar would yield the same standalone formats for a specific locale.

That makes me think that, either I'm doing something wrong, or the standalone properties of the calendar are not working well.

答:
They are capitalised depending on the locale (different regions may have different conventions):

```<code>var calendar = Calendar.current
calendar.locale = Locale(identifier: "en-EN")

print(calendar.standaloneWeekdaySymbols)
//prints ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
</code>```

Looks like in nl-NL they are all lowercase.

You can always use capitalized:

```<code>print("zondag".capitalized) // prints "Zondag"
</code>```

Body:
I need to set some headers with weekdays and month symbols, for that I'm using the calendar's properties weekdaySymbols and monthSymbols. However, I wand them to be capitalized, recently I notice the calendar also has the properties standaloneWeekdaySymbols and standaloneMonthSymbols, which are the symbols to use on headers, however, they don't seem to work as I expected:

var calendar = Calendar.init(identifier: .gregorian)
calendar.locale = Locale.init(identifier: "nl-NL")

print(calendar.weekdaySymbols)
/// OUTPUT: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]

print(calendar.standaloneWeekdaySymbols)
/// OUTPUT: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]

print(calendar.monthSymbols)
/// OUTPUT: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"]

print(calendar.standaloneMonthSymbols)
/// OUTPUT: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"]

Shouldn't standalone properties be capitalized? Am I missing something here?

EDITED FOR pawello2222's answer:

Then I have to point out that there is some inconsistencies with Apple's date APIs, because using DateFormatter with standalone context does yield capitalized results:

let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("EEEE")
dateFormatter.formattingContext = .standalone
dateFormatter.locale = Locale.init(identifier: "nl_NL")

let date = Date()
print(dateFormatter.string(from: date))
/// OUTPUT: Dinsdag

I would have expected that both DateFormatter and Calendar would yield the same standalone formats for a specific locale.

That makes me think that, either I'm doing something wrong, or the standalone properties of the calendar are not working well.

Body:
They are capitalised depending on the locale (different regions may have different conventions):

var calendar = Calendar.current
calendar.locale = Locale(identifier: "en-EN")

print(calendar.standaloneWeekdaySymbols)
//prints ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

Looks like in nl-NL they are all lowercase.

You can always use capitalized:

print("zondag".capitalized) // prints "Zondag"


问:
Python function returns only the first value instead of a dataframe
I have build a function where I append the returns of 5 portfolios to a dataframe which I want to return to a variable . When I run the commands within the function row by row(kind of debugging) I end upwith the variable 'folioReturn'(which is the one I want my script to return) having the right amount of values (e.x 5). But if I call the function, only the first value of the dataframe is returned. Does anyone know how I can get the whole dataframe ?</p>

```<code>
def portfolioReturns (securities, quintilesNo, perReturns):
    '''
    this function receives
    1)securities: array with the security names and values ** for the purpose of our work the names
    should already be sorted
    2)quintilesNo: the number of portfolios we want to create
    3)perReturns: an array with the returns that will be used for performance measuremnt

    It returns an array with the returns for each portfolio

    '''

    # we calculate the number of securities per portfolio
    stdFolioSize = np.divmod(securities.size, quintilesNo)[0] # we take the floor division
    folioReturn = [] # pd.DataFrame()
    # we create portfolios with equal number of securities except of the last one where we use all the remaining securities
    for k in range(0, quintilesNo, 1): # in folio list we store the name of the securities we must include in each portfolio
        if k < (quintilesNo - 1):
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : (k + 1) * stdFolioSize]

        else: # the last portfolio will also include the remainder securities
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : securities.size]

        # now that we have the list of the securities to be included in the folio, we use the table
        # with the periodical returns to check the performance. The portfolio we construct is equally weighted

        # first we drop one index(the first index of the country) and then we store all the periodical returns in one-array
        perRetFinalTable = pd.DataFrame(perReturns.reset_index(level = 0, drop = True)).T

        # using the list of the bonds we want to include in our portfolio we pick the bond returns and
        # we store them in one array. Then we calculate the folio return
        folio = perRetFinalTable[folioList]
        folioReturn = np.append(folioReturn, folio.sum(axis = 1) * (1 / folio.size))
        folioReturn = pd.DataFrame(folioReturn).T
        # folioReturn = pd.Series(folioReturn).T

        return (folioReturn)

</code>```

答:
return statement must be after the for loop if you want whole list in your case during the first loop only the value is returned.
just remove the return from for loop it will work fine.</p>

```<code>def portfolioReturns (securities, quintilesNo, perReturns):
    '''
    this function receives
    1)securities: array with the security names and values ** for the purpose of our work the names
    should already be sorted
    2)quintilesNo: the number of portfolios we want to create
    3)perReturns: an array with the returns that will be used for performance measuremnt

    It returns an array with the returns for each portfolio

    '''

    # we calculate the number of securities per portfolio
    stdFolioSize = np.divmod(securities.size, quintilesNo)[0] # we take the floor division
    folioReturn = [] # pd.DataFrame()
    # we create portfolios with equal number of securities except of the last one where we use all the remaining securities
    for k in range(0, quintilesNo, 1): # in folio list we store the name of the securities we must include in each portfolio
        if k < (quintilesNo - 1):
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : (k + 1) * stdFolioSize]

        else: # the last portfolio will also include the remainder securities
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : securities.size]

        # now that we have the list of the securities to be included in the folio, we use the table
        # with the periodical returns to check the performance. The portfolio we construct is equally weighted

        # first we drop one index(the first index of the country) and then we store all the periodical returns in one-array
        perRetFinalTable = pd.DataFrame(perReturns.reset_index(level = 0, drop = True)).T

        # using the list of the bonds we want to include in our portfolio we pick the bond returns and
        # we store them in one array. Then we calculate the folio return
        folio = perRetFinalTable[folioList]
        folioReturn = np.append(folioReturn, folio.sum(axis = 1) * (1 / folio.size))
        folioReturn = pd.DataFrame(folioReturn).T
        # folioReturn = pd.Series(folioReturn).T

    return (folioReturn)
</code>```

Body:
I have build a function where I append the returns of 5 portfolios to a dataframe which I want to return to a variable . When I run the commands within the function row by row(kind of debugging) I end upwith the variable 'folioReturn'(which is the one I want my script to return) having the right amount of values (e.x 5). But if I call the function, only the first value of the dataframe is returned. Does anyone know how I can get the whole dataframe ?

def portfolioReturns (securities, quintilesNo, perReturns):
    '''
    this function receives
    1)securities: array with the security names and values ** for the purpose of our work the names
    should already be sorted
    2)quintilesNo: the number of portfolios we want to create
    3)perReturns: an array with the returns that will be used for performance measuremnt

    It returns an array with the returns for each portfolio

    '''

    # we calculate the number of securities per portfolio
    stdFolioSize = np.divmod(securities.size, quintilesNo)[0] # we take the floor division
    folioReturn = [] # pd.DataFrame()
    # we create portfolios with equal number of securities except of the last one where we use all the remaining securities
    for k in range(0, quintilesNo, 1): # in folio list we store the name of the securities we must include in each portfolio
        if k < (quintilesNo - 1):
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : (k + 1) * stdFolioSize]

        else: # the last portfolio will also include the remainder securities
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : securities.size]

        # now that we have the list of the securities to be included in the folio, we use the table
        # with the periodical returns to check the performance. The portfolio we construct is equally weighted

        # first we drop one index(the first index of the country) and then we store all the periodical returns in one-array
        perRetFinalTable = pd.DataFrame(perReturns.reset_index(level = 0, drop = True)).T

        # using the list of the bonds we want to include in our portfolio we pick the bond returns and
        # we store them in one array. Then we calculate the folio return
        folio = perRetFinalTable[folioList]
        folioReturn = np.append(folioReturn, folio.sum(axis = 1) * (1 / folio.size))
        folioReturn = pd.DataFrame(folioReturn).T
        # folioReturn = pd.Series(folioReturn).T

        return (folioReturn)

Body:
return statement must be after the for loop if you want whole list in your case during the first loop only the value is returned.
just remove the return from for loop it will work fine.

def portfolioReturns (securities, quintilesNo, perReturns):
    '''
    this function receives
    1)securities: array with the security names and values ** for the purpose of our work the names
    should already be sorted
    2)quintilesNo: the number of portfolios we want to create
    3)perReturns: an array with the returns that will be used for performance measuremnt

    It returns an array with the returns for each portfolio

    '''

    # we calculate the number of securities per portfolio
    stdFolioSize = np.divmod(securities.size, quintilesNo)[0] # we take the floor division
    folioReturn = [] # pd.DataFrame()
    # we create portfolios with equal number of securities except of the last one where we use all the remaining securities
    for k in range(0, quintilesNo, 1): # in folio list we store the name of the securities we must include in each portfolio
        if k < (quintilesNo - 1):
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : (k + 1) * stdFolioSize]

        else: # the last portfolio will also include the remainder securities
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : securities.size]

        # now that we have the list of the securities to be included in the folio, we use the table
        # with the periodical returns to check the performance. The portfolio we construct is equally weighted

        # first we drop one index(the first index of the country) and then we store all the periodical returns in one-array
        perRetFinalTable = pd.DataFrame(perReturns.reset_index(level = 0, drop = True)).T

        # using the list of the bonds we want to include in our portfolio we pick the bond returns and
        # we store them in one array. Then we calculate the folio return
        folio = perRetFinalTable[folioList]
        folioReturn = np.append(folioReturn, folio.sum(axis = 1) * (1 / folio.size))
        folioReturn = pd.DataFrame(folioReturn).T
        # folioReturn = pd.Series(folioReturn).T

    return (folioReturn)


问:
Getting the average number of times a number appears between other numbers
In my cells I have three possible different values, 1 ,0 or ND. I want to get the average number of times 0 appears between the 1s.
But I cannot seem to get it, I have been playing around with =AVERAGE(COUNTIF(A60:C60,  0)). It seems simple but I cannot figure it out.
So I want the average number of times that 0 appears between 1s in the whole row.

imagine each cell is a day. 1s represent fail and 0 represent pass. If the cell has failed that day it is fixed that night. what i want to find out is when i fix a failed cell what is the average amount of days pass before that cell fails again

答:
Count the number of "0"s per line with =COUNTIF(A60:C60,0) and in a new cell the number of "1"s per line using =COUNTIF(A60:C60,1).

As second step, divide the value obtained with the 1st formula through the value obtained with the 2nd formula. This should give you the average number of 0s in relation to the 1s. Hope that helps.


问:
Generate multiple different subplots of multiple lists
I want to plot simple linear plots of my raw data, consisting of mathematical functions on the first column. On the first row I want to plot the base functions, consisting of linear plots of different sine functions. On each subsequent row I want to plot streamplots, consisting of the projection of each of these functions on each base function, so in the end I basically have a 12x6 matrix of subplots.
I'd also like to add titles to each subplots.

The problem I have that the streamplots and linear plots come from different data and I want to solve it with for loops.

I hope this isn't too confusing.

I got this so far:

```<code>functions = [c_f, l_f, pa_f, po_f,n_, log_f, sin, series_vl12, series_apr12, series_mlr202, ex_pn]

base_func = [sin1, sin2, sin3, sin4, sin5]

U = []
V = []
for i in sums_phi:
    U.append(r * np.cos(i))
    V.append(r * np.sin(i))

Y, X = np.mgrid[:101:1,:101:1]

plt.figure(figsize=(15,40))

for x, (i, j) in enumerate(zip(U, V)):
    plt.subplot(11, 5, x+1)
    #function(a, b)
    plt.streamplot(X,Y,i,j, density = 1 )

plt.show()

</code>```

Which gives me the streamplots without the linear subplots of my raw data.

答:
You can add one more line in your definition of the subplots to split your problem in two. First plot your streamplots and then plot your linear plots.

Here in made a small piece of code that you can adapt in your case:

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)

fig, axs = plt.subplots(3, 3)
axs = axs.ravel()

for i in range(6):
    axs[i].plot(x, x**0.5)
</code>```

Gives me the first 6 subplots:

```<code>for i in range(3):
    axs[i+6].plot(x, x**2, c='r')
</code>```

Then I can plot an other function in the last 3 subplots:

Hope it helps for your problem.

Body:
I want to plot simple linear plots of my raw data, consisting of mathematical functions on the first column. On the first row I want to plot the base functions, consisting of linear plots of different sine functions. On each subsequent row I want to plot streamplots, consisting of the projection of each of these functions on each base function, so in the end I basically have a 12x6 matrix of subplots.
I'd also like to add titles to each subplots.

The problem I have that the streamplots and linear plots come from different data and I want to solve it with for loops.

I hope this isn't too confusing.

I got this so far:

functions = [c_f, l_f, pa_f, po_f,n_, log_f, sin, series_vl12, series_apr12, series_mlr202, ex_pn]

base_func = [sin1, sin2, sin3, sin4, sin5]

U = []
V = []
for i in sums_phi:
    U.append(r * np.cos(i))
    V.append(r * np.sin(i))

Y, X = np.mgrid[:101:1,:101:1]

plt.figure(figsize=(15,40))

for x, (i, j) in enumerate(zip(U, V)):
    plt.subplot(11, 5, x+1)
    #function(a, b)
    plt.streamplot(X,Y,i,j, density = 1 )

plt.show()

Which gives me the streamplots without the linear subplots of my raw data.

Body:
You can add one more line in your definition of the subplots to split your problem in two. First plot your streamplots and then plot your linear plots.

Here in made a small piece of code that you can adapt in your case:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)

fig, axs = plt.subplots(3, 3)
axs = axs.ravel()

for i in range(6):
    axs[i].plot(x, x**0.5)

Gives me the first 6 subplots:

for i in range(3):
    axs[i+6].plot(x, x**2, c='r')

Then I can plot an other function in the last 3 subplots:

Hope it helps for your problem.


问:
Sorting algorithms for data of known statistical distribution?
It just occurred to me, if you know something about the distribution (in the statistical sense) of the data to sort, the performance of a sorting algorithm might benefit if you take that information into account.

So my question is, are there any sorting algorithms that take into account that kind of information? How good are they?

An example to clarify: if you know the distribution of your data to be Gaussian, you could estimate mean and average on the fly as you process the data. This would give you an estimate of the final position of each number, which you could use to place them close to their final position.

I'm pretty surprised the answer isn't a wiki link to a thourough page discussing this issue. Isn't this a very common case (the Gaussian case, for example)?

I'm adding a bounty to this question, because I'm looking for definite answers with sources, not speculation. Something like "in the case of gaussian distributed data, XYZ algorithm is the fastest on average, as was proved by Smith et al. [1]". However any additional information is welcome.

答:
Bucket sort would give you a linear time sorting algorithm, as long as you can compute the CDF of each point in O(1) time.

The algorithm, which you can also look up elsewhere, is as follows:

```<code>a = array(0, n - 1, [])          // create an empty list for each bucket
for x in input:
  a[floor(n * cdf(x))].append(x) // O(1) time for each x
input.clear()
for i in {0,...,n - 1}:
  // this sorting step costs O(|a[i]|^2) time for each bucket
  // but most buckets are small and the cost is O(1) per bucket in expectation
  insertion_sort(a[i])
  input.concatenate(a[i])
</code>```

The running time is O(n) in expectation because in expectation there are O(n) pairs (x, y) such that x and y fall in the same bucket, and the running time of insertion sort is precisely O(n + # pairs in the same bucket). The analysis is similar to that of FKS static perfect hashing.

EDIT: If you don't know the distribution, but you know what family it's from, you can just estimate the distribution in O(n), in the Gaussian case by computing the mean and variance, and then use the same algorithm (incidentally, computing the cdf in this case is nontrivial).

Body:
Bucket sort would give you a linear time sorting algorithm, as long as you can compute the CDF of each point in O(1) time.

The algorithm, which you can also look up elsewhere, is as follows:

a = array(0, n - 1, [])          // create an empty list for each bucket
for x in input:
  a[floor(n * cdf(x))].append(x) // O(1) time for each x
input.clear()
for i in {0,...,n - 1}:
  // this sorting step costs O(|a[i]|^2) time for each bucket
  // but most buckets are small and the cost is O(1) per bucket in expectation
  insertion_sort(a[i])
  input.concatenate(a[i])

The running time is O(n) in expectation because in expectation there are O(n) pairs (x, y) such that x and y fall in the same bucket, and the running time of insertion sort is precisely O(n + # pairs in the same bucket). The analysis is similar to that of FKS static perfect hashing.

EDIT: If you don't know the distribution, but you know what family it's from, you can just estimate the distribution in O(n), in the Gaussian case by computing the mean and variance, and then use the same algorithm (incidentally, computing the cdf in this case is nontrivial).

ContentLicense: CC BY-SA 3.0


答:
You're basically exiting the function too early.

Here are two examples to make it simpler to follow along:

```<code>def test():
    lst = []
    for num in range(10):
        lst = num
        return lst

def test2():
    lst = []
    for num in range(10):
        lst.append(num)
    return lst

print(test()) # Output: 0
print(test2()) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

In test we create a list-variable called lst, then inside of a for-loop, we overwrite lst with the current variable num and then immediately issue a return statement, which only returns 0 because it's the first entry in the for-loop.

In test2 we do the same thing in the start of the loop, however, instead of overwriting lst we instead use the method list.append() which adds the value of num to the already created list.

After we're then done with the whole for-loop, we then use the return statement to give back the variable lst which now contains all the values from 0 to 9.

EDIT: It seems I failed to address the actual problem in your code. There are two major errors:

You're exiting your for-loop using the return statement because it's inside of the for-loop. Fix the indentation, and that should be resolved.

Inside of your for-loop, you're overwriting folioReturn instead of appending the values calculated inside of the for-loop to it. Replace the variable folioReturn inside of the for-loop, and then after you've created the DataFrame, append that value to folioReturn.

Title: Python function returns only the first value instead of a dataframe

Body:
You're basically exiting the function too early.

Here are two examples to make it simpler to follow along:

def test():
    lst = []
    for num in range(10):
        lst = num
        return lst

def test2():
    lst = []
    for num in range(10):
        lst.append(num)
    return lst

print(test()) # Output: 0
print(test2()) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In test we create a list-variable called lst, then inside of a for-loop, we overwrite lst with the current variable num and then immediately issue a return statement, which only returns 0 because it's the first entry in the for-loop.

In test2 we do the same thing in the start of the loop, however, instead of overwriting lst we instead use the method list.append() which adds the value of num to the already created list.

After we're then done with the whole for-loop, we then use the return statement to give back the variable lst which now contains all the values from 0 to 9.

EDIT: It seems I failed to address the actual problem in your code. There are two major errors:

You're exiting your for-loop using the return statement because it's inside of the for-loop. Fix the indentation, and that should be resolved.

Inside of your for-loop, you're overwriting folioReturn instead of appending the values calculated inside of the for-loop to it. Replace the variable folioReturn inside of the for-loop, and then after you've created the DataFrame, append that value to folioReturn.


问:
how to update an entity with spring data jpa
I have an entity and a Junit, I want to test that update method is working fine, but when I invoke save method from CrudRepository I get a new entry in my table instead of the updated entity.

This is my entity:

```<code>@Entity(name = "PERSON")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "PERSON_ID")
    private Integer id;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;
//getters and setters
}
</code>```

This is my service class:

```<code>@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person updatePerson(Person oldPerson) throws Exception {

        return personRepository.save(oldPerson);
    }
}
</code>```

This is my repository

```<code>public interface PersonRepository extends CrudRepository<Person, String> {
}
</code>```

This is my test:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAConfigurationTest.class })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional
public class UpdatePersonServiceIntegrationTest {
        @Autowired
    PersonService personService;

        @Before
    public void setUp() throws Exception {
        Person person = new Person(1);
        person.setFirstName("Nicolas");
        person.setLastName("Spessot");

        personService.createPerson(person); //This invokes save
    }

        @Test
    public void updatingPerson() throws Exception{
        Person person = new Person(1);
        person.setFirstName("Juan");
        person.setLastName("Riquelme");

        personService.updatePerson(person);

        Person retrieved = personService.retrievePerson(1); //This invokes findOne

        assertEquals(1, person.getId());
        assertEquals("Juan", person.getFirstName());
        assertEquals("Riquelme", person.getLastName());
    }
}
</code>```

Thanks in advance

答:
One doesn't have to do any complex operations for this.
In your service class you can do something like this.

```<code> @Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person updatePerson(Person oldPerson) throws Exception {

      oldPerson.setId(oldPerson.getId()) ; // pass the associated id for which you want to update and set that id to the same person [ basically setting the same id to the oldPerson ] this way it will not create new entry because here we are not making new ID ]

 //oldPerson.set others [ what is to be updated ]

        return personRepository.save(oldPerson); // now save [old person with updated content but same id as it was before ]
    }
}
</code>```

This solves the problem of creating new entry to the database and updates the same content with Id associate with that person.

Body:
I have an entity and a Junit, I want to test that update method is working fine, but when I invoke save method from CrudRepository I get a new entry in my table instead of the updated entity.

This is my entity:

@Entity(name = "PERSON")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "PERSON_ID")
    private Integer id;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;
//getters and setters
}

This is my service class:

@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person updatePerson(Person oldPerson) throws Exception {

        return personRepository.save(oldPerson);
    }
}

This is my repository

public interface PersonRepository extends CrudRepository<Person, String> {
}

This is my test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAConfigurationTest.class })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional
public class UpdatePersonServiceIntegrationTest {
        @Autowired
    PersonService personService;

        @Before
    public void setUp() throws Exception {
        Person person = new Person(1);
        person.setFirstName("Nicolas");
        person.setLastName("Spessot");

        personService.createPerson(person); //This invokes save
    }

        @Test
    public void updatingPerson() throws Exception{
        Person person = new Person(1);
        person.setFirstName("Juan");
        person.setLastName("Riquelme");

        personService.updatePerson(person);

        Person retrieved = personService.retrievePerson(1); //This invokes findOne

        assertEquals(1, person.getId());
        assertEquals("Juan", person.getFirstName());
        assertEquals("Riquelme", person.getLastName());
    }
}

Thanks in advance

Body:
One doesn't have to do any complex operations for this.
In your service class you can do something like this.

 @Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person updatePerson(Person oldPerson) throws Exception {

      oldPerson.setId(oldPerson.getId()) ; // pass the associated id for which you want to update and set that id to the same person [ basically setting the same id to the oldPerson ] this way it will not create new entry because here we are not making new ID ]

 //oldPerson.set others [ what is to be updated ]

        return personRepository.save(oldPerson); // now save [old person with updated content but same id as it was before ]
    }
}

This solves the problem of creating new entry to the database and updates the same content with Id associate with that person.


问:
Pyqt5 Python3 QPushButton default StrongFocus color or tab selected color
I am trying to figure out a way to change the color of a QPushButton in PyQt5 using Python3.

I can set the background color and the hover color, but the programs keeps the focus color or the

strongfocus color as a default one. Cannot find anything about it, I load my qss file StyleSheet in my

main.py.

like

```<code>QPushButton{
    background-color: #9de650;       #works fine
}

QPushButton:hover{
    background-color: green;         #works fine
}

QPushButton:focus {
    background-color: red;           #doesnt work if the focus color is the color of the button you can
    }                                # change using tab to navigate among a list of buttons

QPushButton:strong:focus {           #doenst work
    background-color: red;
    }

QPushButton:pressed {                #doesnt work get the tab color
    background-color: green;
    }
</code>```

I cant understand why QPushButton:pressed doesnt work. I am at the beginning and no connect or clicked functions on the buttons on my script. I am using Designer, and the color I get on my QPushButton is the same one I get in the designer preview.

THe same behaviour if I save the qss code directly into ui file in designer.

While tabbing between my list of button I can see them assuming the red color for a very short time

before turning blue, red is my focus choosen color.

any hint ?

答:
musicmante qnswered my question:

As I thought. Breeze overrides some colors and behaviors if the css definition of the widget is not complete; what's strange is that you say button:pressed doesn't work, but it does in my tests. In any way, Fusion is the style that usually better handles stylesheets, if it's not a problem to use that, you can just set the application style by using app.setStyle(QtWidgets.QStyleFactory.create('Fusion')).

Body:
I am trying to figure out a way to change the color of a QPushButton in PyQt5 using Python3.

I can set the background color and the hover color, but the programs keeps the focus color or the

strongfocus color as a default one. Cannot find anything about it, I load my qss file StyleSheet in my

main.py.

like

QPushButton{
    background-color: #9de650;       #works fine
}

QPushButton:hover{
    background-color: green;         #works fine
}

QPushButton:focus {
    background-color: red;           #doesnt work if the focus color is the color of the button you can
    }                                # change using tab to navigate among a list of buttons

QPushButton:strong:focus {           #doenst work
    background-color: red;
    }

QPushButton:pressed {                #doesnt work get the tab color
    background-color: green;
    }

I cant understand why QPushButton:pressed doesnt work. I am at the beginning and no connect or clicked functions on the buttons on my script. I am using Designer, and the color I get on my QPushButton is the same one I get in the designer preview.

THe same behaviour if I save the qss code directly into ui file in designer.

While tabbing between my list of button I can see them assuming the red color for a very short time

before turning blue, red is my focus choosen color.

any hint ?


问:
How to access the files in Azure NetApp?
I am wondering if the Azure Storage explorer can be used to access the files in Azure NetApp. If not, what is the storage explorer-like solution for Azure NetApp?

答: No storage explorer cannot be used to access NetApp files. I highly doubt if there is an explorer available as of now unless you use some commands and create your own onw</p>


问:
Android : How to get the Id of selected item from Spinner
In my case I want to get the Id of selected item from Spinner. I have two fields in my modal class which are id and name. I'am listing all the data and am setting to this list to the adapter. I have tried to get the selectedItem Id by using the getSelectedItem() method. But i can only get the first id of the list of item.

This is my code.

```<code>public class ModifyEventFragment extends DialogFragment{
Context context;
CalEvent eve;
Project proj;
Spinner eventType,stage;
public static String eid,pid,type;
public static List<EventType> event_type;
public static List<ProjectStatus> cust_stage;
EditText where,when,who,notes;
String eve_type,stage_val,when_val,who_val,notes_val;
String modified_where,modified_who,modified_when,modified_notes;
public ModifyEventFragment(Project proj)
{
    this.proj=proj;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.modify_project_event, container,
            false);
    context = rootView.getContext();
    eventType = (Spinner) rootView.findViewById(R.id.modifyEventType);
    stage =(Spinner) rootView.findViewById(R.id.modifyStage);
    where = (EditText)rootView.findViewById(R.id.modifyWhere);
    who = (EditText)rootView.findViewById(R.id.modifyWho);
    when = (EditText)rootView.findViewById(R.id.modifyWhen);
    notes =(EditText) rootView.findViewById(R.id.modifyNotes);
    eve = CalEvent.getCalEvent(ProjectEventFragment.calevent.eve_id);
    event_type = EventType.listAll();
    CustomEventTypeAdapter adapter = new CustomEventTypeAdapter(context, event_type);
    eventType.setAdapter(adapter);
    type=((EventType)eventType.getSelectedItem()).et_id;
    cust_stage = ProjectStatus.listAll();
    CustomStatusAdapter adapter1 = new CustomStatusAdapter(context, cust_stage);
    stage.setAdapter(adapter1);
    where.setText(eve.followup_location.toString());
    where.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_where = s.toString();
        }
    });
    who.setText(eve.person_met.toString());
    who.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_who = s.toString();
        }
    });
    when.setText(eve.event_start.toString());
    when.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_when = s.toString();
        }
    });
    notes.setText(eve.notes.toString());
    notes.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_notes = s.toString();
        }
    });
    Button save = (Button) rootView.findViewById(R.id.modifyeventsave);

    save.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            eve.followup_location = modified_where;
            eve.event_start = modified_when;
            eve.person_met = modified_who;
            eve.notes = modified_notes;
            System.out.println("print type"+type);
            eve.save();
            ProjectEventFragment.adapter.notifyDataSetChanged();
        }
    });

    return rootView;
}
</code>```

This is CustomEventType adapter code.

```<code>public class CustomEventTypeAdapter extends BaseAdapter{
Context ctx;
List<EventType> ps;
LayoutInflater inflater;
public CustomEventTypeAdapter(Context ctx,List<EventType> ps)
{
    this.ctx=ctx;
    this.ps=ps;
    inflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return ps.size();
}

@Override
public EventType getItem(int position) {
    // TODO Auto-generated method stub
    return ps.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return ps.get(position).getId();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (convertView == null)
        rowView = inflater.inflate(R.layout.spinner_item_local, parent,
                false);
    TextView textView = (TextView) rowView.findViewById(R.id.spinner_item_text);

    EventType proj = getItem(position);
    try {
        textView.setText(proj.name);

    } catch (Exception e) {

    }

    return rowView;
}
</code>```

Can someone help me to solve this problem?

答:
You have a ProjectStatus bean. Now Override method String toString() in it.

```<code>public class ProjectStatus {

    private Integer id; // Long, String any type

    private String name;

    // more properties if you need

    @Override  // Mandatory
    public String toString() {
        return name; // name + " ("+id+")"; //  can also be returned
    }

    // Getter & Setter
}
</code>```

Then make ArrayAdapter<ProjectStatus> and set it in Spinner to load Spinner with status options.

```<code>//Task 1.
List<ProjectStatus> cust_stages = ProjectStatus.listAll(); // Or using any JSON Data OR API call;

//Task 2.
ArrayAdapter<ProjectStatus> statusAdapter = new ArrayAdapter<ProjectStatus>(
        this, android.R.layout.simple_spinner_item, cust_stages
    );
statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//Task 3.
Spinner stage =(Spinner) rootView.findViewById(R.id.modifyStage);
stage.setAdapter(statusAdapter);
</code>```

Now get selected ProjectStatus and it's Properties in any Click/Change Event like below..

```<code>// In any OnClick / OnSelect event
ProjectStatus selectedStatus = (ProjectStatus) stage.getSelectedItem();
Integer statusId = selectedStatus.getId();
String statusName = selectedStatus.getName();
// and if you have more properties
</code>```

Body:
In my case I want to get the Id of selected item from Spinner. I have two fields in my modal class which are id and name. I'am listing all the data and am setting to this list to the adapter. I have tried to get the selectedItem Id by using the getSelectedItem() method. But i can only get the first id of the list of item.

This is my code.

public class ModifyEventFragment extends DialogFragment{
Context context;
CalEvent eve;
Project proj;
Spinner eventType,stage;
public static String eid,pid,type;
public static List<EventType> event_type;
public static List<ProjectStatus> cust_stage;
EditText where,when,who,notes;
String eve_type,stage_val,when_val,who_val,notes_val;
String modified_where,modified_who,modified_when,modified_notes;
public ModifyEventFragment(Project proj)
{
    this.proj=proj;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.modify_project_event, container,
            false);
    context = rootView.getContext();
    eventType = (Spinner) rootView.findViewById(R.id.modifyEventType);
    stage =(Spinner) rootView.findViewById(R.id.modifyStage);
    where = (EditText)rootView.findViewById(R.id.modifyWhere);
    who = (EditText)rootView.findViewById(R.id.modifyWho);
    when = (EditText)rootView.findViewById(R.id.modifyWhen);
    notes =(EditText) rootView.findViewById(R.id.modifyNotes);
    eve = CalEvent.getCalEvent(ProjectEventFragment.calevent.eve_id);
    event_type = EventType.listAll();
    CustomEventTypeAdapter adapter = new CustomEventTypeAdapter(context, event_type);
    eventType.setAdapter(adapter);
    type=((EventType)eventType.getSelectedItem()).et_id;
    cust_stage = ProjectStatus.listAll();
    CustomStatusAdapter adapter1 = new CustomStatusAdapter(context, cust_stage);
    stage.setAdapter(adapter1);
    where.setText(eve.followup_location.toString());
    where.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_where = s.toString();
        }
    });
    who.setText(eve.person_met.toString());
    who.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_who = s.toString();
        }
    });
    when.setText(eve.event_start.toString());
    when.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_when = s.toString();
        }
    });
    notes.setText(eve.notes.toString());
    notes.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_notes = s.toString();
        }
    });
    Button save = (Button) rootView.findViewById(R.id.modifyeventsave);

    save.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            eve.followup_location = modified_where;
            eve.event_start = modified_when;
            eve.person_met = modified_who;
            eve.notes = modified_notes;
            System.out.println("print type"+type);
            eve.save();
            ProjectEventFragment.adapter.notifyDataSetChanged();
        }
    });

    return rootView;
}

This is CustomEventType adapter code.

public class CustomEventTypeAdapter extends BaseAdapter{
Context ctx;
List<EventType> ps;
LayoutInflater inflater;
public CustomEventTypeAdapter(Context ctx,List<EventType> ps)
{
    this.ctx=ctx;
    this.ps=ps;
    inflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return ps.size();
}

@Override
public EventType getItem(int position) {
    // TODO Auto-generated method stub
    return ps.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return ps.get(position).getId();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (convertView == null)
        rowView = inflater.inflate(R.layout.spinner_item_local, parent,
                false);
    TextView textView = (TextView) rowView.findViewById(R.id.spinner_item_text);

    EventType proj = getItem(position);
    try {
        textView.setText(proj.name);

    } catch (Exception e) {

    }

    return rowView;
}

Can someone help me to solve this problem?

Body:
You have a ProjectStatus bean. Now Override method String toString() in it.

public class ProjectStatus {

    private Integer id; // Long, String any type

    private String name;

    // more properties if you need

    @Override  // Mandatory
    public String toString() {
        return name; // name + " ("+id+")"; //  can also be returned
    }

    // Getter & Setter
}

Then make ArrayAdapter<ProjectStatus> and set it in Spinner to load Spinner with status options.

//Task 1.
List<ProjectStatus> cust_stages = ProjectStatus.listAll(); // Or using any JSON Data OR API call;

//Task 2.
ArrayAdapter<ProjectStatus> statusAdapter = new ArrayAdapter<ProjectStatus>(
        this, android.R.layout.simple_spinner_item, cust_stages
    );
statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//Task 3.
Spinner stage =(Spinner) rootView.findViewById(R.id.modifyStage);
stage.setAdapter(statusAdapter);

Now get selected ProjectStatus and it's Properties in any Click/Change Event like below..

// In any OnClick / OnSelect event
ProjectStatus selectedStatus = (ProjectStatus) stage.getSelectedItem();
Integer statusId = selectedStatus.getId();
String statusName = selectedStatus.getName();
// and if you have more properties


问:
How can I use IF ELSE in WHERE clause on the basis of a string variable?
I have an SP. It returns some number of rows. Here is the SP:

```<code>ALTER PROCEDURE [dbo].[spGetClients]
</code>```

(
    @orderBy varchar(50),
    @startAge int,
    @endAge int,
    @sex char,
    @staffId nvarchar(1024),
    @statusId nvarchar(1024),
    @ethnicityId nvarchar(1024),
    @treatmentProviderId nvarchar(1024)
)
AS
BEGIN
    SET NOCOUNT ON;

```<code>IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) AS ClientName,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex,
    dbo.GetClientStatus(c.Id, @statusId) AS Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id, @ethnicityId) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id, @staffId) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS HealthProvider,
    dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) AS TreatmentProvider
    FROM Client c
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    LEFT OUTER JOIN GeneralStatus gs on gs.Id = c.StatusId
    where gs.Name <> 'Deleted'
    and (dbo.GetAge(c.DateOfBirth, GETDATE()) BETWEEN @startAge and @endAge)
    and ((@sex = 'M' and c.sex = 'M') or (@sex = 'F' and c.Sex = 'F') or (@sex = '' and (c.Sex in ('M', 'F', ''))))
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStatus(c.Id, @statusId) is not null
    and dbo.GetEthnicity(c.Id, @ethnicityId) is not null
    and dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) is not null
    ORDER BY ClientName
END
END
</code>```

The UDFs(User defined functions) are dbo.GetClientStaffContacts(c.Id, @staffId) and other. They return some rows which are having null as well. That's why I'm using last 5 statements in where clause so that only non null values can be collected. Everything is working fine but the problem is, I want this check of non null only when these variables are NOT empty string:

```<code>@staffId nvarchar(1024),
@statusId nvarchar(1024),
@ethnicityId nvarchar(1024),
@treatmentProviderId nvarchar(1024)
</code>```

How can I resolve this issue?
I want something like this:

If @staffId <> '' then dbo.GetClientStaffContacts(c.Id, @staffId) is not null

答:
You can't do logical comparisons within a CASE statement. You have to produce a value from a case expression, and the type of each possible value produced must be the same, or convertible:

```<code>CASE @staffId
    WHEN "" THEN 1
    ELSE
       CASE
           WHEN dbo.GetClientStaffContacts(c.Id, @staffId) is not null THEN 1
           ELSE 0
       END
END = 1
</code>```

Would be a condition you could put in your WHERE clause

There are two forms of CASE expression possible:

Simple CASE (when you're trying to find a WHEN clause that is equal to the provided value after the keyword CASE) - this is what the outer CASE expression is doing (trying to find a WHEN clause that matches the @StaffId value).

Searched CASE (when you're trying to match a WHEN clause based on arbitrary predicates) - this is what the inner CASE expression is doing (testing whether the return of the function is not null)

You can't determine NULL/non-NULL status using a Simple CASE expression, since NULL is not equal to NULL (nor is it not equal).

Body:
I have an SP. It returns some number of rows. Here is the SP:

ALTER PROCEDURE [dbo].[spGetClients]

(
    @orderBy varchar(50),
    @startAge int,
    @endAge int,
    @sex char,
    @staffId nvarchar(1024),
    @statusId nvarchar(1024),
    @ethnicityId nvarchar(1024),
    @treatmentProviderId nvarchar(1024)
)
AS
BEGIN
    SET NOCOUNT ON;

IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) AS ClientName,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex,
    dbo.GetClientStatus(c.Id, @statusId) AS Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id, @ethnicityId) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id, @staffId) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS HealthProvider,
    dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) AS TreatmentProvider
    FROM Client c
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    LEFT OUTER JOIN GeneralStatus gs on gs.Id = c.StatusId
    where gs.Name <> 'Deleted'
    and (dbo.GetAge(c.DateOfBirth, GETDATE()) BETWEEN @startAge and @endAge)
    and ((@sex = 'M' and c.sex = 'M') or (@sex = 'F' and c.Sex = 'F') or (@sex = '' and (c.Sex in ('M', 'F', ''))))
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStatus(c.Id, @statusId) is not null
    and dbo.GetEthnicity(c.Id, @ethnicityId) is not null
    and dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) is not null
    ORDER BY ClientName
END
END

The UDFs(User defined functions) are dbo.GetClientStaffContacts(c.Id, @staffId) and other. They return some rows which are having null as well. That's why I'm using last 5 statements in where clause so that only non null values can be collected. Everything is working fine but the problem is, I want this check of non null only when these variables are NOT empty string:

@staffId nvarchar(1024),
@statusId nvarchar(1024),
@ethnicityId nvarchar(1024),
@treatmentProviderId nvarchar(1024)

How can I resolve this issue?
I want something like this:

If @staffId <> '' then dbo.GetClientStaffContacts(c.Id, @staffId) is not null

Body:
You can't do logical comparisons within a CASE statement. You have to produce a value from a case expression, and the type of each possible value produced must be the same, or convertible:

CASE @staffId
    WHEN "" THEN 1
    ELSE
       CASE
           WHEN dbo.GetClientStaffContacts(c.Id, @staffId) is not null THEN 1
           ELSE 0
       END
END = 1

Would be a condition you could put in your WHERE clause

There are two forms of CASE expression possible:

Simple CASE (when you're trying to find a WHEN clause that is equal to the provided value after the keyword CASE) - this is what the outer CASE expression is doing (trying to find a WHEN clause that matches the @StaffId value).

Searched CASE (when you're trying to match a WHEN clause based on arbitrary predicates) - this is what the inner CASE expression is doing (testing whether the return of the function is not null)

You can't determine NULL/non-NULL status using a Simple CASE expression, since NULL is not equal to NULL (nor is it not equal).


问:
Insert or write data to .txt file with flask
I have tried the existing code, but it still fails. My problem is how to insert data into the .txt file using the Flask form.

The following is my app.py code:

```<code>from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('index.html')

@app.route('/', methods=['GET', 'POST'])
def my_form_post():
    input_nopol = request.form.get['nopol']
    if request.method == 'POST' and input_nopol:
       print(listdir)
       with open('/home/pi/web-server/nopol.txt', 'w') as f:
            f.write(str(input_nopol))
    return render_template('index.html', nopol=input_nopol)

if __name__ == "__main__":
   app.run(host='192.168.1.2', port=8080, debug=True)
</code>```

The following is a simple code for the form at index.html in template folder:

```<code><!DOCTYPE html>
   <head>
      <title>Hello</title>
   </head>

   <body>
      <form method="POST">
        <input name="text">
        <input type="submit">
      </form>
   </body>
</html>
</code>```

I am very grateful for the help and solution from all of you.

答:
```<code><!DOCTYPE html>
<head>
  <title>Hello</title>
</head>

<body>
  <form action="" method="POST">
    <input name="text_box">
    <input type="submit">
  </form>
</code>```

<p>
   </p>

```<code>from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

@app.route('/')
def my_form():
   return render_template('index.html')

@app.route('/', methods=['POST'])
def my_form_post():
    input_nopol = request.form['text_box']
    if request.method == 'POST':
       with open('nopol.txt', 'w') as f:
            f.write(str(input_nopol))
    return render_template('index.html', nopol=input_nopol)

if __name__ == '__main__':
    app.debug = True
    app.run()
</code>```

Body:
I have tried the existing code, but it still fails. My problem is how to insert data into the .txt file using the Flask form.

The following is my app.py code:

from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('index.html')

@app.route('/', methods=['GET', 'POST'])
def my_form_post():
    input_nopol = request.form.get['nopol']
    if request.method == 'POST' and input_nopol:
       print(listdir)
       with open('/home/pi/web-server/nopol.txt', 'w') as f:
            f.write(str(input_nopol))
    return render_template('index.html', nopol=input_nopol)

if __name__ == "__main__":
   app.run(host='192.168.1.2', port=8080, debug=True)

The following is a simple code for the form at index.html in template folder:

<!DOCTYPE html>

      <title>Hello</title>

      <form method="POST">
        <input name="text">
        <input type="submit">
      </form>

I am very grateful for the help and solution from all of you.

Body:
<!DOCTYPE html>
<head>
  <title>Hello</title>
</head>

<body>
  <form action="" method="POST">
    <input name="text_box">
    <input type="submit">
  </form>

from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

@app.route('/')
def my_form():
   return render_template('index.html')

@app.route('/', methods=['POST'])
def my_form_post():
    input_nopol = request.form['text_box']
    if request.method == 'POST':
       with open('nopol.txt', 'w') as f:
            f.write(str(input_nopol))
    return render_template('index.html', nopol=input_nopol)

if __name__ == '__main__':
    app.debug = True
    app.run()


问:
running totals automatically inserted reset every 9 rows
I have a google sheet with 4 users use to log hours and other info in. The columns are totalised and displayed at the top.

What I would like to do is in a column, say L, number 1 - 9 every nine lines (rows) starting at row 6  (row number to be defined) and in another column, say M, insert the running total of the nine lines of the value in column I.

The reason for the running total is that it needs to be transferred in paper-based logbooks which have 9 lines per page.

Hope that makes sense?

How would you go about doing this and is it an equation or a macro I would need?

In the screenshot I would like to automatically add columns L and M. M is based on the value in I

L and M are the values under Page totals and I is the flight time.

test sheet

update 1: I have solved the counting with the following in L7 and then dragged down

=if(L6+1 < 10, L6+1,1)

Update 2: nearly working using the below in M7 and dragging it down, however, when column I is blank it still adds a number instead of leaving the cell blank!

```<code>=if(L7=1,
I7,
if(ISBLANK(I7), " ", M6+I7)
)
</code>```

答:
Formulae:

For column L, you can use an ARRAYFORMULA with the MOD operator, paste the following into L6:

```<code>=ARRAYFORMULA(MOD((ROW(L6:L) + 3),9) + 1)
</code>```

For column M, use L7 = 0 instead of ISBLANK(L7), paste this in M6 and drag down:

```<code>=IF(L6 = 1, I6, if(I6 = 0, " ", M5 + I6))
</code>```

Body:
I have a google sheet with 4 users use to log hours and other info in. The columns are totalised and displayed at the top.

What I would like to do is in a column, say L, number 1 - 9 every nine lines (rows) starting at row 6  (row number to be defined) and in another column, say M, insert the running total of the nine lines of the value in column I.

The reason for the running total is that it needs to be transferred in paper-based logbooks which have 9 lines per page.

Hope that makes sense?

How would you go about doing this and is it an equation or a macro I would need?

In the screenshot I would like to automatically add columns L and M. M is based on the value in I

L and M are the values under Page totals and I is the flight time.

test sheet

update 1: I have solved the counting with the following in L7 and then dragged down

=if(L6+1 < 10, L6+1,1)

Update 2: nearly working using the below in M7 and dragging it down, however, when column I is blank it still adds a number instead of leaving the cell blank!

=if(L7=1,
I7,
if(ISBLANK(I7), " ", M6+I7)
)

Body:
Formulae:

For column L, you can use an ARRAYFORMULA with the MOD operator, paste the following into L6:

=ARRAYFORMULA(MOD((ROW(L6:L) + 3),9) + 1)

For column M, use L7 = 0 instead of ISBLANK(L7), paste this in M6 and drag down:

=IF(L6 = 1, I6, if(I6 = 0, " ", M5 + I6))


问:
Specify type annotation for Python function returning type of argument
How do I correctly type-annotate the function below?

def f(cls: type) -> ???:
    return cls()

# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()
```

Is there a way to type-annotate ??? with something that involves the value of cls instead of just Any or to omit the return type annotation? It is OK if I have to change the type annotation of the cls parameter.

答:
Using a mix of Callable or Type and a TypeVar to indicate how the return type corresponds to the parameter type:

```<code>from typing import Callable, TypeVar, Type

T = TypeVar("T")

# Alternative 1, supporting any Callable object
def f(cls: Callable[[], T]) -> T:
    return cls()

ret_f = f(int)
print(ret_f)  # It knows ret_f is an int

# Alternative 2, supporting only types
def g(cls: Type[T]) -> T:
    return cls()

ret_g = f(int)
print(ret_g)  # It knows ret_g is an int
</code>```

The 1st alternative accepts any callable object; not just calls that create objects.

Thanks for the corrections @chepner

Body:
How do I correctly type-annotate the function below?

def f(cls: type) -> ???:
    return cls()

# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()

Is there a way to type-annotate ??? with something that involves the value of cls instead of just Any or to omit the return type annotation? It is OK if I have to change the type annotation of the cls parameter.

Body:
Using a mix of Callable or Type and a TypeVar to indicate how the return type corresponds to the parameter type:

from typing import Callable, TypeVar, Type

T = TypeVar("T")

# Alternative 1, supporting any Callable object
def f(cls: Callable[[], T]) -> T:
    return cls()

ret_f = f(int)
print(ret_f)  # It knows ret_f is an int

# Alternative 2, supporting only types
def g(cls: Type[T]) -> T:
    return cls()

ret_g = f(int)
print(ret_g)  # It knows ret_g is an int

The 1st alternative accepts any callable object; not just calls that create objects.

Thanks for the corrections @chepner


问:
Specify configs in the ini-formatted file:
Noob here,
Im trying to run android emulator installed for my reactnative app to test on vscode online on azure linux machine and getting the follow error:

Specify configs in the ini-formatted file:
    /home/vsonline/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config
```

when I run npm start-android-emulator I get the error.
Please any help. I am trying to run react-native code without installing android studio

答: you should use npx or yarn like this npx start-android-emulator or yarn start-android-emulator

Body:
Noob here,
Im trying to run android emulator installed for my reactnative app to test on vscode online on azure linux machine and getting the follow error:

Specify configs in the ini-formatted file:
    /home/vsonline/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

when I run npm start-android-emulator I get the error.
Please any help. I am trying to run react-native code without installing android studio


问:
python: Using the choice box to get data besides getString()
I have defined an object that has several attribute..

```<code>class thing(object):
    def __init__(self, type, name, attrA, attrB, attrC):
        self.type = type
        self.name = name
        self.attrA = attrA
        self.attrB = attrB
        self.attrC = attrC
</code>```

lets say then I have a list of things

```<code>self.things=[thing('car','fred',1,2,3),
             thing('car','george',a,b,c),
             thing('truck','bob',6,7,8),
             thing('truck','tom',x,y,z)
            ]
</code>```

I then populate a choice box with SOME of the items from that list

```<code>for each in self.things:
    if each.type == 'car':
       self.choiceCar.Append(item=each.name)
</code>```

When the user selects Bob from the dropdown I have an event for that

```<code>def EvtChoice(self,event):
    self.Name = event.GetString()
</code>```

This captures the name of the selection, but how do I get the other attributes?  What I am currently doing is

```<code>     for each in self.items:
        if self.Name == each.name
          #Get other things here
</code>```

My thought is that if my list grows large then this loop through my entire list will become very inefficient and really unneeded since the user has already selected the specific item I want.  What I think I should be able to do is to get the index of the selected item, but im not sure how to do that, or even if that is the correct way to go about it.

答:
Associating data or objects with wx.Choice or wx.ComboBox is pretty easy. You can see an example using the latter here:

http://www.blog.pythonlibrary.org/2010/12/16/wxpython-storing-object-in-combobox-or-listbox-widgets/

The basic idea is to pass an empty list to the control's constructor and then iterate over the objects and Append them to the control. So something like this:

```<code>for obj in self.things:
    self.choiceCar.Append(obj.name, obj)
</code>```

Then in the event handler for the widget, you can get the object back by doing this:

```<code>obj = self.choiceCar.GetClientData(self.choiceCar.GetSelection())
</code>```

Body:
I have defined an object that has several attribute..

class thing(object):
    def __init__(self, type, name, attrA, attrB, attrC):
        self.type = type
        self.name = name
        self.attrA = attrA
        self.attrB = attrB
        self.attrC = attrC

lets say then I have a list of things

self.things=[thing('car','fred',1,2,3),
             thing('car','george',a,b,c),
             thing('truck','bob',6,7,8),
             thing('truck','tom',x,y,z)
            ]

I then populate a choice box with SOME of the items from that list

for each in self.things:
    if each.type == 'car':
       self.choiceCar.Append(item=each.name)

When the user selects Bob from the dropdown I have an event for that

def EvtChoice(self,event):
    self.Name = event.GetString()

This captures the name of the selection, but how do I get the other attributes?  What I am currently doing is

     for each in self.items:
        if self.Name == each.name
          #Get other things here

My thought is that if my list grows large then this loop through my entire list will become very inefficient and really unneeded since the user has already selected the specific item I want.  What I think I should be able to do is to get the index of the selected item, but im not sure how to do that, or even if that is the correct way to go about it.

Body:
Associating data or objects with wx.Choice or wx.ComboBox is pretty easy. You can see an example using the latter here:

http://www.blog.pythonlibrary.org/2010/12/16/wxpython-storing-object-in-combobox-or-listbox-widgets/

The basic idea is to pass an empty list to the control's constructor and then iterate over the objects and Append them to the control. So something like this:

for obj in self.things:
    self.choiceCar.Append(obj.name, obj)

Then in the event handler for the widget, you can get the object back by doing this:

obj = self.choiceCar.GetClientData(self.choiceCar.GetSelection())


问:
Handling "Windows Security" window with pywinauto
I am writing a program to connect to the Remote Desktop Connection automatically. So, up untill now I was successfull in getting the application up and running and have the Computer Name written into the text box. Then, I am able to automatically click submit btn. Here is the code:

```<code>import pywinauto
from pywinauto.application import Application

app = Application().start("mstsc.exe")

computerName = "computer_name"
password = "password"

app['Dialog']['Edit'].type_keys(computerName, with_spaces=True)
app['Dialog']['Connect'].click()
</code>```

This is the window where all the aforementioned stuff is done:

The next thing that pops-up after hitting Connect button is the Windows Security, where I need to input password (automatically). However, I am not sure, how should python identify the controls of that window and especially the Password text field:

So far I have tried to indetify it by its title, but unsuccessfully:

```<code>windowsSecurity = pywinauto.findwindows.find_windows(title_re = r"Windows Security")
</code>```

---------------------------------
SOLUTION --------------------------------

Just solved the issue using the following way. Firstly I identified what are the controls of the window that pops up, but before that, I am leaving some pause time for it to come on surface. Secondly, using the controls that I have identified, I send the keys and send click command. Here is the list of controls that I got by dlg.print_ctrl_ids()

| | Edit - '' (L656, T323, R1100, B371) | | ['Surname, NameEdit', 'Edit'] | | child_window(auto_id="PasswordField_2", control_type="Edit") | | |

```<code>computerName = "computer"
password = "password"
app = pywinauto.application.Application(backend="uia")
app.start('mstsc.exe')

dlg = app.window(title_re="Remote Desktop Connection")
dlg['Edit'].type_keys(computerName)
dlg['Connect'].click()

time.sleep(5)

if dlg.child_window(title="Windows Security",control_type="Window").exists():

    windows_security = dlg.child_window(title="Windows     Security",control_type="Window")
    dlg['PasswordField_2'].type_keys(password)
    dlg.child_window(auto_id='OkButton').click_input()
else:
    print("Wait time exceeded")
</code>```

Body:
I am writing a program to connect to the Remote Desktop Connection automatically. So, up untill now I was successfull in getting the application up and running and have the Computer Name written into the text box. Then, I am able to automatically click submit btn. Here is the code:

import pywinauto
from pywinauto.application import Application

app = Application().start("mstsc.exe")

computerName = "computer_name"
password = "password"

app['Dialog']['Edit'].type_keys(computerName, with_spaces=True)
app['Dialog']['Connect'].click()

This is the window where all the aforementioned stuff is done:

The next thing that pops-up after hitting Connect button is the Windows Security, where I need to input password (automatically). However, I am not sure, how should python identify the controls of that window and especially the Password text field:

So far I have tried to indetify it by its title, but unsuccessfully:

windowsSecurity = pywinauto.findwindows.find_windows(title_re = r"Windows Security")

---------------------------------
SOLUTION --------------------------------

Just solved the issue using the following way. Firstly I identified what are the controls of the window that pops up, but before that, I am leaving some pause time for it to come on surface. Secondly, using the controls that I have identified, I send the keys and send click command. Here is the list of controls that I got by dlg.print_ctrl_ids()

| | Edit - '' (L656, T323, R1100, B371) | | ['Surname, NameEdit', 'Edit'] | | child_window(auto_id="PasswordField_2", control_type="Edit") | | |

computerName = "computer"
password = "password"
app = pywinauto.application.Application(backend="uia")
app.start('mstsc.exe')

dlg = app.window(title_re="Remote Desktop Connection")
dlg['Edit'].type_keys(computerName)
dlg['Connect'].click()

time.sleep(5)

if dlg.child_window(title="Windows Security",control_type="Window").exists():

    windows_security = dlg.child_window(title="Windows     Security",control_type="Window")
    dlg['PasswordField_2'].type_keys(password)
    dlg.child_window(auto_id='OkButton').click_input()
else:
    print("Wait time exceeded")