I am trying to optimize this block of code to use a single query rather than looping over and over.
while not (dataX):
i += 1
this_id = '/'.join(this_id.split('/')[0:-i])
if not this_id:
break
else:
dataX = db.conn[db_read].query("SELECT x AS xX FROM link WHERE _deleted = 0 AND _ref = %s AND _ntype = 'code' LIMIT 1;", data = (this_id,))
I want to use the IN clause with a variable that contains all possible substring but I can't get it to work.
this_id_list = "'/a/b/c/d/e' , '/a/b/c/d', '/a/b/c', '/a/b', '/a'"
result = db.conn[db_read].query("SELECT x AS xX FROM link WHERE _deleted = 0 AND _ref IN($this_id_list)")
Any idea what am I doing wrong and how to fix it? I would really appreciate any input! This is a Python script btw.
this_id_list = "'/a/b/c/d/e' , '/a/b/c/d', '/a/b/c', '/a/b', '/a'"
This should be a string
Related
I'm currently trying to get into Python and Ren'Py a bit. Since I like to design a lot dynamically
and don't want to use copy&paste so often, I'm trying to create a page that will have ImageButtons with the corresponding number I specify.
In the example below I use "4" - but this can be higher.
I have built a class for this purpose:
Example:
init python:
class PictureSettings(object):
def __init__ (self, ImgIdle, ImgHover, LabelCall):
self.ImgIdle = ImgIdle
self.ImgHover = ImgHover
self.LabelCall = LabelCall
return
For the Idle/Hover and for the Jump.
If I insert in the code now in an object each entry "manually" with append I get all 4 pictures as desired indicated.
Example: (Works - but is not dynamic)
python:
var_pictures = []
var_pictures.append(PictureSettings("img_picture_1_idle", "img_picture_1_hover", "picture_1"))
var_pictures.append(PictureSettings("img_picture_2_idle", "img_picture_2_hover", "picture_2"))
var_pictures.append(PictureSettings("img_picture_3_idle", "img_picture_3_hover", "picture_3"))
var_pictures.append(PictureSettings("img_picture_4_idle", "img_picture_4_hover", "picture_4"))
I would like it to be like this:
Example (Here I get only ""img_picture_4_idle", "img_picture_4_hover", "picture_4""):
$ countlimit = 4
$ count = 1
python:
while count < countlimit:
var_pictures = []
var_pictures.append(PictureSettings(
ImgIdle = "img_picture_[count]_idle",
ImgHover = "img_picture_[count]_hover",
LabelCall = "picture_[count]"))
count += 1
Have already tried various things, unfortunately without success.
For example: with Add - instead of append (because this overwrites the result and leaves only the last entry
I get the following error:
var_pictures.add(PictureSettings( AttributeError: 'RevertableList' object has no attribute 'add')
Maybe someone can help me with the solution so I can keep my code dynamic without copying something X times.
Thanks for your help
You are creating your list inside your loop, so it is recreated every time.
At the end, you only get the last created list.
var_pictures = []
while count < countlimit:
var_pictures.append(PictureSettings(
ImgIdle = "img_picture_[count]_idle",
ImgHover = "img_picture_[count]_hover",
LabelCall = "picture_[count]"))
count += 1
On another subject, if you want to do this in a more pythonic way:
pictures = [] # no need for var_, we know its a variable
for i in range(1, 5):
pictures.append(PictureSettings(
# in python, we prefere snake_case attributes
img_idle=f'img_picture_{i}_idle',
img_hover=f'img_picture_{i}_hover',
...
))
# or even shorter with list comprehension
pictures = [
PictureSettings(
img_idle=f'img_picture_{i}_idle',
)
for i in range(1, 5)
]
By the way, no need to return in your class constructor
I am running a function that grabs some data from a website and writes it into a pandas database. I am using selenium and geckodriver.
...code...
first_names = driver.find_elements_by_class_name('first-name')
first_names = [name.text for name in first_names]
last_names = driver.find_elements_by_class_name('last-name')
last_names = [name.text for name in last_names]
commit_status = driver.find_elements_by_class_name('school-name')
commit_status = [commit.text for commit in commit_status]
#error is happening below
athlete['commit_school'] = athlete['commit'].str.replace('\d+', '').str.replace('/',
'').str.replace('VERBAL', '').str.replace('SIGNED', '')
athlete['first'] = athlete['first'].str.title()
athlete['last'] = athlete['last'].str.title()
...code...
I then loop through this function to go through similar data on different states webpages. Sometimes it returns the data on the page normally and continues to the next state, while other times, I get:
AttributeError: Can only use .str accessor with string values!
...and the code breaks. The part that is confusing me is that the times I get the error seem to be arbitrary. Sometimes I will make it through 1/4 of the loop and sometimes 3/4 of the loop.
My first attempt to fix was a try/except, but I am not sure if I am doing it right or if that is the best approach:
athlete['state'] = state_all[:length:]
athlete['hs'] = hs_all[:length:]
athlete['commit'] = commit_status[:length:]
try:
athlete['commit_school'] = athlete['commit'].str.replace('\d+', '').str.replace('/',
'').str.replace('VERBAL', '').str.replace('SIGNED', '')
athlete['first'] = athlete['first'].str.title()
athlete['last'] = athlete['last'].str.title()
except AttributeError:
pass
athlete['list'] = 'Rivals_' + year + '_' + list_state
athlete['home'] = profile_page[:length:]
The error is happening within that try/except statement, but I think it just skips all of it if it finds an error.
Does the below code where I add .astype('str') to the middle for each column solve? You probably have column with mixed data type of strings and objects.
athlete['commit_school'] = athlete['commit'].astype('str').str.replace('\d+', '').str.replace('/', '').str.replace('VERBAL', '').str.replace('SIGNED', '')
athlete['first'] = athlete['first'].astype('str').str.title()
athlete['last'] = athlete['last'].astype('str').str.title()
I got a situation I have to generate a if condition based on item configured in my configuration json file.
So once the if statement converted into a string I want that to run by eval .
This is what I am trying for that.
Here is what flags and set_value look like
My json
"EMAIL_CONDITION":
{
"TOXIC_THRESOLD":"50",
"TOXIC_PLATFORM_TODAY":"0",
"TOXIC_PRS_TODAY":"0",
"Explanation":"select any or all 1 for TOXIC_Thresold 2 for TOXIC_PLATFORM 3 for toxic_prs ",
"CONDITION_TYPE":["1","2"]
},
"email_list":{
"cc":["abc#def.t"],
"to":["abc#def.net"]
}
The Python
CONDITION_TYPE is a variable where values can be either all, any or 1,2 ,2,3, or 1,3
1 stands for toxic index 2 for platform and 3 for toxic prs
But the idea is going forward any number of parameters can be added so I wanted to make the if condition generic so that can take any number of conditions simply just wanted to avoid to many if else. all and any i have already handaled its straight forward but this is variable number so only else part snippet given
flags['1'] = toxic_index
flags['2'] = toxic_platform
flags['3'] = toxic_prs
set_value['1'] = toxic_index_condition
set_value['2'] = toxic_platform_condition
set_value['3'] = toxic_pr_condition
else:
condition_string = 'if '
for val,has_more in lookahead(conditions):
if has_more:
condition_string = str(condition_string+ str(flags[val] >= set_value[val])+ str('and') )
else:
condition_string = str(condition_string+ str(flags[val] >= set_value[val]) + str(':') )
print str(condition_string)
I do understand that most of them are variable so I am getting the response like
if False and False:
Instead of False I wanted to get the real condition(basically like condition_string+ str(flags[val] >= set_value[val]) ) based on that I can send mail.
I am not able to do that as I am getting False and False.
Please suggest me a best solution for it.
So I'm writing a small project using python,
But now I'm in trouble.
I made some code like this:
START_BUTTONS = ("button1", "button2")
markup = types.ReplyKeyboardMarkup()
lengthof = len(START_BUTTONS)
countn = 0
while (countn < lengthof):
exec("itembtn" + str(countn) + " = types.KeyboardButton(START_BUTTONS[" + str(countn) + "])")
countn = countn + 1
So, this will parse something like this (unitl the tuple ends):
itembtn0 = types.KeyboardButton(START_BUTTONS[0])
itembtn1 = types.KeyboardButton(START_BUTTONS[1])
and...
So those variables are usable later.
But, my problem is here. I want to check how many of those variables are there (itembtn0 itembtn1 itembtn2 itembtn3...) and put them like this:
markup.row(itembtn0, itembtn1, itembtn2)
so , if there were 5 of those, it will return something like this:
markup.row(itembtn0, itembtn1, itembtn2, itembtn3, itembtn4)
Actually I have no idea for what I should write.
Thanks for help! & Sorry for my bad english.
You are trying to create numbered variables, which can in all cases be replaced by an array. Try something simple instead:
START_BUTTONS = ("button1", "button2")
markup = types.ReplyKeyboardMarkup()
itembtn = []
for btn in START_BUTTONS:
itembtn.append(types.KeyboardButton(btn))
Access it with
itembtn[0]
itembtn[1]
etc.
And you can know how many there are:
len(itembtn)
I am not sure about your markup function, but you can pass the whole array as parameters like this:
markup.row(*itembtn)
I'm trying to build a function for fitting of my data. I'm using CurveExpert and the lines are in python. I'm no expert so after trying, it says I have an error one line after the end of the return (last line). Can you please help me? I want to note that I tried to copy an existing format of another function.
Thanks in advance!
name = ur"Diffusion"
nindvar = 1
equation = r"8.4*erfc(a/(2*sqrt(13.6094*x*b)))"
latexequation = r"8.4\mathrm{erfc}{\left(a/{left(2\sqrt{13.6094 x b\right)}\right)}"
def evaluate(x,a,b):
"""
"""
y = 8.4*erfc(a/(2*sqrt(13.6094*x*b)))
return y
def initialize(x,y):
"""
"""
try:
a = 74
b = 0.37
return a,b
You can't have try without except.