This is the model in Google App Engine:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT = db.FloatProperty()
So, mCOUNT is integer and mWEIGHT is float. I calculate the age of the item like this:
age1 = datetime.datetime.now() - rep.mDATE0
age_hour = float(age1.seconds) / 3600
rep.mWEIGHT = float((rep.mCOUNT - 1) / (age_hour + 2)**1.5)
But when I try a query like this:
QUERY = Rep.all()
QUERY.filter("mAUTHOR =", user)
QUERY.order("-mWEIGHT")
RESULTS = QUERY.fetch(10)
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
# line 103
result.mCOUNT,
))
I get a TypeError on line 103 which is
result.mCOUNT,
TypeError: a float is required
Why would mCOUNT be float? By the way, the error is raised only if the item is not in the datastore and it is written for the first time by the else clause of the if loop.
Can you help me use the correct type? Thanks for your help.
-----------------------------------------------------
EDIT
I just noticed that I had %f for string formatting for mWEIGHT and changing that to %s seems to solve the problem (but I don't know why. Is it because mWEIGHT=None?):
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
# changing %f to %s appears to solve the problem.
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT if result.mWEIGHT is not None else 0.0,
result.mWEIGHT,
result.mCOUNT,
))
And here are some values:
mUNIQUE: A | mWEIGHT: 0.299954933969 | mCOUNT: 2 |
mUNIQUE: Z | mWEIGHT: 0.0 | mCOUNT: 1 | # With answer by TokenMacGuy
mUNIQUE: R | mWEIGHT: None | mCOUNT: 1 | # with %f changed to %s
mUNIQUE: P | mWEIGHT: None | mCOUNT: 1 | # with %f changed to %s
Any suggestions how I can add rep.mWEIGHT to the else clause?
------------------------------------------------------------
The entire code is below:
K = []
s = self.request.get('sentence')
K.append(s)
K = f2.remove_empty(K[0].split('\r\n'))
UNIQUES = f2.f2(K)
COUNTS = f2.lcount(K, UNIQUES)
C_RESULT = "no results yet"
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
rep = C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
age1 = datetime.datetime.now() - rep.mDATE0
age_hour = float(age1.seconds) / 3600
rep.mWEIGHT = float((rep.mCOUNT - 1) / (age_hour + 2)**1.5)
self.response.out.write("<b>rep.UNIQUE: %s</b>: <br />"
# "rep.mCOUNT: %s <br />"
"rep.mWEIGHT: %s <br />"
# "C_RESULT: %s <br />"
# "rep: %s <br />"
# "utc_tuple: %s <br />"
# "mDATE0_epoch: %s <br />"
"rep.mDATE0: %s "
"age_hour: %s <br />"
#
% (rep.mUNIQUE,
# rep.mCOUNT,
rep.mWEIGHT,
# C_RESULT,
# rep,
# utc_tuple,
# mDATE0_epoch,
rep.mDATE0,
age_hour,
))
rep.put()
else:
rep = Rep()
rep.mCOUNT = COUNTS[i]
rep.mUNIQUE = UNIQUES[i]
rep.put()
self.response.out.write("<b>rep.UNIQUE: %s</b>: |"
"rep.mCOUNT: %s: <br />"
% (rep.mUNIQUE,
rep.mCOUNT,))
QUERY = Rep.all()
QUERY.filter("mAUTHOR =", user)
QUERY.order("-mWEIGHT")
RESULTS = QUERY.fetch(10)
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
result.mCOUNT,
))
It looks like you are occasionally not setting mWEIGHT. How about changing
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
result.mCOUNT,
))
to
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT if result.mWEIGHT is not None else 0.0,
result.mCOUNT,
))
Related
This question already has answers here:
Parse date string and change format
(10 answers)
How to convert a date string to different format [duplicate]
(2 answers)
Closed 28 days ago.
This post was edited and submitted for review 27 days ago.
I would like to create a function that will convert the date from a string variable to a date format for further processing. The problem is that I managed to isolate the fields where there is no entry "date" : [], but I can't create an if condition that would distinguish the date format string.
my code:
input: json file
{
"entries": [
{
"attributes": {
"cn": "Diana Troy",
"sn": "Troy",
"givenName": "Diana",
"sAMAccountName": "wonder-woman",
"userAccountControl": 514,
"whenCreated": "2015-09-22 10:21:02+00:00",
"whenChanged": "2023-01-11 09:33:59+00:00",
"lastLogonTimestamp": [],
"pwdLastSet": "2023-01-11 09:33:59.608543+00:00",
"accountExpires": "9999-12-31 23:59:59.999999+00:00"
},
"dn": "CN=Diana Troy,OU=Users,OU=DC-COMICS,DC=universum,DC=local"
}
]
}
code:
with open(encoded_retrieved_users, 'r', encoding="UTF-8") as file:
data = json.load(file)
retrieved_users = data['entries']
retrieved_users.sort(key=lambda d: d["attributes"]["sn"]) # sortuje po sAMAccountName
def is_value(var):
if type(var) is int:
val = var
elif type(var) is str:
val = var
else:
val = None
return val
def to_short_date_format(string_to_format):
if is_value(string_to_format) == None:
short_date = "NO DATE"
else:
short_date = string_to_format
return short_date
for user in retrieved_users:
attributes = user['attributes']
userAccountControl = is_value(attributes['userAccountControl'])
whenCreated = to_short_date_format(attributes['whenCreated'])
whenChanged = to_short_date_format(attributes['whenChanged'])
lastLogonTimestamp = to_short_date_format(attributes['lastLogonTimestamp'])
pwdLastSet = to_short_date_format(attributes['pwdLastSet'])
accountExpires = to_short_date_format(attributes['accountExpires'])
print("userAccountControl | " + str(userAccountControl) + " | " + str(type(userAccountControl)))
print("whenCreated | " + whenCreated + " | " + str(type(whenCreated)))
print("whenChanged | " + whenChanged + " | " + str(type(whenChanged)))
print("lastLogonTimestamp | " + str(lastLogonTimestamp) + " | " + str(type(lastLogonTimestamp)))
print("pwdLastSet | " + str(pwdLastSet) + " | " + str(type(pwdLastSet)))
print("accountExpires | " + accountExpires + " | " + str(type(accountExpires)))
print("----------------------------------")
output:
wonder-woman
userAccountControl | 514 | <class 'int'>
whenCreated | 2015-09-22 10:21:02+00:00 | <class 'str'>
whenChanged | 2023-01-11 09:33:59+00:00 | <class 'str'>
lastLogonTimestamp | NO DATE | <class 'str'>
pwdLastSet | 2023-01-11 09:33:59.608543+00:00 | <class 'str'>
accountExpires | 9999-12-31 23:59:59.999999+00:00 | <class 'str'>
----------------------------------
what i would like to get:
def to_short_date_format(string_to_format):
if is_value(string_to_format) == None:
short_date = "NO DATE"
else:
if string_to_format == <string format %Y-%m-%d %H:%M:%S%z>
dt = datetime.strptime(string_to_format, '%Y-%m-%d %H:%M:%S%z')
short_date = dt.strftime('%Y-%m-%d')
elif string_to_format == <string format %Y-%m-%d %H:%M:%S.%f%z>
dt = datetime.strptime(string_to_format, '%Y-%m-%d %H:%M:%S.%f%z')
short_date = dt.strftime('%Y-%m-%d')
return short_date
output:
wonder-woman
userAccountControl | 514
whenCreated | 2015-09-22
whenChanged | 2023-01-11
lastLogonTimestamp | NO DATE
pwdLastSet | 2023-01-11
accountExpires | 9999-12-31
----------------------------------
I was able to get the output by reusing your snippet. Minor catch is that the date format that you were trying to extract was wrong :
my_date = "2013-06-10 11:50:16+00:00"
# print(my_date)
# print(type(my_date))
from datetime import datetime
dt =datetime.strptime(my_date, '%Y-%m-%d %H:%M:%S%z')
print(dt)
dt_new = dt.strftime('%Y-%m-%d')
print(dt_new)
Output:
So I am trying to make a program that take in input for a flight, and stores it in arrays based on each type of input. Here are the arrays that I use to do this:
airline = []
flightNumbers = []
destination = []
gate = []
status = []
Here is the issue that I am having. After the user goes through and adds 1 flight, I want the program to print a flight status board in the console. For example if I enter:
"Delta", "Dl1480", "Atlanta", "E11", "Ontime"
"American", "AA367", "New York City", "H10", "Delayed"
"United", "UA3411", "Louisville, KY", "F25", "Cancelled"
this is what I want to see output by the program:
airline: | flight number: | destination: | gate: | status:
--------------------------------------------------------------------
Delta | DL1480 | Atlanta | E11 | Ontime
American | AA367 | New York City | H10 | Delayed
United | UA3417 | Louisville,KY | F25 | Cancelled
Here is what I tried to use to get this to print:
def showAll(self):
print("Airline | Flight Number | Destination | Gate | Status")
x = 0
while x < len(a.airline):
print(a.airline + [" | "] + a.flightNumbers + [" | "] + a.destination + [" | "] + a.gate + [" | "]+ a.status + ["\n"])
x += 1
but I get this as output if I enter 2 random entries:
Airline | Flight Number | Destination | Gate | Status
['delta', 'delta', ' | ', '001', '002', ' | ', 'Los angeles, ca', 'atlanta', ' | ', 'a1', 'a3', ' | ', 'ontime', 'ontime', '\n']
['delta', 'delta', ' | ', '001', '002', ' | ', 'Los angeles, ca', 'atlanta', ' | ', 'a1', 'a3', ' | ', 'ontime', 'ontime', '\n']
Can some suggest a way I can fix this, or a better way of going about this entirely? Here is the code for the entire program:
class FSB:
# arrays to store flight information
airline = []
flightNumbers = []
destination = []
gate = []
status = []
input = ""
def addFlight(self):
while input != "bye":
# get inputs
air = input("Enter an airline name >> ")
fn = input("Enter a flight number >> ")
dest = input("Enter a destination >> ")
g = input("Enter a gate number >> ")
stat = input("Enter a flight status >> ")
self.air = air
self.fn = fn
self.dest = dest
self.g = g
self.stat = stat
# add inputs to appropiate arrays
a.airline.append(self.air)
a.flightNumbers.append(self.fn)
a.destination.append(self.dest)
a.gate.append(self.g)
a.status.append(self.stat)
print("Data stored sucessfully.\n")
a.showAll()
def showAll(self):
print("Airline | Flight Number | Destination | Gate | Status")
x = 0
while x < len(a.airline):
print(a.airline + [" | "] + a.flightNumbers + [" | "] + a.destination + [" | "] + a.gate + [" | "]+ a.status + ["\n"])
x += 1
go = input("To add a new entry, enter 1.\nTo reprint list, enter 2.\nTo exit, enter 3.\n")
if go == "1":
a.addFlight()
elif go == "2":
for x in range(1,26):
print(" ")
a.showAll()
elif go == "3":
exit()
if __name__ == "__main__":
a = FSB()
a.addFlight()
You're trying to concatenate a string "|" to your list. Please try doing ["|"]instead.
I ended up iterating through each array manually, and this is what I got:
def showAll(self):
print("Airline\t\t\t" +"| Flight Number\t\t" +"| Destination\t\t" +"| Gate \t\t" +"| Status")
for x in range(len(a.airline)):
print("-------------------------------------------------------------------------------------------------------------------")
print(str(a.airline[x] + "\t\t") + str(a.flightNumbers[x] + "\t\t") + str(a.destination[x] + "\t\t\t\t") + str(a.gate[x] + "\t\t") + str(a.status[x]))
Thank you to everyone who suggested an answer, I appreciate it!
I want to capture the sensor data through thingspeak.
I used the url provided with the api key in the browser:
http://api.thingspeak.com/update?key=MYKEY&field1=25&field2=75
I expect it will return field1 and field2, but the result below shows only the value of field1.
"channel":{
"id":202242,
"name":"DHT11",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Temperature ( degC ) 1",
"field2":"Humidity ( % )",
"created_at":"2016-12-11T17:16:21Z",
"updated_at":"2016-12-11T18:12:00Z",
"last_entry_id":12
},
"feeds":[
{
"created_at":"2016-12-11T18:12:00Z",
"entry_id":12,
"field1":25
}
]
What step have I missed?
Try this approach:
Here you make request using APIs. You will find various API requests here.
import urllib2
import json
import time
READ_API_KEY=' '
CHANNEL_ID= ' '
while True:
TS = urllib2.urlopen("http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s" \
% (CHANNEL_ID,READ_API_KEY))
response = TS.read()
data=json.loads(response)
a = data['created_at']
b = data['field1']
c = data['field2']
d = data['field3']
print a + " " + b + " " + c + " " + d
time.sleep(5)
TS.close()
I am working on a code which was developed using gurobipy, the objective is to integrate Dask package into it.The purpose is to run the code on a larger randomly generated dataset.
Below is the code and the closet I have come to is the code below this code. I am kind of struggling to finish it. I can't figure out how and where to input the Dask package.
import numpy as np
import gurobipy as gbp
import time
import dask.array as da
def GuTransProb():
t1 = time.time()
Demand
# 1000x1000
Cij = np.random.randint(100, 1000, 250000)
Cij = Cij.reshape(500,500)
print Cij
# Supply
Si = np.random.randint(500, 2000, 500)
Si = Si.reshape(500,1)
SiSum = np.sum(Si)
print SiSum
# Demand
Dj = np.sort(Si, axis=None)
DjSum = np.sum(Dj)
client_nodes = range(len(Cij))
print client_nodes
# 2. Create Model, Set MIP Focus, Add Variables, & Update Model
m = gbp.Model(' -- The Transportation Problem -- ')
# Set MIP Focus to 2 for optimality
gbp.setParam('MIPFocus', 2)
client_var = []
for orig in client_nodes:
client_var.append([])
for dest in client_nodes:
client_var[orig].append(m.addVar(vtype=gbp.GRB.CONTINUOUS,
obj=Cij[orig][dest],
name='x'+str(orig+1)+'_'+str(dest+1)))
print client_var
# Update Model Variables
m.update()
# 3. Set Objective Function
m.setObjective(gbp.quicksum(Cij[orig][dest]*client_var[orig][dest]
for orig in client_nodes for dest in client_nodes),
gbp.GRB.MINIMIZE)
# 4. Add Constraints
# Add Supply Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[dest][orig]
for dest in client_nodes) - Si[orig] == 0,
'Supply_Constraint_%d' % orig)
# Add Demand Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[orig][dest]
for dest in client_nodes) - Dj[orig] == 0,
'Demand_Constraint_%d' % orig)
# 5. Optimize and Print Results
try:
m.optimize()
except Exception as e:
print e
t2 = time.time()-t1
print '*****************************************************************************************'
print ' | From SUPPLY Facility to DEMAND Facility x(Si)_(Dj) shipping # of units '
print ' | ↓ ↓ ↓↓ ↓↓'
selected = []
for v in m.getVars():
if v.x > 0:
var = '%s' % v.VarName
value = '%i' % v.x
selected.append(v.x)
print ' | ', var, '_____ Units: ' ,value
print ' | Selected Facility Locations --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ '
print ' | Candidate Facilities [p] ------------ ', len(selected)
print ' | Supply Sum -------------------------- ', SiSum
print ' | Demand Sum -------------------------- ', DjSum
val = m.objVal
print ' | Objective Value --------------------- ', int(val)
print ' | Real Time to Optimize (sec.) -------- ', t2
print '*****************************************************************************************'
print ' -- The Transportation Problem --'
m.write('path.lp')
try:
GuTransProb()
except Exception as e:
print e
import numpy as np
import gurobipy as gbp
import time
import dask.array as da
# 500x500
Cij = np.random.randint(100, 1000, 250000)
print Cij
Cij = Cij.reshape(500,500)
print Cij
Cij = da.from_array(Cij, chunks=(1000, 1000))
print Cij
# Supply
#Si = np.random.randint(500, 2000, 500)
#Si = Si.reshape(500,1)
#Si = da.from_array(Si, chunks=(100, 100))
Si = np.random.randint(500, 2000, 500)
print Si
Si = Si.reshape(500,1)
print Si
Si = da.from_array(Si, chunks=(1000, 1000))
print Si
SiSum = Si.sum()
print SiSum
# Demand
Dj = np.sort(Si, axis=None)
print Dj
DjSum = np.sum(Dj)
print DjSum
client_nodes = range(len(Cij))
print client_nodes
# 2. Create Model, Set MIP Focus, Add Variables, & Update Model
m = gbp.Model(' -- The Transportation Problem -- ')
# Set MIP Focus to 2 for optimality
gbp.setParam('MIPFocus', 2)
client_var = []
for orig in client_nodes:
client_var.append([])
for dest in client_nodes:
client_var[orig].append(m.addVar(vtype=gbp.GRB.CONTINUOUS,
obj=Cij[orig][dest],
name='x'+str(orig+1)+'_'+str(dest+1)))
print client_var
# Update Model Variables
m.update()
# 3. Set Objective Function
m.setObjective(gbp.quicksum(Cij[orig][dest]*client_var[orig][dest]
for orig in client_nodes for dest in client_nodes),
gbp.GRB.MINIMIZE)
# 4. Add Constraints
# Add Supply Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[dest][orig]
for dest in client_nodes) - Si[orig] == 0,
'Supply_Constraint_%d' % orig)
# Add Demand Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[orig][dest]
for dest in client_nodes) - Dj[orig] == 0,
'Demand_Constraint_%d' % orig)
# 5. Optimize and Print Results
try:
m.optimize()
except Exception as e:
print e
t2 = time.time()-t1
print '*****************************************************************************************'
print ' | From SUPPLY Facility to DEMAND Facility x(Si)_(Dj) shipping # of units '
print ' | ↓ ↓ ↓↓ ↓↓'
selected = []
for v in m.getVars():
if v.x > 0:
var = '%s' % v.VarName
value = '%i' % v.x
selected.append(v.x)
print ' | ', var, '_____ Units: ' ,value
print ' | Selected Facility Locations --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ '
print ' | Candidate Facilities [p] ------------ ', len(selected)
print ' | Supply Sum -------------------------- ', SiSum
print ' | Demand Sum -------------------------- ', DjSum
val = m.objVal
print ' | Objective Value --------------------- ', int(val)
print ' | Real Time to Optimize (sec.) -------- ', t2
print '*****************************************************************************************'
print ' -- The Transportation Problem --'
m.write('path.lp')
try:
GuTransProb()
except Exception as e:
print e
I would like to parse declarations using pyparsing in a C-like source (GLSL code) such that I get a list of (type, name, value).
For example:
int a[3];
int b=1, c=2.0;
float d = f(z[2], 2) + 3*g(4,a), e;
Point f = {1,2};
I would like to obtain something like:
[ ('int', 'a[3]', ''),
('int', 'b', '1'),
('int', 'c', '2.0'),
('float', 'd', 'f(z[2], 2) + 3*g(4,a)'),
('float', 'e', ''),
('Point', 'f', '{1,2}') ]
I've played with Forward() and operatorPrecedence() to try to parse the rhs expression but I suspect it is not necessary in my case.
So far I have:
IDENTIFIER = Regex('[a-zA-Z_][a-zA-Z_0-9]*')
INTEGER = Regex('([+-]?(([1-9][0-9]*)|0+))')
EQUAL = Literal("=").suppress()
SEMI = Literal(";").suppress()
SIZE = INTEGER | IDENTIFIER
VARNAME = IDENTIFIER
TYPENAME = IDENTIFIER
VARIABLE = Group(VARNAME.setResultsName("name")
+ Optional(EQUAL + Regex("[^,;]*").setResultsName("value")))
VARIABLES = delimitedList(VARIABLE.setResultsName("variable",listAllMatches=True))
DECLARATION = (TYPENAME.setResultsName("type")
+ VARIABLES.setResultsName("variables", listAllMatches=True) + SEMI)
code = """
float a=1, b=3+f(2), c;
float d=1.0, e;
float f = z(3,4);
"""
for (token, start, end) in DECLARATION.scanString(code):
for variable in token.variable:
print token.type, variable.name, variable.value
but the last expression (f=z(3,4)) is not parsed because of the ,.
There is a C struct parser on the pyparsing wiki that might give you a good start.
This seems to work.
IDENTIFIER = Word(alphas+"_", alphas+nums+"_" )
INT_DECIMAL = Regex('([+-]?(([1-9][0-9]*)|0+))')
INT_OCTAL = Regex('(0[0-7]*)')
INT_HEXADECIMAL = Regex('(0[xX][0-9a-fA-F]*)')
INTEGER = INT_HEXADECIMAL | INT_OCTAL | INT_DECIMAL
FLOAT = Regex('[+-]?(((\d+\.\d*)|(\d*\.\d+))([eE][-+]?\d+)?)|(\d*[eE][+-]?\d+)')
LPAREN, RPAREN = Literal("(").suppress(), Literal(")").suppress()
LBRACK, RBRACK = Literal("[").suppress(), Literal("]").suppress()
LBRACE, RBRACE = Literal("{").suppress(), Literal("}").suppress()
SEMICOLON, COMMA = Literal(";").suppress(), Literal(",").suppress()
EQUAL = Literal("=").suppress()
SIZE = INTEGER | IDENTIFIER
VARNAME = IDENTIFIER
TYPENAME = IDENTIFIER
OPERATOR = oneOf("+ - * / [ ] . & ^ ! { }")
PART = nestedExpr() | nestedExpr('{','}') | IDENTIFIER | INTEGER | FLOAT | OPERATOR
EXPR = delimitedList(PART, delim=Empty()).setParseAction(keepOriginalText)
VARIABLE = (VARNAME("name") + Optional(LBRACK + SIZE + RBRACK)("size")
+ Optional(EQUAL + EXPR)("value"))
VARIABLES = delimitedList(VARIABLE.setResultsName("variables",listAllMatches=True))
DECLARATION = (TYPENAME("type") + VARIABLES + SEMICOLON)
code = """
int a[3];
int b=1, c=2.0;
float d = f(z[2], 2) + 3*g(4,a), e;
Point f = {1,2};
"""
for (token, start, end) in DECLARATION.scanString(code):
vtype = token.type
for variable in token.variables:
name = variable.name
size = variable.size
value = variable.value
s = "%s / %s" % (vtype,name)
if size: s += ' [%s]' % size[0]
if value: s += ' / %s' % value[0]
s += ";"
print s