I have another program which is meant to get information and then write it into a separate text doc. For this program, I want to take the data on the text doc and format it into an output. I have managed to get the formatting correct as well as the loop to read the information correctly but am struggling to get three more variables: 1) Find the total amount due between all employees added together. 2) Find the total amount of hours all the employees worked added. 3) Find the average hours worked per week. I cannot figure out how to get these variables as the information from the text doc must be in string format (to my knowledge), and i need them to be in float to do the calculations.
Thanks for any help in advance!
def main():
employeeCount = 0
infile = open("BillingTEST.txt","r")
print("Employee Name\t\t" +
"Rate\t" +
"Week 1\t" +
"Week 2\t" +
"Week 3\t" +
"Week 4\t" +
"Hours\t" + "Total")
name = readAsString(infile)
while name != "":
employeeCount += 1
rate = readAsFloat(infile)
week1 = readAsFloat(infile)
week2 = readAsFloat(infile)
week3 = readAsFloat(infile)
week4 = readAsFloat(infile)
empHours = week1+week2+week3+week4
empMoney = empHours * rate
print(name + "\t\t\t$" +
str(rate)+ "\t" +
str(week1)+"\t" +
str(week2)+"\t" +
str(week3)+"\t" +
str(week4)+"\t" +
str(empHours)+"\t" +
str(empMoney))
name = readAsString(infile)
print("\nTotal Billable Due:\t"+
"\nTotal Billable Hours:"+
"\nAverage Billable Hours:\t"+
"\nEmployee Count: ",employeeCount)
def readAsString(file):
return file.readline().rstrip("\n")
def readAsFloat(file):
return float(file.readline().rstrip("n"))
main()
Related
I wrote some codes trying to let the user be able to check the percentage of the money they spent(compared to the money they earned). Almost every step perform normally, until the final part.
a_c[('L'+row_t)].value return:
=<Cell 'Sheet1'.B5>/<Cell 'Sheet1'.J5>
yet I hope it should be some value.
Code:
st_column = st_column_r.capitalize()
row_s = str(a_c.max_row)
row_t = str(a_c.max_row + 1)
row = int(row_t)
a_c[('J'+row_t)] = ('=SUM(I2,J'+row_s+')') #總收入
errorprevention = a_c[('J'+row_t)].value
a_c[(st_column+row_t)] = ('=SUM('+(st_column+'2')+','+(st_column+row_s)+')')
a_c['L'+row_t].number_format = FORMAT_PERCENTAGE_00
if errorprevention != 0:
a_c[('L'+row_t)] = ('='+str(a_c[(st_column+row_t)])+'/'+str(a_c[('J'+row_t)]))
print('過往支出中,'+inputtype[st_column]+'類別佔總收入的比率為:'+a_c[('L'+row_t)].value)
Try changing the formula creation to;
a_c[('L' + row_t)].value = '=' + a_c[(st_column + row_t)].coordinate + '/' + a_c[('J' + row_t)].coordinate
or use an f string
a_c[('L' + row_t)].value = f"={a_c[(st_column + row_t)].coordinate}/{a_c[('J' + row_t)].coordinate}"
I am trying to use 'for loop' to write to a file in python dynamically, but I do not know how to calculate to write dynamically. I would appreciate if I get some help on this.
def earnings(name, age, salary):
AnnualRate = 0.05
outFile = open('yearly_earnings.txt', 'w')
outFile.write('Prepared by: Amornchot Singh')
outFile.write('Age Salary Total')
n = 26
for n in range(66):
ageLimit = 65
i = 26
totalEarned = 0
for i in range(ageLimit+1):
totalEarned += salary * (1+AnnualRate)
print('summary for ' + name)
print('Starting salary at age ' + age + ' was ' + salary)
print('Salary increases were 5.0% per year')
print('Total accumulated earnings by age 65 is {:,.2f}'.format(totalEarned))
print("To view yearly data go to 'yearly_earnings.txt'")
print("'Thank you for using the earnings() function.'")
First of all remove all redundant lines of code
Call the function
Don't forget to close the file after writing something, otherwise it
will not save the data in your file
Python don't allow to add integer with string so convert the integer
into str before concatenating
print('Starting salary at age ' + str(age) + ' was ' + str(salary))
Here is full code
def earnings(name, age, salary):
AnnualRate = 0.05
outFile = open('yearly_earnings.txt', 'w')
outFile.write('Prepared by: Amornchot Singh')
outFile.write('Age Salary Total')
ageLimit = 65
i = 26
totalEarned = 0
for i in range(ageLimit+1):
totalEarned += salary * (1+AnnualRate)
outFile.close()
print('summary for ' + name)
print('Starting salary at age ' + str(age) + ' was ' + str(salary))
print('Salary increases were 5.0% per year')
print('Total accumulated earnings by age 65 is {:,.2f}'.format(totalEarned))
print("To view yearly data go to 'yearly_earnings.txt'")
print("'Thank you for using the earnings() function.'")
earnings("Tariq", 20, 500000)
I've built a program to fill up a databank and, by the time, it's working. Basically, the program makes a request to the app I'm using (via REST API) returns the data I want and then manipulate to a acceptable form for the databank.
The problem is: the GET method makes the algorithm too slow, because I'm acessing the details of particular entries, so for each entry I have to make 1 request. I have something close to 15000 requests to do and each row in the bank is taking 1 second to be made.
Is there any possible way to make this requests faster? How can I improve the perfomance of this method? And by the way, any tips to measure the perfomance of the code?
Thanks in advance!!
here's the code:
# Retrieving all the IDs I want to get the detailed info
abc_ids = serializers.serialize('json', modelExample.objects.all(), fields=('id'))
abc_ids = json.loads(abc_ids)
abc_ids_size = len(abc_ids)
# Had to declare this guys right here because in the end of the code I use them in the functions to create and uptade the back
# And python was complaining that I stated before assign. Picked random values for them.
age = 0
time_to_won = 0
data = '2016-01-01 00:00:00'
# First Loop -> Request to the detailed info of ABC
for x in range(0, abc_ids_size):
id = abc_ids[x]['fields']['id']
url = requests.get(
'https://api.example.com/v3/abc/' + str(
id) + '?api_token=123123123')
info = info.json()
dealx = dict(info)
# Second Loop -> Picking the info I want to uptade and create in the bank
for key, result in dealx['data'].items():
# Relevant only for ModelExample -> UPTADE
if key == 'age':
result = dict(result)
age = result['total_seconds']
# Relevant only For ModelExample -> UPTADE
elif key == 'average_time_to_won':
result = dict(result)
time_to_won = result['total_seconds']
# Relevant For Model_Example2 -> CREATE
# Storing a date here to use up foward in a datetime manipulation
if key == 'add_time':
data = str(result)
elif key == 'time_stage':
# Each stage has a total of seconds that the user stayed in.
y = result['times_in_stages']
# The user can be in any stage he want, there's no rule about the order.
# But there's a record of the order he chose.
z = result['order_of_stages']
# Creating a list to fill up with all stages info and use in the bulk_create.
data_set = []
index = 0
# Setting the number of repititions base on the number of the stages in the list.
for elemento in range(0, len(z)):
data_set_i = {}
# The index is to define the order of the stages.
index = index + 1
for key_1, result_1 in y.items():
if int(key_1) == z[elemento]:
data_set_i['stage_id'] = int(z[elemento])
data_set_i['index'] = int(index)
data_set_i['abc_id'] = id
# Datetime manipulation
if result_1 == 0 and index == 1:
data_set_i['add_date'] = data
# I know that I totally repeated the code here, I was trying to get this part shorter
# But I could not get it right.
elif result_1 > 0 and index == 1:
data_t = datetime.strptime(data, "%Y-%m-%d %H:%M:%S")
data_sum = data_t + timedelta(seconds=result_1)
data_sum += timedelta(seconds=3)
data_nova = str(data_sum.year) + '-' + str(formaters.DateNine(
data_sum.month)) + '-' + str(formaters.DateNine(data_sum.day)) + ' ' + str(
data_sum.hour) + ':' + str(formaters.DateNine(data_sum.minute)) + ':' + str(
formaters.DateNine(data_sum.second))
data_set_i['add_date'] = str(data_nova)
else:
data_t = datetime.strptime(data_set[elemento - 1]['add_date'], "%Y-%m-%d %H:%M:%S")
data_sum = data_t + timedelta(seconds=result_1)
data_sum += timedelta(seconds=3)
data_nova = str(data_sum.year) + '-' + str(formaters.DateNine(
data_sum.month)) + '-' + str(formaters.DateNine(data_sum.day)) + ' ' + str(
data_sum.hour) + ':' + str(formaters.DateNine(data_sum.minute)) + ':' + str(
formaters.DateNine(data_sum.second))
data_set_i['add_date'] = str(data_nova)
data_set.append(data_set_i)
Model_Example2_List = [Model_Example2(**vals) for vals in data_set]
Model_Example2.objects.bulk_create(Model_Example2_List)
ModelExample.objects.filter(abc_id=id).update(age=age, time_to_won=time_to_won)
if the bottleneck is in your network request, there isn't much you can do except to perhaps use gzip or deflate but with requests ..
The gzip and deflate transfer-encodings are automatically decoded for
you.
If you want to be doubly sure, you can add the following headers to the get request.
{ 'Accept-Encoding': 'gzip,deflate'}
The other alternative is to use threading and have many requests operate in parrallel, a good option if you have lot's of bandwidth and multiple cores.
Lastly, there are lots of different ways to profile python including with cprofile + kcachegrind combo.
If I call this pathon function from console, the dates are calculated as expected:
def get_nearest_date(day, month):
"""Gets nearest date in the future for provided day and month."""
today = date.today()
res = ""
if (today.month < month):
res = str(day) + "." + str(month) + "." + str(today.year)
elif ((today.month == month) & (today.day < day)):
res = str(day) + "." + str(month) + "." + str(today.year)
else:
res = str(day) + "." + str(month) + "." + str((today.year + 1))
return res
for example:
print get_nearest_date(1, 1)
print get_nearest_date(1, 12)
returns
1.1.2016
1.12.2015
But if I use this function as custom keyword in a Robot Framework testcase like this
Bla
${d} = Get Nearest Date 1 1
Log To Console ${d}
${d} = Get Nearest Date 1 12
Log To Console ${d}
it prints
Bla
1.1.2015
1.12.2015
which is wrong (first date should be 2016). Why is this?
It took me some time to realise that in RF the parameters passed to my custom keyword
${d} = Get Nearest Date 1 1
are actually strings. Passing number variables solves this issue:
${d} = Get Nearest Date ${1} ${1}
After hours and hours of looking around and reading documents, I have to call for help and sanity. I'm no python expert or even HTML expert, so I'd appreciate every small bit of help that I can get.
I can pay for a little time if needed...
What I'm trying to do is:
Two webpages. One is in my server and one isn't. The one that isn't in my server (order.asp), has this line:
<FONT CLASS="fv">Estimated Weight of Order:</FONT></TD><TD ALIGN="RIGHT"><FONT CLASS="fv">XX.XXoz XX.XXg</FONT>
I need something that I can put in my server, queries the weight from the page that isn't on my server (order.asp page) and matches the weight with a shipping price that I would have on my page (as a table or maybe with ifs).
There will be different order pages (order1.asp order2.asp order3.asp) with different weights. The script or whatever should do that for ea. wpage.
Here's a flowchart I just made to help understand:
http://www.gliffy.com/go/publish/image/5123674/L.png
A very helpful user already gave me this piece of code:
html = open("html.txt").read()
out = open("foundWeights.txt", "w")
#split html on order number
legoOrders = html.split("Order #")
for order in legoOrders[1:]:
print order
orderNumber = order.split("<")[0]
weightString = order.split('Estimated Weight of Order:</FONT></TD><TD ALIGN="RIGHT"><FONT CLASS="fv">')[1]
splitWeightString = weightString.split(' ')
splitStringFinal = splitWeightString[1].split("<")
grams = splitStringFinal[0]
ozs = weightString.split(' ')[0]
out.write(str(orderNumber) + "\t" + str(grams) + "\t" + str(ozs) + "\n"
Which pulls out the order number, and weight in ozs and grams.
What I don't know how to do is, having a table of shipping prices and weight ranges, match that weight to a shipping price, pull the shipping price and... well, do some things with it.
Ideally, if I knew how to do that (I don't know nothing in python, but I do know programming basics and C), I could pull the order total too, sum the order total and the shipping price, and FINALLY get a grand total.
I hope I made it clear.
All the best,
Gerald
This is how the page order.asp will look like (varying the weight and order total numbers):
http://pastebin.com/uH18CF5k
Getting there slowly. I added this to your code #duhaime
#get Shipping Range
test = "B"
if ( 0 < grams < 100 ):
test = "A"
if ( 100 < grams < 500):
test = "A"
Along with the str(test) in the out.write.
However, it prints a B when I run it, but it should print an A. Know what's wrong?
Thanks again for your feedback, #Brick Top. This code pulls down the Order Number, Grand Total, Order Total, Shipping Cost, Weight in Grams, and Weight in Ozs from the html, and writes them to a tab-separated text file that you can open and easily review in Excel.
EDIT: The script also calculates the shipping class, based on the weight of the order in grams. The Shipping Class is indicated in the final column of the out file:
from decimal import *
html = open("html.txt").read()
out = open("legoShipping.txt", "w")
out.write("Order Number" + "\t" +
"Grand Total (currency)" + "\t" +
"Order Total (currency)" + "\t" +
"Shipping Cost (currency)" + "\t" +
"Order Weight (grams)" + "\t" +
"Order Weight (oz.)" + "\t" +
"Shipping Class" + "\n")
#split html on order number
legoOrders = html.split("Order #")
for order in legoOrders[1:]:
orderNumber = order.split("<")[0]
#get Grand Total
grand = order.split("<TD>Grand Total:</TD>")[1].split('<TD ALIGN="RIGHT"><B>')[1].split("<")[0].split(' ')
grandCurrency = grand[0]
grandTotal = grand[1]
#get Order Total
orderTotalAndCurrency = order.split('<TD>Order Total:</TD>')[1].split('<TD ALIGN="RIGHT">')[1].split("<")[0].split(' ')
orderCurrency = orderTotalAndCurrency[0]
orderTotal = orderTotalAndCurrency[1]
#get Shipping Cost
shipping = order.split("<TD>Shipping:</TD>")[1].split('<TD ALIGN="RIGHT">')[1].split("<")[0].split(' ')
shippingCurrency = shipping[0]
shippingCost = shipping[1]
#get Weights
weightString = order.split('Estimated Weight of Order:</FONT></TD><TD ALIGN="RIGHT"><FONT CLASS="fv">')[1]
splitWeightString = weightString.split(' ')
splitStringFinal = splitWeightString[1].split("<")
grams = splitStringFinal[0]
ozs = weightString.split(' ')[0]
#convert grams to mathematical value
gramsValue = Decimal(grams[:-1])
#create default shipping class value. Set it to ""
shippingClass = ""
if gramsValue > 0:
if gramsValue < 100:
shippingClass = "A"
if gramsValue >= 100:
if gramsValue < 200:
shippingClass = "B"
out.write(str(orderNumber) + "\t" +
str(grandTotal) + " (" + str(grandCurrency) + ")" + "\t" +
str(orderTotal) + " (" + str(orderCurrency) + ")" + "\t" +
str(shippingCost) + " (" + str(shippingCurrency) + ")" + "\t" +
str(grams) + "\t" +
str(ozs) + "\t" +
str(shippingClass) + "\n")
Output in OpenOffice Calc: