i'm trying to implement this code. here are the problems:
1. i want to use variable typ_transport in further coding not just inside if.(it does not recognize the variable.)
2. the logic seems to be right but when i change the values in jsonStr (e.g. "walk" : true to "walk" : fasle ) the output does not print the right output.
Could any one help me with this? thanks
import json
jsonStr = '{"walk" : true, "bike" : false, "tram" : false}'
inputvar = json.loads(jsonStr)
if inputvar['walk'] == 'True' and inputvar['bike'] == 'False' :
typ_transport='foot'
elif inputvar['walk'] == 'False' and inputvar['bike'] == 'True' :
typ_transport='bicycle'
class transport:
if typ_transport=='foot':
velocity=80
typ='foot'
elif typ_transport=='bicycle':
velocity=330
typ='bicycle'
def __init__(self,typ,velocity):
self.velocity = velocity
self.typ = typ
if inputvar['tram'] == 'False' :
radius= T*transport.velocity
print (radius)
else :
print (typ_transport, 333)
I see some problems in the code, so I'll try to point them out as I go through your questions
i want to use variable typ_transport in further coding not just inside if.(it does not recognize the variable.)
The reason why you can't access the typ_transport variable is that it's created inside the if statement. If you wish to access the variable later in the code, you would have to change the scope of the typ_transport into a global scope.
You can do this in two ways. First is creating a global variable before you start the if statement
typ_transport = ""
if inputvar['walk'] == True and inputvar['bike'] == False:
typ_transport = 'foot'
The second way would be to create a global variable inside the if statement using global keyword. This way is highly discouraged since it is easy to lose the track of variables and their scopes.
the logic seems to be right but when i change the values in jsonStr (e.g. "walk" : true to "walk" : fasle ) the output does not print the right output
Aside from the spelling errors you got there, Python booleans are kept in True, and False (no single quote, first letter capitalized). When you use JSON module, it should parse correctly, but it's always good idea to double check.
Lastly, You are using class but it's not organized. Let's try to make it look little more tidier.
class transport:
def __init__(self,typ_transport): #utilizing global variable we created
if typ_transport == 'foot':
velocity = 80
self.typ_transport = self.typ_transport
self.velocity = velocity
elif typ_transport == 'bicycle':
......
Now to get the velocity when typ_transport = 'foot'
passenger = transport(typ_transport) #creating passenger object
velocity = passenger.velocity
import json
jsonStr = ('[{"walk" : true, "bike" : false, "tram" : false}, '
'{"walk" : false, "bike" : true, "tram" : false}, '
'{"walk" : false, "bike" : false, "tram" : true},'
'{"walk" : false, "bike" : false, "tram" : false}]'
)
inputvar = json.loads(jsonStr)
class Transport:
def __init__(self,typ):
self.typ = typ
self.velocity = None
if typ == 'foot':
self.velocity = 80
elif typ == 'bicycle':
self.velocity = 330
elif typ == 'tram':
self.velocity = 333
for var in inputvar:
typ_transport = None
if var['walk'] is True and var['bike'] is False:
typ_transport = 'foot'
elif var['walk'] is False and var['bike'] is True:
typ_transport = 'bicycle'
elif var['tram'] is True:
typ_transport = 'tram'
transport = Transport(typ_transport)
print(transport.typ, transport.velocity)
This make more sense to me.
Feel free to change it, if I misunderstood your logic.
Related
I got question about CatBoostClassifier.
params = {
'loss_function' : 'Logloss',
'eval_metric' : 'AUC',
'verbose' : 200,
'random_seed' : 42,
'custom_metric' : 'AUC:hints=skip_train~false'
}
cbc = CatBoostClassifier(**params)
cbc.fit(x_tr, y_tr,
eval_set = (x_te, y_te),
use_best_model = True,
plot = True
);
predictions = cbc.predict(x_te)
Model results:
bestTest = 0.6786987522
But when I try :
from sklearn import metrics
auc = metrics.roc_auc_score(y_te, predictions)
auc
I got 0.5631684491978609 result. Why this results differ ? What first and second result mean ? Which one is final metric of my cbc model ?
OK,
I found solution. I should use:
predictions = cbc.predict_proba(x_te)
rather than
predictions = cbc.predict(x_te)
Now I have the same results.
When I run the program It will only run the first If and make those specific changes. Noticed when i switched them around and only the first one gives me what I want... Thanks for the help.
if SW1 != r['SW1']: #check the received value of SW1 & change it on the App if there is a mismatch
print("Changing SW1 status to the value in the database.")
if self.sw1.active == True:
self.sw1.active = False
else:
self.sw1.active = True
else:
return
if LED1 != r['LED1']: #check the received value of led1 & change it on the App if there is a mismatch
print("Changing LED1 status to the value in the database.")
if self.led1.active == True:
self.led1.active = False
else:
self.led1.active = True
else:
return
if LED2 != r['LED2']: #check the received value of led2 & change it on the App if there is a mismatch
print("Changing LED2 status to the value in the database.")
if self.led2.active == True:
self.led2.active = False
else:
self.led2.active = True
else:
if LED3 != r['LED3']: #check the received value of led3 & change it on the App if there is a mismatch
print("Changing LED3 status to the value in the database.")
if self.led3.active == True:
self.led3.active = False
else:
self.led3.active = True
else:
return
You should not return in else after every if. This will make the function to close after the first if is failed. I will explain it further with one example.
Take this function which checks if a number is even.
def foo_bar(n):
if n%2==0:
print("Even")
else:
return
print("I have been reached")
If an even number is passed, you will see the below output
>>> foo_bar(10)
Even
I have been reached
If the Odd number is passed, you will not see any output as the function is returning None and Terminated in else.
Now if you have multiple ifs in the function,
def foo_bar(n):
if n%2==0:
print("Even")
else:
return
if n%3==0:
print("Divisible by 3")
print("I have been reached")
If you pass 9 as an argument, the above function prints nothing. It is because after one condition is checked , you are returning None which terminates the function.
Hope this answers your question.
I have some troubles with a simple code that I've made :
SWEP.PrintName = "Gestionnaire d'alarmes Administrateur"
SWEP.Author = "Frass"
SWEP.Instructions = "Clic Gauche : Ouvrir le gestionnaire"
SWEP.Spawnable = true
SWEP.AdminOnly = true
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = true
SWEP.Secondary.Ammo = "none"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Slot = 1
SWEP.SlotPos = 2
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = true
SWEP.ViewModel = "models/weapons/v_pistol.mdl"
SWEP.WorldModel = "models/weapons/w_pistol.mdl"
local ShootSound = Sound( "buttons/button14.wav" )
function SWEP:PrimaryAttack()
self:TabletMenu()
end
function TabletMenu() (reduced, there's a lot of code inside)
When I try to use my SWEP in GMOD, the console give me this error :
[ERROR] lua/weapons/alarmtabletld.lua:44: attempt to call method 'TabletMenu' (a nil value)
1. unknown - lua/weapons/alarmtabletld.lua:44
I really don't understand what is doing this error...
Some help could be really nice !
You are calling a TabletMenu function that doesnt exist as part of the SWEP table. Is it defined somewhere else perhaps?
I am working on a check_mk plugin and can't seem to get the WATO specified params passed to the check function when it runs for one check in particular...
The check param rule shows in WATO
It writes correct looking values to rules.mk
Clicking the Analyze check parameters icon from a hosts service discovery shows the rule as active.
The check parameters displayed in service discovery show the title from the WATO file so it seems like it is associating things correctly.
Running cmk -D <hostname> shows the check as always having the default values though.
I have been staring at it for awhile and am out of ideas.
Check_MK version: 1.2.8p21 Raw
Bulk of check file:
factory_settings["elasticsearch_status_default"] = {
"min": (600, 300)
}
def inventory_elasticsearch_status(info):
for line in info:
yield restore_whitespace(line[0]), {}
def check_elasticsearch_status(item, params, info):
for line in info:
name = restore_whitespace(line[0])
message = restore_whitespace(line[2])
if name == item:
return get_status_state(params["min"], name, line[1], message, line[3])
check_info['elasticsearch_status'] = {
"inventory_function" : inventory_elasticsearch_status,
"check_function" : check_elasticsearch_status,
"service_description" : "ElasticSearch Status %s",
"default_levels_variable" : "elasticsearch_status_default",
"group" : "elasticsearch_status",
"has_perfdata" : False
}
Wato File:
group = "checkparams"
#subgroup_applications = _("Applications, Processes & Services")
register_check_parameters(
subgroup_applications,
"elasticsearch_status",
_("Elastic Search Status"),
Dictionary(
elements = [
( "min",
Tuple(
title = _("Minimum required status age"),
elements = [
Age(title = _("Warning if below"), default_value = 600),
Age(title = _("Critical if below"), default_value = 300),
]
))
]
),
None,
match_type = "dict",
)
Entry in rules.mk from WATO rule:
checkgroup_parameters.setdefault('elasticsearch_status', [])
checkgroup_parameters['elasticsearch_status'] = [
( {'min': (3600, 1800)}, [], ALL_HOSTS ),
] + checkgroup_parameters['elasticsearch_status']
Let me know if any other information would be helpful!
EDIT: pls help
Posted question here as well and the mystery got solved.
I was matching the WATO rule to item None (5th positional arg in the WATO file), but since this check had multiple items inventoried under it (none of which had the id None) the rule was applying to the host, but not to any of the specific service checks.
Fix was to replace that param with:
TextAscii( title = _("Status Description"), allow_empty = True),
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm having a bit of trouble with my class functions. On my class I have 3 different functions but whenever I call one of the functions outside of the class, it only ever calls the first one despite me typing in the correct function name.
This is the class below with the different functions, although I have only included two as I don't want you to have to search through lots of code.
class mage(baseclass):
def __init__(self, name, level, attack, defence, hp):
baseclass.__init__(self, name, level, hp)
self.attack = attack
self.defence = defence
def __str__(self):
return "You are now a Mage, your new stats are:\n Level: {0}\n Attack: {1}\n Defence: {2}\n HP: {3}".format(self.level, self.attack, self.defence, self.hp)
def flamevortex(self, x, y, z):
print("You used Flame Vortex")
time.sleep(1.5)
damageofmove = 3
damagedone = damageofmove*y
damagedoneafterdefence = damagedone - z
x = x - damagedoneafterdefence
print("The monster's health is now " + str(x))
time.sleep(1.5)
return x
def lightningbolt(self, x, y, z):
print("You used Lightning Bolt")
time.sleep(1.5)
damageofmove = 3
damagedone = damageofmove*y
damagedoneafterdefence = damagedone - z
x = x - damagedoneafterdefence
print("The monster's health is now " + str(x))
time.sleep(1.5)
return x
This is the place where I am calling the functions:
if Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX":
monster1.hp = p1.flamevortex(monster1.hp, p1.attack, monster1.defence)
if chosenmove == monsterattacks[0]:
p1.hp = monsterlasersword(p1.hp)
elif chosenmove == monsterattacks[1]:
p1.hp = monsterswipe(p1.hp)
elif chosenmove == monsterattacks[2]:
monster1.hp = monsterregen(monster1.hp)
time.sleep(1.5)
print("After the monster's attacks, your hp is now " + str(p1.hp))
elif Userattack.upper() == "LIGHTNINGBOLT" or "LIGHTNING BOLT":
monster1.hp = p1.lightningbolt(monster1.hp, p1.attack, monster1.defence)
if chosenmove == monsterattacks[0]:
p1.hp = monsterlasersword(p1.hp)
elif chosenmove == monsterattacks[1]:
p1.hp = monsterswipe(p1.hp)
elif chosenmove == monsterattacks[2]:
monster1.hp = monsterregen(monster1.hp)
time.sleep(1.5)
print("After the monster's attacks, your hp is now " + str(p1.hp))
No matter what the user inputs, it only ever calls the first function.
I know this is a lot to process and appreciate any help. Thanks
if Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX": means is userattack.upper() equal to "FLAMEVORTEX", or does the string "FLAME VORTEX" have True value.
Now since empty strings are False and non-empty strings are True, Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX" is always True, and that's not what you meant.
Try: Userattack.upper() == "FLAMEVORTEX" or Userattack.upper()=="FLAME VORTEX"