Custom Validation in Model with Parameter from controller - ruby-on-rails-3

i have this chunk of codes in my controller
def create
number = params[:number]
#color = Colors.new(params[:colors])
#color.save
end
and i have this validation in model color.rb
validate :should_be_primary
def should_be_primary
#validations here
end
I just want the validation should only run when my params[:number] == 1
Note: params[:number] is only a parameter and not a table field.
anyone please help me.

def create
number = params[:number]
params[:colors][:param_number] = number
#color = Colors.new(params[:colors])
#color.save
end
validate :should_be_primary
def param_number=(number)
#number = number
end
def should_be_primary
if #number
#blah blah
end
end

Try this on your model.rb
validate :should_be_pimary if self.number == 1
def should_be_primary
#validations here
end

Related

Unable to iterate a list to a thread

I am trying to pass a json return between functions but I get errors. So I convert the json to a list. However, I cannot iterate the list from a while loop unless I specify an actual number.
Full code is
class BackendThread(QThread):
update_date = pyqtSignal(list)
def run(self):
device_mode = []
while True:
#do stuff and get json_return
for xx in json_return["result"]["devices"]:
for y in xx["nodes"]:
if y['type'] == "FRAME_BUFFER":
data = xx["device_id"] + "\n" + y['configuration']['display_mode']
device_mode.append(data)
self.update_date.emit(str(device_mode))
device_mode = []
time.sleep(1)
class Window(QDialog):
def __init__(self):
QDialog.__init__(self)
self.resize(400,400)
self.input=QTextEdit(self)
self.input.resize(400,400)
self.initUI()
def initUI(self):
self.backend=BackendThread()
self.backend.update_date.connect(self.handleDisplay)
self.backend.start()
def handleDisplay(self,data):
count = 0
while count < 11:
self.input.setText(data[count])
count += 1
if __name__ == '__main__':
app=QApplication(sys.argv)
win =Window()
win.show()
sys.exit(app.exec_())
So this part does not work. I only get the last item in the list
count = 0
while count < 11:
self.input.setText(data[count])
count += 1
When I do this, it works but I cannot hard code the item number becuase the list will never have the same amount of items
self.input.setText(data[0])
self.input.setText(data[1])
self.input.setText(data[2])
etc
Any ideas as to how to get that while loop working?

How to change the mutable parameter in Pyomo (AbstractModel)?

I am trying to update my mutable parameter Nc in my Abstract model
the initial value is 4
I constructed the instance then change instance.Nc to 5 and solve it but it is still 4 (initial value) , can any body help ?
from pyomo.environ import *
import random
model = AbstractModel()
model.i = RangeSet(40)
model.j = Set(initialize=model.i)
model.x = Var(model.i,model.j, initialize=0,within=Binary)
model.y = Var(model.i, within=Binary)
model.Nc=Param(initialize=5,mutable=True)
def Ninit(model,i):
return random.randint(0,1)
model.N=Param(model.i,initialize=Ninit,mutable=True)
def Dinit(model,i,j):
return random.random()
model.D=Param(model.i,model.j,initialize=Dinit,mutable=True)
def rule_C1(model,i,j):
return model.x[i,j]<=model.N[i]*model.y[j]
model.C1 = Constraint(model.i,model.j,rule=rule_C1)
def rule_C2(model):
return sum(model.y[i] for i in model.i )==model.Nc
model.C2 = Constraint(rule=rule_C2)
def rule_C3(model,i):
return sum(model.x[i,j] for j in model.j)==model.N[i]
model.C3 = Constraint(model.i,rule=rule_C3)
def rule_OF(model):
return sum( model.x[i,j]*model.D[i,j] for i in model.i for j in model.j )
model.obj = Objective(rule=rule_OF, sense=minimize)
opt = SolverFactory('glpk')
#model.NC=4
instance = model.create_instance()
instance.NC=4
results = opt.solve(instance) # solves and updates instance
print('NC= ',value(instance.Nc))
print('OF= ',value(instance.obj))
It seems you are actually initializing your parmeter Nc to 5 (model.Nc=Param(initialize=5,mutable=True)) and then changing it to 4 once you create the instance (instance.Nc=4), so you might want to do the opposite (model.Nc=Param(initialize=4,mutable=True) then instance.Nc=4)
Also, note that you are inconsistantly addressing the Nc parameter throughout the code. When you declare the parameter you name it "Nc" (model.Nc=Param(initialize=5,mutable=True)), which is the actual python variable that Pyomo will use in the model, but later you try to change it with capital letters "NC", which is not a parameter (instance.NC=4). Minor typos like these can cause confusion and give you errors. Make sure to fix them and give it a try again

Keras custom metric

How can I create a custom metric that on a categorical problem accepts as correct predictions not only when the predicted category and the true one are the same, but also when the predicted category is a neighbour category of the true one?
This answer is valid if you consider that "only one class" should be output.
def neighbourMetric(yTrue,yPred):
#these make this function not differntiable, but since you asked for "metric" it's ok
trueIndices = K.argmax(yTrue)
predIndices = K.argmax(yPred)
minAccepted = trueIndices - 1
maxAccepted = trueIndices + 1
satisfiesMin = K.cast(K.greater_equal(predIndices,minAccepted),K.floatx())
satisfiesMax = K.cast(K.less_equal(predIndices,maxAccepted),K.floatx())
satisfiesBoth = satisfiesMin * satisfiesMax
return K.mean(satisfiesBoth)
Here is how I solved it:
def one_off(y_true, y_pred):
return K.cast(K.abs(K.argmax(y_true, axis=-1) - K.argmax(y_pred, axis=-1)) < 2, K.floatx())

Ohm::DataTypes::Type::Hash can't convert normal hash to SerializedHash

Maybe this question is too naive, but it really confused me. Here is my code, a profession class.
class Profession < OhmModel
include ProfessionMethods
attribute :type, Type::Integer
attribute :level, Type::Integer
attribute :add_point, Type::Hash
attribute :attribute_add_point, Type::Hash
reference :player, Player
def initialize(args = {})
super
if args.blank?
self.type = 1
self.level = 1
end
#add_point = SerializedHash.new
#attribute_add_point = SerializedHash.new
end
# 初始化加点
def init_add_point(hash)
hash.each do |key, value|
#add_point[key] = value
end
update_add_point
end
def update_add_point
self.add_point = #add_point
self.save
init_attribute_add_point
end
def init_attribute_add_point
self.add_point.each do |key, value|
key_new = key.to_s.gsub('_percent', '').to_sym
PROFESSIONS[type][key_new][:attribute].split(',').each do |attr|
#attribute_add_point[attr] = value
end
end
update_attribute_add_point
end
def update_attribute_add_point
self.attribute_add_point = #attribute_add_point
self.save
end
def name
PROFESSIONS[type][:name]
end
def probability
hash = {}
PROFESSIONS[type].keys.each do |key|
case key
when /property_id_\d?_percent/
hash[key] = PROFESSIONS[type][key]
end
end
return hash
end
def base_value
hash = {}
hash[:basic] = PROFESSIONS[type][:basic]
return hash
end
def points_count
5*level
end
def get_add_point
hash ={}
add_point_hash = self.add_point
add_point_hash.keys.each do |key|
key_new = key.to_s.gsub('_percent', '').to_sym
info = "#{PROFESSIONS[type][key_new][:name]}: #{PROFESSIONS[type][key_new][:des]}"
hash[info] = add_point_hash[key]
end
return hash
end
def fresh_add_point
probability_hash = probability
base_value_hash = base_value
points_count_value = points_count
calculate_probability(probability_hash, base_value_hash, points_count_value)
end
def redistribute_add_point
hash = {}
probability_hash = {}
probability.keys.each do |key|
probability_hash[key] = 1.0/probability.count
end
base_value_hash = base_value
points_count_value = points_count
add_point_hash = calculate_probability(probability_hash, base_value_hash, points_count_value)
init_add_point(add_point_hash)
add_point_hash.keys.each do |key|
key_new = key.to_s.gsub('_percent', '').to_sym
info = "#{PROFESSIONS[type][key_new][:name]}: #{PROFESSIONS[type][key_new][:des]}"
hash[info] = add_point_hash[key]
end
return hash
end
protected
def after_create
hash = fresh_add_point
init_add_point(hash)
end
end
It is all right when initializing.
pro = Profession.create
=> #<Profession:0x9504ffc
#_memo={},
#add_point=
{:property_id_1_percent=>104.0,
:property_id_2_percent=>101.0,
:property_id_3_percent=>100.0,
:property_id_4_percent=>100.0,
:property_id_5_percent=>100.0},
#attribute_add_point=
{"crystal_output"=>104.0,
"tritium_output"=>104.0,
"power_consume"=>101.0,
"speed"=>100.0,
"armor"=>100.0,
"hp_damage"=>100.0,
"armor_damage"=>100.0,
"sheild_damage"=>100.0},
#attributes=
{:type=>1,
:level=>1,
:created_at=>1368756861,
:updated_at=>1368756861,
:id=>"34",
:add_point=>
{:property_id_1_percent=>104.0,
:property_id_2_percent=>101.0,
:property_id_3_percent=>100.0,
:property_id_4_percent=>100.0,
:property_id_5_percent=>100.0},
:attribute_add_point=>
{"crystal_output"=>104.0,
"tritium_output"=>104.0,
"power_consume"=>101.0,
"speed"=>100.0,
"armor"=>100.0,
"hp_damage"=>100.0,
"armor_damage"=>100.0,
"sheild_damage"=>100.0}},
#errors={},
#id="34">
When reassign a hash type value to pro.add_point and save the object, Here is the problem.
pro.add_point = {:one => 1, :two => 2}
pro.save
Profession[34]
=> #<Profession:0x9a544bc
#_memo={},
#add_point={},
#attribute_add_point={},
#attributes=
{:created_at=>"1368756861",
:level=>"1",
:attribute_add_point=>
"{\"crystal_output\":104.0,\"tritium_output\":104.0,\"power_consume\":101.0,\"speed\":100.0,\"armor\":100.0,\"hp_damage\":100.0,\"armor_damage\":100.0,\"sheild_damage\":100.0}",
:add_point=>"{:one=>1, :two=>2}",
:updated_at=>"1368757147",
:type=>"1"},
#id="34">
The "add_point" attribute is saved as a normal string, not convert to a JSON style.

How do I fix error message. "Remember that ordinal parameters are 1-based!"

given the code snippet (please do not ask why I construct it this way...)
...some more Logic...
def blaParam = ['checkinable':checkinable]
def blaQuery = " AND c.product = :checkinable"
...some more Logic...
and
def paramBox = [] + blaParam
def queryBox = "" + blaQuery
def c = Bla.executeQuery("FROM Bla b WHERE 1 = 1 "+queryBox+" ", paramBox, [max:params.max])
I end up with a message
errors.GrailsExceptionResolver Remember that ordinal parameters are 1-based!
How do I prevent this?
Merging the two last parameter maps worked for me:
Bla.executeQuery("FROM Bla b WHERE 1 = 1 "+queryBox+" ", paramBox + [max:params.max])
if I change
def paramBox = [] + blaParam
to
def paramBox = [:] + blaParam
it is working