skip an iteration of the for loop in python - django

I need a hand, I don't understand how to fix it.
Look at the photo to better understand my speech, where the new field is populated the value of new is subtracted from the total and I don't want it to be subtracted immediately but the next round.
How can I do?
def UserAndamentoListView(request):
giorni = []
mese = []
new_user = []
tot_user = []
tot = User.objects.all().count()
for day in range(5):
giorni.append(datetime.datetime.now() - datetime.timedelta(days=day))
new = User.objects.filter(date_joined__contains = giorni[day].date())
new_user.append(new)
tot -= new.count()
tot_user.append(tot)
context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user}
return render(request, 'andamento.html', context)

Just subtract after appending the total
for day in range(5):
giorni.append(datetime.datetime.now() - datetime.timedelta(days=day))
new = User.objects.filter(date_joined__contains = giorni[day].date())
new_user.append(new)
tot_user.append(tot)
tot -= new.count()
The value of tot is changed at the end of the current loop iteration but is not used until the next trip around the loop.

Related

Django querysets to subtract items

I have two query sets to get the values for stock_in and stock_out. How do i loop to subtract stock_out from stock_in
here are the querysets
stock_in = OrderItems.objects.values('drug').annotate(
quantity_received=Sum('quantity_received'),
).order_by('drug')
stock_out = RequestItems.objects.values('drug').annotate(
quantity_received=Sum('quantity_issued')
).order_by('drug')
Approach it from the Drug model. It makes it a bit easier on the query.
Drug.objects.annotate(
stock_in=Sum('orderitems_set__quantity_received'),
stock_out=Sum('requestitems_set__quantity_issued'),
).annotate(
current_stock=F('stock_in')-F('stock_out')
)
Or you might be able to do it in one. I'm not sure.
Drug.objects.annotate(
current_stock=Sum('orderitems_set__quantity_received') - Sum('requestitems_set__quantity_issued'),
)
def stock_list(request):
stock_in = OrderItems.objects.values('drug__drugTitle','drug__drugCode', 'drug__denom_quantity').order_by('drug').annotate(quant_in=Sum('quantity_received'))
stock_out = RequestItems.objects.values('drug__drugTitle', 'drug__drugCode', 'drug__denom_quantity').order_by('drug').annotate(quant_out=Sum('quantity_issued'))
stock_available=[]
index = 0
for item in stock_out:
if item is None:
remaining_stc = stock_in[index]['quant_in']
stock_available.append({'drug__drugTitle':stock_in[index]['drug__drugTitle'],'drug__drugCode':stock_in[index]['drug__drugCode'], 'drug__denom_quantity':stock_in[index]['drug__denom_quantity'], 'quantr':remaining_stc})
else:
remaining_stc = stock_in[index]['quant_in']-stock_out[index]['quant_out']
stock_available.append({'drug__drugTitle':stock_in[index]['drug__drugTitle'],'drug__drugCode':stock_in[index]['drug__drugCode'], 'drug__denom_quantity':stock_in[index]['drug__denom_quantity'], 'quantr':remaining_stc})
index = index + 1
context = {
"stock_available":stock_available,
}
return render(request, 'stock/stock_list.html', context)

For loop in Django

I have two question. First question: Python script that shows me the precipitation for a certain period.For example, I'm getting an initial year-month and a final year-month.
Initial:
year:2000
month:3
Final
year1:2005
month:4
Now, instead of seeing:
2000/3,2000/4,2000/5,2000/6..........2005/1,2005/2,2005/3,2005/4
she works like this(look in the hooked picture):
2000/3, 2000/4, 2001/3, 2001/4........2005/3,2005/4.
I want to work for me like the first case.
def period_month_prec(year,month,year1,month1):
for i in range (year,year1+1,1):
for j in range(month,month1+1,1):
......................
Second question: How to write the output(picture) from the script in csv.fileenter image description here
This is what my views.py script looks like , which saves me only the first result:
def monthly_period(request):
if request.method == "POST" :
form = PeriodMonthlyForm(request.POST)
if form.is_valid():
data = form.cleaned_data
year = data.get('year')
month = data.get('month')
year1 = data.get('year1')
month1 = data.get('month1')
lon = data.get('lon')
lat = data.get ('lat')
inter = data.get('inter')
point = period_month_prec(year,month,year1,month1,lon,lat)
args = {'point':point}
response = HttpResponse(content_type='text/txt')
response['Content-Disposition'] = 'attachment; filename="precipitation.txt"'
writer = csv.writer(response)
writer.writerow([point])
return response
else:
form = PeriodMonthlyForm()
active_period_monthly = True
return render (request, 'carpatclimapp/home.html',{'form':form, 'active_period_monthly': active_period_monthly})
Ok, i have forms like this:
Forms
You set initial values(red color) and end interval(blue color). For this given interval, the lon and lat are defined for the point in which we want to perform interpolation. When you press the submit button, it starts with interpolation for a defined period. The loop problem is because it works only for the defined months (we see from the 2nd picture that it only works in the interval 1-6) but not for 7,8,9,10,11,12 months between these years.
Initial: year:2000, month:3
Final: year1:2001, month:4
for this she's doing it like this: 2000/3,2000/4,2001/3,2001/4
I do not want that, I want this: 2000/3,2000/4,2000/5,2000/6,2000/7.....2000/12,2001/1,2001/2,2001/3,2001/4.
this is me code :
def period_month_prec(year,month,year1,month1,lon,lat):
cnx = sqlite3.connect(DB1)
cursor = cnx.cursor()
table = 'monthly'
year = int(year)
year1 = int(year1)
month = int(month)
month1 = int(month1)
for i in range (year,year1+1,1):
for j in range(month,month1+1,1):
query = '''
SELECT dates, cell, prec FROM %s WHERE dates = "%s-%s" ;
''' % (table,i,j)
df = pd.read_sql_query(query, cnx)
tacka = '''SELECT id, lon, lat,country,altitude FROM %s;''' % 'grid1'
grid1 = pd.read_sql_query(tacka, cnx)
podaci = pd.merge(df,grid1,left_on='cell',right_on='id')
podaci_a = podaci.drop(['cell','id','country','altitude'],axis=1)
lon_n = podaci_a['lon'].values
lat_n = podaci_a['lat'].values
prec =podaci_a['prec'].values
x_masked, y_masked, prec_p = remove_nan_observations(lon_n, lat_n, prec)
xy = np.vstack([x_masked,y_masked]).T
xi = ([lon,lat])
inter_point = interpolate_to_points(xy,prec_p,xi, interp_type='linear'
return (i,j,lon,lat,inter_point)
The results that come out look like this:
loop with calculations
The second question was how to save these results(2nd picture) in the csv file, how to write correctly views.py. Currently she looks like this :
def monthly_period(request):
if request.method == "POST" :
form = PeriodMonthlyForm(request.POST)
if form.is_valid():
data = form.cleaned_data
year = data.get('year')
month = data.get('month')
year1 = data.get('year1')
month1 = data.get('month1')
lon = data.get('lon')
lat = data.get ('lat')
inter = data.get('inter')
point = period_month_prec(year,month,year1,month1,lon,lat)
args = {'point':point}
response = HttpResponse(content_type='text/txt')
response['Content-Disposition'] = 'attachment; filename="precipitation.txt"'
writer = csv.writer(response)
writer.writerow([point])
return response
else:
form = PeriodMonthlyForm()
active_period_monthly = True
return render (request, 'carpatclimapp/home.html',{'form':form, 'active_period_monthly': active_period_monthly})
I hope I'm a little clearer now

Get different result when use i iteration and np.sum function

I have a pandas Dataframe, I want to get the sum of the 'daily return' column of the data frame for every 60 days. The following is my code:
day = days() #days is a function to count business days.
for day>60:
for i in range(day-60,day):
current_x = sh600004['daily return'][i]
x_list.append(current_x)
x_sum = sum(x_list)
print x_sum
Here's what I got
To test the result, I used the following code:
y = sh600004
y.apply(lambda x: x.sum())
and I got different result.
The sum of 'daily return' column is not the same. When I print out my dataframe sh600004, I realize the data in x_sum is same as sh600004['daily return'], not the sum of it.
What do I need to do to get the sum of every 60 days of the daily return ? Can anyone help, please?
I don't know is that gonna help or not, but here's my the code I wrote so far:
#calculate daily return
daily_close = sh600004['close']
daily_pct_c = daily_close.pct_change().fillna(0)
sh600004['daily return'] = daily_pct_c
def days():
day = np.busday_count((datetime.datetime.strptime(sh600004['date'][0], '%Y/%m/%d')),pd.to_datetime(date), weekmask='1111100', holidays=holiday_list)
return day
def xn_deviation():
x_list = []
deviation_list = []
z_list = []
diff_list = []
result_list = []
day = days()
for i in range(0, 60):
current_x = sh600004['daily return'][i]
x_list.append(current_x)
x_sum = sum(x_list)
x_average = x_sum/len(x_list) #xn average
x_deviation = current_x - x_average #xn deviation
deviation_list.append(x_deviation)
dev_sum = sum(deviation_list) #calculate Z
z_list.append(dev_sum) #deviation sum list
r = max(z_list)-min(z_list) #calculate widest deviation
diff = np.square(current_x - x_average)
diff_list.append(diff)
sum_diff = sum(diff_list)
s = np.sqrt(sum_diff/len(x_list))
result_list = [r,s]
return result_list
else:
for i in range(day-60,day):
#same code as before
#loop
for date in sh600004.index:
days()
xn_deviation()

Memory Error when exporting data to csv file

Hello I was hoping someone could help me with my college coursework, I have an issue with my code. I keep running into a memory error with my data export.
Is there any way I can reduce the memory that is being used or is there a different approach I can take?
For the course work I am given a file of 300 records about customer orders from a CSV file and then I have to export the Friday records to a new CSV file. Also I am required to print the most popular method for customer's orders and the total money raised from the orders but I have an easy plan for that.
This is my first time working with CSV so I'm not sure how to do it. When I run the program it tends to crash instantly or stop responding. Once it appeared with 'MEMORY ERROR' however that is all it appeared with. I'm using a college provided computer so I am not sure on the exact specs but I know it runs 4GB of memory.
defining count occurences predefined function
def countOccurences(target,array):
counter = 0
for element in array:
if element == target:
counter= counter + 1
print counter
return counter
creating user defined functions for the program
dataInput function used for collecting data from provided file
def dataInput():
import csv
recordArray = []
customerArray = []
f = open('E:\Portable Python 2.7.6.1\Choral Shield Data File(CSV).csv')
csv_f = csv.reader(f)
for row in csv_f:
customerArray.append(row[0])
ticketID = row[1]
day, area = datasplit(ticketID)
customerArray.append(day)
customerArray.append(area)
customerArray.append(row[2])
customerArray.append(row[3])
recordArray.append(customerArray)
f.close
return recordArray
def datasplit(variable):
day = variable[0]
area = variable[1]
return day,area
def dataProcessing(recordArray):
methodArray = []
wed_thursCost = 5
friCost = 10
record = 0
while record < 300:
method = recordArray[record][4]
methodArray.append(method)
record = record+1
school = countOccurences('S',methodArray)
website = countOccurences('W',methodArray)
if school > website:
school = True
elif school < website:
website = True
dayArray = []
record = 0
while record < 300:
day = recordArray[record][1]
dayArray.append(day)
record = record + 1
fridays = countOccurences('F',dayArray)
wednesdays = countOccurences('W',dayArray)
thursdays = countOccurences('T', dayArray)
totalFriCost = fridays * friCost
totalWedCost = wednesdays * wed_thursCost
totalThurCost = thursdays * wed_thursCost
totalCost = totalFriCost + totalWedCost + totalThurCost
return totalCost,school,website
My first attempt to writing to a csv file
def dataExport(recordArray):
import csv
fridayRecords = []
record = 0
customerIDArray = []
ticketIDArray = []
numberArray = []
methodArray = []
record = 0
while record < 300:
if recordArray[record][1] == 'F':
fridayRecords.append(recordArray[record])
record = record + 1
with open('\Courswork output.csv',"wb") as f:
writer = csv.writer(f)
for record in fridayRecords:
writer.writerows(fridayRecords)
f.close
My second attempt at writing to the CSV file
def write_file(recordArray): # write selected records to a new csv file
CustomerID = []
TicketID = []
Number = []
Method = []
counter = 0
while counter < 300:
if recordArray[counter][2] == 'F':
CustomerID.append(recordArray[counter][0])
TicketID.append(recordArray[counter][1]+recordArray[counter[2]])
Number.append(recordArray[counter][3])
Method.append(recordArray[counter][4])
fridayRecords = [] # a list to contain the lists before writing to file
for x in range(len(CustomerID)):
one_record = CustomerID[x],TicketID[x],Number[x],Method[x]
fridayRecords.append(one_record)
#open file for writing
with open("sample_output.csv", "wb") as f:
#create the csv writer object
writer = csv.writer(f)
#write one row (item) of data at a time
writer.writerows(recordArray)
f.close
counter = counter + 1
#Main Program
recordArray = dataInput()
totalCost,school,website = dataProcessing(recordArray)
write_file(recordArray)
In the function write_file(recordArray) in your second attempt the counter variable counter in the first while loop is never updated so the loop continues for ever until you run out of memory.

Numerology with Python And Django

i have a function that give me the result that im expecting in console mode, but if i try to use the function with Django, the page never load and just have a loop calculating and never end.
Any idea ?
*sorry with my english
Console function (WORK GREAT):
def sum_digitos(n):
sum = 0;
while n != 0:
sum += n % 10
n /= 10
if sum > 9:
x = str(sum)
y =list(x)
sum = int(y[0]) + int(y[1])
return sum
print sum_digitos(2461978)
Django views:
def Calcular(request):
if request.method == 'POST':
form = NumerologiaForm(request.POST)
if form.is_valid():
sum = 0;
ano = str(request.POST['fecha_year'])
mes = str(request.POST['fecha_month'])
dia = str(request.POST['fecha_day'])
data = dia + mes + ano
fecha = int(data)
while fecha != 0:
f = fecha
sum += f % 10
f /= 10
if sum > 9:
x = str(sum)
y =list(x)
sum = int(y[0]) + int(y[1])
resultado = get_object_or_404(Numero,numero = sum)
return HttpResponseRedirect(resultado.get_absolute_url())
else:
form = NumerologiaForm()
return render_to_response('numerologiaForm.html',{'form':form})
Try:
f = fecha
while f!= 0:
sum += f % 10
f /= 10
if sum > 9:
x = str(sum)
y =list(x)
sum = int(y[0]) + int(y[1])
It seems you were changing f, but checking fecha for the looping.
Sanjay's answer is the correct one, and I recommend it. I just wanted to ask why you didn't just do:
from numerology import sum_digitos
def Calcular(request):
# In your code, you return HttpResponseRedirect using a nonexistent
# "resultado" variable if the form is not valid. This will raise an
# exception. I think you meant to indent "return Http..." one step more.
if request.method == 'POST':
form = NumerologiaForm(request.POST)
else:
form = NumerologiaForm()
# "or..." part of next line not needed if form.is_valid() returns
# False for a blank form.
if not form.is_valid() or form == NumerologiaForm():
return render_to_response('numerologiaForm.html', {'form': form})
ano = str(request.POST['fecha_year'])
mes = str(request.POST['fecha_month'])
dia = str(request.POST['fecha_day'])
resultado = get_object_or_404(Numero,
numero=sum_digitos(int(dia + mes + ano)))
return HttpResponseRedirect(resultado.get_absolute_url())
You had a working function in Python already... why not just import it and use it?
There's no need to go to all that work to sum the digits in that number, because the sum of the digits is num % 9. If num % 9 is zero, then the actual sum of digits is 9.
By changing your method to
def sum_digitos(n):
sum_ = n % 9
return sum_ if sum_ != 0 else 9
You will completely avoid whatever issue was happening inside your original method.
You don't say what the rest of your environment is like, but you should be using f //= 10 to ensure that you're performing integer division.