I have the following problem:
I want to use a while not loop under a true-false condition. I define the condition and tell the loop what to do while the condition is True and False respectively. However, in the line 'converge = False, j = 1' (please see code below), I get the message 'int' object is not iterable. Can you help please? I don't know what the problem here is as I am fairly new to python.
Condition that the model run should stop at steady state (when the slope does not change anymore)
Final_pools_2 = [pools_2[-1,:]]
converge = False, j = 1
while not converge:
parset_2[-6:] = Final_pools_2
j = j+1
fluxes_2,pools_2 = f2py.dalec(fluxes_2,pools_2,drivers,-10.,deltat,removal,fires,parset_2,1)
Final_pools_2.append(pools_2[-1,:])
test = 1-np.abs(Final_pools_2[-1]/parset_2[-6:])
if test > 0.001:
converge = True
Final_pools_2 = np.array(Final_pools_2)
Thanks for your help :)
You cant inialise two variables of different types on one line.
Change it to:
converge = False
j = 1
Related
I am trying to write a pattern matching function in SML but I get this error
Error: non-constructor applied to argument in pattern: -
I am trying to do something as such:
fun illegal (c:char) i j n m =
let
fun legal (#"A") 0 j = true
|legal (#"B") i 0 = true
|legal (#"C") i n = true
|legal (#"D") m j = true
| legal c i j = false
in
if (legal c i j = false) then 0
else i
end
**I suspect that the problem is that my n,m are two constants that have been valued right before. Any help appreciated
(I searched online and here I added parentheses in my chars, and tried some other stuff but my error persisted)**
When you pattern match, something like i is not checking to see if it has the same value as the existing i binding, but it's introducing a new i binding.
When you have:
legal (#"A") 0 j = true
You're really looking for is something like:
legal (#"A") 0 j2 = j = j2
I have data in the form of list of lists where I am trying to match the demand and supply such that each demand matches uniquely to one supply item.
dmndId_w_freq = [['a',4,[1,2,3,4]],['b',6,[5,6,7,8,3,4]],['c',7,[6,5,7,9,8,3,4]],['d',8,[1,6,3,4,5,6,7,10]]]
num_sims = 1
for sim_count in range(num_sims):
dmndID_used_flag = {}
splID_used_flag = {}
dmndID_splId_one_match = {}
for i in dmndId_w_freq:
if i[0] not in dmndID_used_flag.keys():
for j in i[2]:
#print j
#print "CLICK TO CONTINUE..."
#raw_input()
if j in splID_used_flag.keys():
i[2].remove(j)
dmndID_splId_one_match[i[0]] = i[2][0]
splID_used_flag[i[2][0]] = 1
dmndID_used_flag[i[0]] = 1
print
print dmndID_splId_one_match
#print splID_used_flag
#print dmndID_used_flag
#raw_input()
I would expect the output dmndID_splId_one_match to be something like {'a':1,'b':5,'c':6,'d':3}.
But I end up getting {'a':1,'b':5,'c':6,'d':6}
So I am NOT getting a unique match as the supply item 6 is getting mapped to demands 'c' as well as demand 'd'.
I tried to debug the code by looping through it and it seems that the problem is in the for-loop
for j in i[2]:
The code is not going through all the elements of i[2]. It does not happen with the 'a' and 'b' part. but starts happening with the 'c' part. It goes over 6 and 5 but skips 7 (the third element of the list [6,5,7,9,8,3,4]). Similarly, in the 'd' part it skips the 2nd element 6 in the list [1,6,3,4,5,6,7,10]. And that is why the mapping is happening twice, since I am not able to remove it.
What am I doing wrong that it is not executing the for-loop as expected?
Is there a better way to write this code?
I figured out the problem in the for loop. I am looping through i[2] and then trying to modify it within the loop. this makes it unstable.
I know this has been asked a number of times but somehow that didn't work out. I have this model field in model Song.
sent_score = models.DecimalField(default= 0.0,max_digits=4,decimal_places=2,blank=True)
In my view i update sent score the following ways.
song_item = Song.objects.get(id=id)
com_list = Comment.objects.filter(song_id=id)
com_count = com_list.count()
pos_comments = com_list.filter(sentiment='positive')
pos_count = pos_comments.count()
getcontext().prec = 2
sent_score = Decimal(pos_count)/Decimal(com_count)
However it still gives me this error:
InvalidOperation: quantize result has too many digits for current context
I also tried the quantize method in this way:
sc = Decimal(pos_count)/Decimal(com_count)
Decimal(sc).quantize(Decimal('12.12'), rounding = ROUND_DOWN)
song_item.sent_score = sc
song_item.save()
but it still gives the same error please tell me where am i going wrong
You should not use getcontext().prec = 2 as you did in your first try, because it changes the precision for everything, not just this one calculation.
The issue with your second example is, that Decimal(sc).quantize(Decimal('12.12'), rounding=ROUND_DOWN) and even sc.quantize(Decimal('12.12'), rounding=ROUND_DOWN) do not change sc. Here is an example that works:
sc = Decimal(pos_count)/Decimal(com_count)
sc_adjusted = sc.quantize(Decimal('12.12'), rounding=ROUND_DOWN)
song_item.sent_score = sc_adjusted
song_item.save()
I am trying to create a sequence of similar dictionaries to further store them in a tuple. I tried two approaches, using and not using a for loop
Without for loop
dic0 = {'modo': lambda x: x[0]}
dic1 = {'modo': lambda x: x[1]}
lst = []
lst.append(dic0)
lst.append(dic1)
tup = tuple(lst)
dic0 = tup[0]
dic1 = tup[1]
f0 = dic0['modo']
f1 = dic1['modo']
x = np.array([0,1])
print (f0(x) , f1(x)) # 0 , 1
With a for loop
lst = []
for j in range(0,2):
dic = {}
dic = {'modo': lambda x: x[j]}
lst.insert(j,dic)
tup = tuple(lst)
dic0 = tup[0]
dic1 = tup[1]
f0 = dic0['modo']
f1 = dic1['modo']
x = np.array([0,1])
print (f0(x) , f1(x)) # 1 , 1
I really don't understand why I am getting different results. It seems that the last dictionary I insert overwrite the previous ones, but I don't know why (the append method does not work neither).
Any help would be really welcomed
This is happening due to how scoping works in this case. Try putting j = 0 above the final print statement and you'll see what happens.
Also, you might try
from operator import itemgetter
lst = [{'modo': itemgetter(j)} for j in range(2)]
You have accidentally created what is know as a closure. The lambda functions in your second (loop-based) example include a reference to a variable j. That variable is actually the loop variable used to iterate your loop. So the lambda call actually produces code with a reference to "some variable named 'j' that I didn't define, but it's around here somewhere."
This is called "closing over" or "enclosing" the variable j, because even when the loop is finished, there will be this lambda function you wrote that references the variable j. And so it will never get garbage-collected until you release the references to the lambda function(s).
You get the same value (1, 1) printed because j stops iterating over the range(0,2) with j=1, and nothing changes that. So when your lambda functions ask for x[j], they're asking for the present value of j, then getting the present value of x[j]. In both functions, the present value of j is 1.
You could work around this by creating a make_lambda function that takes an index number as a parameter. Or you could do what #DavisYoshida suggested, and use someone else's code to create the appropriate closure for you.
The software we use LanDesk Service Desk uses Boo Language calculations to allow for dynamic windows.
I have a drop down list on a form that has one of two options. "Acute" and "Ambulatory". Based on which is chosen, one of two possible fields will no longer be hidden and will be set to mandatory. I have managed to get this to work, but I'm afraid if the number of options grows on future forms that the code will get a little wordy. Do any of you have any suggestions for alternatives. Thank you,
import System
static def GetAttributeValue(Request):
isAcuteHidden = true
isAcuteMandatory = false
isAmbulatoryHidden = true
isAmbulatoryMandatory = false
if Request._PharmacyType != null and Request._PharmacyType._Name == "Acute":
isAcuteHidden = false
isAcuteMandatory = true
elif Request._PharmacyType != null and Request._PharmacyType._Name == "Ambulatory":
isAmbulatoryHidden = false
isAmbulatoryMandatory = true
return String.Format(":SetHidden(_AcutePharmacy, {0});:SetMandatory(_AcutePharmacy, {1});:SetHidden(_AmbulatoryPharmacy, {2});:SetMandatory(_AmbulatoryPharmacy, {3});", isAcuteHidden, isAcuteMandatory, isAmbulatoryHidden, isAmbulatoryMandatory)
A few pointers:
It appears that for both pairs, the is?????Hidden and corresponding is?????Mandatory will always be opposite values. If so, you don't need two separate boolean variables to track them.
If you're going to end up with a lot of blocks that look basically like this one, the proper way to handle it in Boo is with a macro, like so:
macro HiddenOrRequiredValues:
ControlStrings = List[of String]()
ArgVarNames = List[of ReferenceExpression]()
counter = 0
for arg as ReferenceExpression in HiddenOrRequiredValues.Arguments:
argVariable = ReferenceExpression("is$(arg)Hidden")
yield [|$argVariable = true|]
yield [|
if Request._PharmacyType != null and Request._PharmacyType._Name == $(arg.ToString()):
$argVariable = false
|]
ControlStrings.Add(":SetHidden(_$(arg)Pharmacy, {$(counter)});:$(arg)Mandatory(_AcutePharmacy, {$(counter + 1)})")
ArgVarNames.Add(argVariable)
counter += 2
resultString = join(ControlStrings, '')
resultCmd as MethodInvocationExpression = [|String.Format($resultString)|]
for varName in ArgVarNames:
resultCmd.Arguments.Add([|$varName|])
resultCmd.Arguments.Add([|not $varName|])
yield [|return $resultCmd|]
Then the entirety of your method becomes:
static def GetAttributeValue(Request):
HiddenOrRequiredValues Acute, Ambulatory
It's more work to set it up, but once you have the macro in place, adding in more values becomes much, much easier. Feel free to modify the macro to suit your needs. This should be enough to get you started, though.