Is a "Try / Except ValueError UNLESS" possible? - exception

I'm new to python and have been trying like hell for the past few hours to figure out how to get this to work properly...
It's very simple code I'm sure, but I'm just not getting it.
It should be pretty self-explanatory below in the code, but basically I'm asking a user to input the date of an event as an 'int' and if it's not a number, then ask them to try again... UNLESS it's a "?"
while True:
date = None
street = str(input('Name of street?: ').title())
city = str(input("In what city?: ").title())
while True:
try:
year = int(input("Date of event? (or '?'): "))
if date == "?":
break
except Exception:
print("That's not a date, try again!")
continue
break
It seems that it's not even getting to see IF because it gets caught by the 'except' before it can.

If you're going to display help or something when a '?' is input, then just call the function to display the help where you have the break currently.
if date == "?":
display_help()
continue
Then, split reading the input and processing it into two steps.
in = input("Date of event? (or '?'): ")
if in == "?":
display_help()
continue
year = int(in)
Also, you ask for a date but then assume that a year is entered, I'd be more explicit in your promt.
"Please enter the year of the event, ex: 1998"
or whatever form you actually want it in.

Trying using a valueError exception. Also I think in your post you mentioned you wanted to enter a date as integer, so I replaced year with the date. If you wanted the year to be an integer you can replace the variable date with year. If you wanted to the user to enter a year, day and month then this program needs to be redesigned a bit.
date = None
street = str(input('Name of street?: ').title())
city = str(input("In what city?: ").title())
while True:
date = input("Date of event? (or '?'): ")
if date == "?":
break
else:
try:
date = int(date)
except ValueError:
print("That's not a date, try again!")
continue
break

Related

How do I query for the last 30 days of data in Power Query using JSON?

I would like to request the last 30 days of CrewHu Import data from today's date in this query. At the moment it is just set to get everything greater than the 25th September 2022 but I want to change this to be a dynamic value. Has anyone else had this problem / knows of a workaround?
let
Source = Json.Document(Web.Contents("https://api.crewhu.com/api" & "/v1/survey?query={""_updated_at"":{""$gte"":""2022-09-25T00:00:00.000Z""}}", [Headers=[X_CREWHU_APITOKEN="xxxxxxxxxxx"]])),
I've tried:
OneMonthAgo = Text.Replace(Text.Start (Text.From(Date.AddDays(DateTime.LocalNow(),-30)),10),"/","-") & "T00:00:00.000Z",
And calling this as a variable but because the string does not come with quotation marks it gives a syntax error when the variable is called in the 'Source = ' line.
Well, first you want
= Date.ToText(Date.From(Date.AddDays(DateTime.LocalNow(),-30)), [Format="yyyy-MM-dd"])& "T00:00:00.000Z"
since that returns 2022-09-28T00:00:00.000Z while yours returns 9-28-2022 T00:00:00.000Z which does not seem to be the original format
then try out this, which I cant test
let variable = Date.ToText(Date.From(Date.AddDays(DateTime.LocalNow(),-30)), [Format="yyyy-MM-dd"])& "T00:00:00.000Z",
Source = Json.Document(Web.Contents("https://api.crewhu.com/api" & "/v1/survey?query={""_updated_at"":{""$gte"":"""&variable&"""}}", [Headers=[X_CREWHU_APITOKEN="xxxxxxxxxxx"]]))
in Source

Result of user-defined function not displaying on web app

I am trying to define a function that divides Amount of money by Number of days.
So far the user can submit values, but I don't know how to make the result display on my Streamlit web app.
I copied part of my code below.
P.S. I am also a complete beginner in Python.
Thanks for any help
#HOW OFTEN EAT OUT
st.write("2. How often do you eat out?")
form04 = st.form(key='form04')
days = form04.text_input('Please enter average number of days')
submit04 = form04.form_submit_button('Submit')
#HOW MUCH INCOME
if submit04:
st.write('3. What is your monthly income?')
form05 = st.form(key='form05')
income = form05.text_input('Please enter monthly income')
submit05 = form05.form_submit_button('Submit')
if submit05:
def idealbudget(days, income):
budget=float(income)/float(days)
return float(budget)
st.write('Result is', budget)
In this code snippet, you define a function but you never actually call it:
if submit05:
def idealbudget(days, income):
budget=float(income)/float(days)
return float(budget)
st.write('Result is', budget)
Additionally, your st.write call is tabbed incorrectly, it should be at the same level as the def statement. A working solution probably looks like the following (untested):
if submit05:
def idealbudget(days, income):
budget=float(income)/float(days)
return float(budget)
st.write('Result is', idealbudget(days, income))

pyalgotrade trouble with exit-order-event (onExitOk)

Struggelig a bit with my trading algo. It seems that the orders cant finish before the next onBars() is called, and the quantities become a mess. Im using the enterLongLimit() to enter a trade, which calls onEnterOk() when it finishes - but im using limitOrder to exit parts of a position based on some technical indicator, and that doesnt seem to call onExitOk().
def onExitOk(self, position):
print("Exit ok", position.getExitOrder().getExecutionInfo().getDateTime())
def onEnterOk(self, position):
print("Enter ok", position.getEntryOrder().getExecutionInfo())
def _closePosition(self, price, qty, reason, date):
print("Closing position with price", price, "and closing qty", qty)
brk = self.getBroker()
shares = brk.getShares(self.instrument) * qty
print("Cash now before sell: ", brk.getCash(self.instrument))
self.info("Sell BTC %s at %s because %s on %s " % (shares, price, reason, date))
self.position = self.limitOrder(self.instrument, price, shares*-1)
print("Cash now after sell: ", brk.getCash(self.instrument))
Execution:
Closing position with price 746.3 and closing qty 0.5
Cash now before sell: 17.423283999999967
Cash now after sell: 17.423283999999967
The cash before and after the limitOrder is the same, so i have to wait for the event to come in. Ideas?
I had a similar problem and then after some digging I found that onEnter and onExit events are only triggered when a position is opened using one of the enterLong or enterShort methods. Trades executed with stop, limit or stop-limit orders do not trigger onEnter or onExit events which is a real shame.
This what the comments in the source code say, ie.:
def onEnterOk(self, position):
"""Override (optional) to get notified when the order submitted to enter a position was filled. The default implementation is empty.
:param position: A position returned by any of the enterLongXXX or enterShortXXX methods.
:type position: :class:`pyalgotrade.strategy.position.Position`.
"""
pass
See the strategy class code.
Your limit order should still work as expected even though you do not get the notification.

How to sort objects in DOORS by modification TIME, not just mod DATE?

Sorting objects in DOORS by the built-in DXL Attribute "Last Modified On" only sorts to the date level. That is, after sorting there is no guarantee to the order of Objects that were modified on the same calendar date (but at different times).
That's beyond stupid, especially since other online sources suggest that this field does in fact have this information available - but apparently only sorts on the displayed info, not the underlying data.
Neverminding how I'd LIKE this to work, what can I do instead? Today a module has literally hundreds of changed Objects, but I'm only interested in those altered in the last hour.
Looks like DOORS stores Last Modified On as a date only, without any time. Just to check, I added a layout DXL column with this in it:
Date dMod
dMod = obj."Last Modified On"
dMod = dateAndTime(dMod)
display dMod ""
In return I was greeted with entries like:
09/08/15 00:00:00
I'm not really proud of this next thing, but it sort of does the job. I created a DXL attribute called Last History Date with the following DXL:
History hr
Date dResult = null
Date dHist = null
Date dLastMod = null
dLastMod = obj."Last Modified On"
dLastMod = dateAndTime(dLastMod)
for hr in obj do {
dHist = hr.date
}
if (null dHist) { dResult = dLastMod }
else if (dLastMod > dHist) { dResult = dLastMod }
else { dResult = dHist }
obj.attrDXLName = dResult
If there are no history records, or history is recorded before Last Modified On, it just uses Last Modified On and you'll have to deal with 00:00:00. The history date isn't necessarily the same as Last Modified On -- depends on if you have "Affect change dates" or "Generate history" features turned on for the various object attributes. It's sort of a half-baked solution, but if you really want to sort with time I can't think of another way.

get specific value from parameter

I have a multi-valued parameter TimeMonthOfYear(from cube) that contains January Februrary...December.
I want to set a default value showing current month using MonthName(Month(Today)) (I tried it and it didn't work) when running report...
If I do this [Time].[Month Of Year].&[October] it works! October is selected in dropdown after previous dropdown (Year) was selected.
I don't want to do it the "hard coded" way...I have tried
[Time].[Month Of Year].&[MonthName(Month(Today))] and
="[Time].[Month Of Year].&["&MonthName(Month(Today))&"]" without luck
Any help is very much appreciated!
Yup :) Well it's now working with may be a not so nice solution but will work for now with the help of vb code. in standard value I have ="[Time].[Month Of Year].&[" + Code.SetMonth() + "]" and custom code Function SetMonth() As String Dim x as STRING x =CStr(MonthName(Month(Today))) 'CStr not needed I think If x = "januari" Then x = "January" ElseIf x = "februari" Then x = "February" ... End If Return(x) End Function That is giving me the current month after selecting value in year drop-down :)