I am trying to make a program that will display total stock of cement, brick, spanner, mirror, and hammer. But the problem Please help me
is thsi program keeps showing me' cementinVar is not defined' but i already defined it above as (cementinVar = Tkinter.IntVar()) .
def textboxvalue2():
Total_StockIn = 0
CementIn = cementinVar.get()
HammerIn = hammerinVar.get()
SpannerIn = spannerinVar.get()
BrickIn = brickinVar.get()
MirrorIn = mirrorinVar.get()
CementOut = cementoutVar.get()
HammerOur = hammeroutVar.get()
SpannerOut = spanneroutVar.get()
BrickOut = brickoutVar.get()
MirrorOut = mirroroutVar.get()
Total_StockIn = (CementIn + HammerIn + SpannerIn + BrickIn + MirrorIn)+Total_StockIn
StockInLabel = Tkinter.Label(sub,text='The total stock in is '+str(Total_StockIn))
StockInLabel.grid(row=7, column =2)
You define cementinVar in another scope. You have two possible solutions:
Use a global variable
Use a class variable
Related
Can anyone tell me why I can only refer to the Checkbutton variable once? the important part of code is bold.
The first time that I use the variable it run, but the second, the same variable dont work. I think I tried very much but dont work!
def botao_executar():
botão_executar = comand of Button
if (pag1 <= numero_quadros):
img1 = cv.imread('imagemfinal.jpg')
novo_y_1 = int(num_novos_y*1)
crop_image_1 = img1[0:novo_y_1]
status = cv.imwrite('Desktop\ORC/crop_image1.png', crop_image_1)
q = 590
a = (q+220)
z = (q-590)
p = (q+250)
#Dimensoes_1
crop_image_1_1_dimensoes = crop_image_1[q+60:a-20, z:p]
status_dimensoes = cv.imwrite('Desktop\ORC/crop_image1.1_dimensoes.png', crop_image_1_1_dimensoes)
img_1_1_dimensoes = PIL.Image.open('Desktop\ORC/crop_image1.1_dimensoes.png')
pytesseract.pytesseract.tesseract_cmd =r'C:\Users\joaoccfaria\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
result_1_1_dimensoes = pytesseract.image_to_string(img_1_1_dimensoes, config='--psm 6 digits')
with open('abc.txt',mode ='w') as file:
file.write(result_1_1_dimensoes)
if v_dimensoes.get()> 0:
v_dimensoes.get= variable of checkbutton here it works!
print('dimensoes_1 = '+ result_1_1_dimensoes + ';')
sheet.write('A1', result_1_1_dimensoes)
else:
pass
pag2 = 2
if (pag2 <= numero_quadros):
img2 = cv.imread('imagemfinal.jpg')
novo_y_1 = int(num_novos_y*1)
crop_image_2 = img2[novo_y_1:novo_y_1*2]
status = cv.imwrite('Desktop\ORC/crop_image2.png', crop_image_2)
q = 590
a = (q+220)
z = (q-590)
p = (q+250)
#Dimensoes_2
crop_image_2_1_dimensoes = crop_image_2[q+60:a-20, z:p]
status_dimensoes = cv.imwrite('Desktop\ORC/crop_image2.1_dimensoes.png', crop_image_2_1_dimensoes)
img_2_1_dimensoes = PIL.Image.open('Desktop\ORC/crop_image2.1_dimensoes.png')
pytesseract.pytesseract.tesseract_cmd =r'C:\Users\joaoccfaria\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
result_2_1_dimensoes = pytesseract.image_to_string(img_2_1_dimensoes, config='--psm 6 digits')
with open('abc.txt',mode ='w') as file:
file.write(result_2_1_dimensoes)
if v_dimensoes.get()> 0:
here the same variable, but says that the name is not defined
print('dimensoes_2 = '+ result_2_1_dimensoes + ';')
sheet.write('A21', result_2_1_dimensoes)
else:
pass
Thanks in advance, any suggestion. Compliments.
I am trying to implement a "user-friendly" portfolio optimization program in Python.
Since I am still a beginner I did not quite manage to realize it.
The only thing the program should use as input are the stock codes.
I tried to create a mwe below:
import numpy as np
import yfinance as yf
import pandas as pd
def daily_returns(price):
price = price.to_numpy()
shift_1 = price[1:]
shift_2 = price[:-1]
return (shift_1 - shift_2)/shift_1
def annual_returns(price):
price = price.to_numpy()
start = price[0]
end = price[len(price)-1]
return (end-start)/start
def adjusting(price):
adj = len(price)
diff = adj - adjvalue
if diff != 0:
price_new = price[:-diff]
else: price_new = price
return price_new
#Minimal Reproducible Example
#getting user input
names = input('Stock codes:')
names = names.split()
a = len(names)
msft = yf.Ticker(names[0])
aapl = yf.Ticker(names[1])
#import data
hist_msft = msft.history(interval='1d',start='2020-01-01',end='2020-12-31')
hist_msft = pd.DataFrame(hist_msft,columns=['Close'])
#hist_msft = hist_msft.to_numpy()
hist_aapl = aapl.history(interval='1d',start='2020-01-01',end='2020-12-31')
hist_aapl = pd.DataFrame(hist_aapl,columns=['Close'])
#hist_aapl = hist_aapl.to_numpy()
#daily returns
aapl_daily_returns = daily_returns(hist_aapl)
aapl_daily_returns = np.ravel(aapl_daily_returns)
msft_daily_returns = daily_returns(hist_msft)
msft_daily_returns = np.ravel(msft_daily_returns)
#adjusting for different trading periods
adjvalue = min(len(aapl_daily_returns),len(msft_daily_returns))
aapl_adj = adjusting(aapl_daily_returns)
msft_adj = adjusting(msft_daily_returns)
#annual returns
aapl_ann_returns = annual_returns(hist_aapl)
msft_ann_returns = annual_returns(hist_msft)
#inputs for optimization
cov_mat = np.cov([aapl_adj,msft_adj])*252
ann_returns = np.concatenate((aapl_ann_returns,msft_ann_returns))
Now I just want the code to work with a various, unknown number of inputs. I tried reading a lot about global variables or tried to figure it out with dictionaries but couldn't really achieve any progress.
I think using the for loop can solve your problem!
...
names = input('Stock codes:')
names = names.split()
for name in names:
#analyze here
#I don't know anything about stocks so I wont write anything here
...
I am trying to return an array of constructed objects that are build on top of objects that I retrieve from some url plus another fields that I get from another url.
I have an array that consists of two arrays that each has about 8000 objects...
I have tried to make each object construction as a thread however it still takes a lot of time...
Any solution? Here is my code:
def get_all_players_full_data(ea_players_json):
all = []
ea_players_json = list(ea_players_json.values())
for i in range(len(ea_players_json)):
for player_obj in ea_players_json[i]:
all.append(player_obj)
for player_obj in range(len(all)):
all_data = []
with concurrent.futures.ThreadPoolExecutor(len(all)) as executor:
for player_data in all:
future = executor.submit(build_full_player_data_obj, player_data)
print(future.result())
all_data.append(future.result())
def build_full_player_data_obj(ea_player_data):
if ea_player_data.get("c") is not None:
player_full_name = ea_player_data.get("c")
else:
player_full_name = ea_player_data.get("f") + " " + ea_player_data.get("l")
player_id = ea_player_data.get("id")
# go to futhead to find all cards of that player
futhead_url_player_data = f'{FUTHEAD_PLAYER}{player_full_name}'
details_of_specific_player = json.loads(requests.get(futhead_url_player_data).content)
cards_from_the_same_id = []
for player_in_json_futhead in details_of_specific_player:
if player_in_json_futhead["player_id"] == player_id:
rating = player_in_json_futhead["rating"]
specific_card_id = player_in_json_futhead["def_id"]
revision = player_in_json_futhead["revision_type"]
name = player_in_json_futhead["full_name"]
nation = player_in_json_futhead["nation_name"]
position = player_in_json_futhead["position"]
club = player_in_json_futhead["club_name"]
cards_from_the_same_id.append(Player(specific_card_id, name, rating, revision, nation,
position, club))
return cards_from_the_same_id
I am trying to make a form where if I input a medicine's name, it will show the solution of the medicine serially. But it is kind of limited bythe way I'm making it like more lines I'll code more spaces they will get to have the number of feedback. It would be great if you could help me to make something short but have the infinity process like loop.
df = pd.DataFrame({'FEVER':['NAPA_PLUS','JERIN','PARASITAMOL'],
'GASTRIC':['SECLO40','SECLO20','ANTACID'],
'WATERINESS':['ORSALINE','TESTY_SALINE','HOME_MADE_SALINE']})
def word_list(text):
return list(filter(None, re.split('\W+', text)))
session = raw_input("INPUT THE NAME OF THE MEDICINES ONE BY ONE BY KEEPING SPACE:")
feedback = session
print(word_list(feedback))
dff = pd.DataFrame({'itemlist':[feedback]})
dff['1'] = dff['itemlist'].astype(str).str.split().str[0]
dff['2'] = dff['itemlist'].astype(str).str.split().str[1]
dff['3'] = dff['itemlist'].astype(str).str.split().str[2]
dff['4'] = dff['itemlist'].astype(str).str.split().str[3]
dff['5'] = dff['itemlist'].astype(str).str.split().str[4]
for pts1 in dff['1']:
pts1 = df.columns[df.isin([pts1]).any()]
for pts2 in dff['2']:
pts2 = df.columns[df.isin([pts2]).any()]
for pts3 in dff['3']:
pts3 = df.columns[df.isin([pts3]).any()]
for pts4 in dff['4']:
pts4 = df.columns[df.isin([pts4]).any()]
for pts5 in dff['5']:
pts5 = df.columns[df.isin([pts5]).any()]
This wraps your repeated code into two loops:
...
dff = pd.DataFrame({'itemlist':[feedback]})
limit = 5
for i in xrange(limit):
name = str(i+1)
dff[name] = dff['itemlist'].astype(str).str.split().str[i]
for pts in dff[name]:
pts = df.columns[df.isin([pts]).any()]
Is it possible to use a for loop to search through the text of tags that correspond to a certain phrase. I've been trying to create this loop but isn't hasn't been working. Any help is appreciated thanks! Here is my code:
def parse_page(self, response):
titles2 = response.xpath('//div[#id = "mainColumn"]/h1/text()').extract_first()
year = response.xpath('//div[#id = "mainColumn"]/h1/span/text()').extract()[0].strip()
aud = response.xpath('//div[#id="scorePanel"]/div[2]')
a_score = aud.xpath('./div[1]/a/div/div[2]/div[1]/span/text()').extract()
a_count = aud.xpath('./div[2]/div[2]/text()').extract()
c_score = response.xpath('//a[#id = "tomato_meter_link"]/span/span[1]/text()').extract()[0].strip()
c_count = response.xpath('//div[#id = "scoreStats"]/div[3]/span[2]/text()').extract()[0].strip()
info = response.xpath('//div[#class="panel-body content_body"]/ul')
mp_rating = info.xpath('./li[1]/div[2]/text()').extract()[0].strip()
genre = info.xpath('./li[2]/div[2]/a/text()').extract_first()
date = info.xpath('./li[5]/div[2]/time/text()').extract_first()
box = response.xpath('//section[#class = "panel panel-rt panel-box "]/div')
actor1 = box.xpath('./div/div[1]/div/a/span/text()').extract()
actor2 = box.xpath('./div/div[2]/div/a/span/text()').extract()
actor3 = box.xpath('./div/div[3]/div/a/span/text()').extract_first()
for x in info.xpath('//li'):
if info.xpath("./li[x]/div[1][contains(text(), 'Box Office: ')/text()]]
box_office = info.xpath('./li[x]/div[2]/text()')
else if info.xpath('./li[x]/div[1]/text()').extract[0] == "Runtime: "):
runtime = info.xpath('./li[x]/div[2]/time/text()')
Your for loop is completely wrong:
1. You're using info. but searching from the root
for x in info.xpath('.//li'):
2. x is a HTML node element and you can use it this way:
if x.xpath("./div[1][contains(., 'Box Office: ')]"):
box_office = x.xpath('./div[2]/text()').extract_first()
I think you might need re() or re_first() to match the certain phrase.
For example:
elif info.xpath('./li[x]/div[1]/text()').re_first('Runtime:') == "Runtime: "):
runtime = info.xpath('./li[x]/div[2]/time/text()')
And you need to modify your for loop, cuz the variable x in it is actually a Selector but not a number, so it's not right to use it like this: li[x].
gangabass in the last answer made a good point on this.