Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to automate few of my DBA tasks using python3.
x = " ##Hostname: host1"
y = "##innodb_buffer_pool_size: 1"
z = " ##Max_connections: 150"
op = {}
a = tuple(x.split(':'))
b = tuple(y.split(':'))
c = tuple(z.split(':'))
host=""
if (a[0].strip()).lower() == "##hostname" and (a[1].strip()).lower() not in op:
host = a[1].strip()
op[host] = []
if (b[0].strip()).lower() == "##innodb_buffer_pool_size" and int(b[1].lstrip())<2:
#z = b[0].strip().lstrip('##'),b[1].strip()
op[host].append((b[0].strip().lstrip('##'),b[1].strip()))
if (c[0].strip()).lower() == "##Max_connections" and int(c[1].lstrip())<152:
op[host].append((c[0].strip().lstrip('##'),c[1].strip()))
#elif (a[0].strip()).lower() == "##log_bin" and int(a[1].strip()) == 0:
# op[host].append(tuple((a[0].strip()).lstrip('##'),a[1].strip()))
#elif (a[0].strip()).lower() == "##expire_logs_days" and int(a[1].strip()) == 0:
# op[host].append(tuple((a[0].strip()).lstrip('##'),a[1].strip()))
#else:
# pass
#print (c)
print (op)
Output i am getting:
{'host1': [('innodb_buffer_pool_size', '1')]}
Output i am expecting:
{'host1': [('innodb_buffer_pool_size', '1'),('max_connections','150')]}
If you look at my the code, my first append statement appends tuple to an empty list.
But my second append is not appending to the tuple to the list .
I cannot understand why this behaviour since this first python project and what should be done to append a tuple to an existing list for a specific key in a dictionary.
This is only part of the script, I am trying to iterate through several files and construct a list of tuples for each host with each unique host being the key, hence constructing a dictionary.
Thanks
When you have this kind of case, leanr to debug and split your code, here the problem from the if using Max_connections because that's the one missing
When printing the 2 conditions we have
print((c[0].strip()).lower() == "##Max_connections", int(c[1].lstrip()) < 152) # False True
Then looking further at the first, you set the value as lowercase but your testing stirng contains an uppercase : not valie
Correction
if (c[0].strip()).lower() == "##max_connections" and int(c[1].lstrip()) < 152:
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0
while i < len(friends):
if friends[i].islower != True:
print(friends[i])
else:
ignoredNames.append(friends[i])
i += 1
print(f"The Number Of The Ignored Names Is {len(ignoredNames)}")
I believe friends[i].islower is giving you the bound method rather than the result of that method. If you want the result, you should call friends[i].islower():
friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0
while i < len(friends):
if friends[i].islower() != True:
print(friends[i])
else:
ignoredNames.append(friends[i])
i += 1
Output:
Mohamed
Shady
Sherif
You iterate in python using for ... in ....
Also you don't need to invert checking for islower if you want to check for the upper case of the first letter.
Also don't compare boolean values to boolean constants. It's redundant.
friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
for friend in friends:
if friend[0].isupper():
print(friend)
else:
ignoredNames.append(friend)
print(f"The Number Of The Ignored Names Is {len(ignoredNames)}")
You need to call the method as .islower() rather than .islower. The former calls the method and actually returns the boolean value you want in the check.
For instance:
friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
i=0
ignoredNames=[]
while i < len(friends):
if friends[i].islower() != True:
print(friends[i])
else:
ignoredNames.append(friends[i])
i += 1
print(ignoredNames)
Output:
Mohamed
Shady
Sherif
['ahmed', 'eman']
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
When running this program I get this error message: NameError: name 'wordList' is not defined. Can't figure out why. Thanks.
import ahocorasick
def build_actree(wordlist):
actree = ahocorasick.Automaton()
for index, word in enumerate(wordlist):
actree.add_word(word, (index, word))
actree.make_automaton()
return actree
if __name__ == '__main__':
actree = build_actree(wordlist=wordlist)
sent_cp = sent
for i in actree.iter(sent):
sent_cp = sent_cp.replace(i[1][1], "**")
sent = '我草你妈'
wordlist =['我草']
print("屏蔽词:",i[1][1])
print("屏蔽结果:",sent_cp)
`
The first thing you do in your code is :
actree = build_actree(wordlist=wordlist)
But there is no place where wordlist is defined. May be some code is missing.
This is the solution I finally came up with:
import ahocorasick
def build_actree(wordlist):
actree = ahocorasick.Automaton()
for index, word in enumerate(wordlist):
actree.add_word(word, (index, word))
actree.make_automaton()
return actree
if __name__ == '__main__':
# correction : add wordlist initialisation
sent = '我草你妈'
wordlist =['我草']
actree = build_actree(wordlist=wordlist)
sent_cp = sent
for i in actree.iter(sent):
sent_cp = sent_cp.replace(i[1][1], "**")
print("屏蔽词:", i[1][1])
print("屏蔽结果:", sent_cp)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have two for else block which verifies two integers,Is it possible to combine both together?
for vars in result['events']:
if vars['yyy'] == 977:
break
else:
raise AssertionError('output not found')
for vars in result['events']:
if vars['yyy'] == int(line.split(',')[-1], 16):
break
else:
raise AssertionError('output not found')
With simple or condition:
for vars in result['events']:
if vars['yyy'] == 977 or vars['yyy'] == int(line.split(',')[-1], 16):
break
else:
raise AssertionError('output not found')
Update after condition clarification:
(also line.split(',')[-1] is replaced with line[line.rfind(',') + 1:])
yyy_set = {977, int(line[line.rfind(',') + 1:], 16)}
for vars in result['events']:
vars['yyy'] in yyy_set and yyy_set.remove(vars['yyy'])
if not yyy_set: break # all set items were consumed
else:
raise AssertionError('output not found')
The other answers assume you want to find one of two needles in a single haystack, and don't care which one you find, but the question isn't clear if that's the correct solution.
To cover the case where you need both search values to be found (looking for two different needles in one haystack, and both must exist), there is no easy syntax to do it. But you can build that logic out of a set and for/else:
remaining = {977, int(line.split(',')[-1], 16)}
for vars in result['events']:
remaining.discard(vars['yyy'])
if not remaining:
break
else:
raise AssertionError('Expected outputs not found: {}'.format(remaining))
remaining.discard(vars['yyy']) removes each vars['yyy'] if it exists, and silently ignores it if it does not. When both expected values have been seen (and discarded), the set is empty, and you break, bypassing the else. If one or more values has not been seen, they'll remain in remaining and can be incorporated into the error message.
The question could have a bit clearer that what it is. Based on what I could understand, you are looking for 2 different values in result['events']. You could use 'or' condition to club the 2 conditions together.
if foobar == 'bac' or zoo == '123':
blah
else:
bleh
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
while dir_loop_water < water_lenth:
ds_water = gdal.Open('path'+ dirlist_water[dir_loop_water] , gdal.GA_ReadOnly)
numer_of_band_water = str(ds_water.RasterCount)
if numer_of_band_water == '3':
print('water condition matched')
rb_water = ds_water.GetRasterBand(1)
band1_water_tmp = rb_water.ReadAsArray()
band1_water = band1_water_tmp.tolist()
rb2_water = ds_water.GetRasterBand(2)
band2_water_tmp = rb2_water.ReadAsArray()
band2_water = band2_water_tmp.tolist()
rb3_water = ds_water.GetRasterBand(3)
band3_water_tmp = rb3_water.ReadAsArray()
band3_water = band3_water_tmp.tolist()
[cols_water,rows_water] = band1_water_tmp.shape
loop_water_cols = 0
while loop_water_cols < cols_water:
loop_water_rows = 0
while loop_water_rows < rows_water:
dataset.append([band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0])
loop_water_rows = loop_water_rows +1
del dataset[0]
with open('path/dataset.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(dataset)
f.close()
dataset= [None]
loop_water_cols = loop_water_cols +1
dir_loop_water= dir_loop_water+1
With the above code, I want to add lists with length 4 to dataset.
but i print dataset's value(print(dataset[number])), it print like this.
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0]
[0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]
In my opinion of above code, I add one list with four values.
However, the result is a combination of two lists with four values.
I could not find where the list would be merged.
Thanks for letting me know how to add only one list with 4 values at a time.
Your dataset.append() method is appending the entire list into your list (making a list of lists).
To append each item of the new list into the dataset (If I'm understanding you correctly) use += like so:
dataset += [band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0]
this will result in a list like so:
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0, 0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
def DS():
import os
import pandas as pd
directory=input('What folder would you like to work in? ( Example: /Users/hem/Desktop/pythontest/ ')
filename=input('Please enter the name (including .csv) of the file you would like to analyze ' )
idkey=input('What is the subject ID you are analyzing? ' )
sessionkey=input('What session of testing are you analyzing? ')
print('---------- Calculating Drug Stroop endpoints ----------')
os.chdir(directory)
dataframe = pd.read_csv(filename, error_bad_lines=False)
output={}
CategoryID = dataframe['CategoryID'].tolist
ReactionTime = dataframe['ReactionTime'].tolist
CorrectResponse = dataframe['CorrectResponse'].tolist
#Stroop interference score
totalN = 0
countN = 0
CorrectResponseNeutral = 0
for i in range(len(CategoryID)):
if CategoryID[i] == 1:
totalN + ReactionTime[i]
countN + 1
CorrectResponseNeutral + CorrectResponse[i]
AverageRTNeutral = totalN/countN
CorrectResponseNeutral = CorrectResponseNeutral/countN
totalD = 0
countD = 0
CorrectResponseDrug = 0
for i in range(len(CategoryID)):
if CategoryID[i] == 2:
totalD + ReactionTime[i]
countD + 1
CorrectResponseDrug + CorrectResponse[i]
AverageRTDrug = totalD/countD
CorrectResponseDrug = CorrectResponseDrug/countD
InterferenceScore = AverageRTNeutral - AverageRTDrug
output['SubjectID'] = idkey
output['Session'] = sessionkey
output['Interference Score'] = InterferenceScore
output['Accuracy of Neutral Trials'] = CorrectResponseNeutral
output['Accuracy of Drug Trials'] = CorrectResponseDrug
print('---------- Done calculating endpoints ----------')
outputname=input('What would you like to name your outputfile? (Please include.csv)')
outputdataframe = pd.DataFrame.from_dict([output])
outputdataframe.to_csv(os.path.join('/Users/hem/Desktop/Analysis/DrugStroopAnalyzed',outputname))
Hey Guys. Im trying to write a script that would calculate endpoints for a medical task. When I run the program, it works all the way until it hits the first for loop of the script. I'm pretty sure there is an error because CategoryID doesnt have a length property. But I also think it should because I'm converting it to a list in the beginning. Any suggestions on how to fix this? Thanks in advance.
It seems like you forgot the () after tolist method, so it can be parsed as a call to the method, and not the method itself:
CategoryID = dataframe['CategoryID'].tolist()
ReactionTime = dataframe['ReactionTime'].tolist()
CorrectResponse = dataframe['CorrectResponse'].tolist()