ROR code sends many mails - ruby

I am having following ROR code
def func (point,c,r)
res=isPointInCircle(point,c,r) #returns true/ false
if res=='false'
AlertMailer.geofence('mail#gmail.com').deliver
end
end
func is called for every 2 minutes with different point.
isPointInCircle checks point is within circle or not .Returns true false.
I want to send mail when the point is first time outside or inside the circle.
Means if initially point is inside for 1 hrs.
no mail
if it goes outside
I want single mail to be sent which does not happen,
because func is called every 2 min.
so emails are sent every 2 minutes which i dont want .
So how to do this

You could check if the previous status is the same as the current status, and only send the mail if there has been a change (the point is inside the circle and it was outside before, or vice versa).
def func(point, c, r)
status = point_in_circle?(point, c, r)
if last_status != status
AlertMailer.geofence('mail#gmail.com').deliver
end
end
It's hard to say how to implement last_status without knowing more about your app. If there were a Point model, I might add in_circle? as an instance method. Then you could get the previous point from the database and compare the two:
def check_point_status(current, previous, c, r)
if current.in_circle?(c, r) != previous.in_circle?(c, r)
AlertMailer.geofence('mail#gmail.com').deliver
end
end
A couple of pointers: Ruby usually uses snake_case not camelCase for variables and functions, and "predicate" methods (returning true/false) are typically named with a question mark at the end to indicate that they are yes/no questions. You wouldn't have needed the comment in your code because it would have been obvious that point_in_circle? returns true or false.
Also your code suggests your function returns "true" or "false" as strings, which is a really bad idea! If you used the actual boolean values true or false, you could have written your original code as
def func(point, c, r)
unless point_in_circle?(point, c, r)
AlertMailer.geofence('mail#gmail.com').deliver
end
end

Related

How do I prevent multiple discordrb bot activations being processed out of sequence?

I have a Ruby Discord (discordrb) bot written to manage D&D characters. I notice when multiple players submit the same command, at the same time, the results they each receive are not independent. The request of one player (assigning a weapon to their character) ends up being assigned to other characters who submitted the same request at the same time. I expected each request to be executed separately, in sequence. How do I prevent crossing requests?
bot.message(contains:"$Wset") do |event|
inputStr = event.content; # this should contain "$Wset#" where # is a single digit
check_user_or_nick(event); pIndex = nil; #fetch the value of #user & set pIndex
(0..(#player.length-1)).each do |y| #find the #player pIndex within the array using 5 char of #user
if (#player[y][0].index(#user.slice(0,5)) == 0) then pIndex = y; end; #finds player Index Value (integer or nil)
end;
weaponInt = Integer(inputStr.slice(5,1)) rescue false; #will detect integer or non integer input
if (pIndex != nil) && (weaponInt != false) then;
if weaponInt < 6 then;
#player[pIndex][1]=weaponInt;
say = #player[pIndex][0].to_s + " weapon damage has be set to " + #weapon[(#player[pIndex][1])].to_s;
else;
say = "Sorry, $Wset requires this format: $Wset? where ? is a single number ( 0 to 5 )";
end;
else
say = "Sorry, $Wset requires this format: $Wset? where ? is a single number ( 0 to 5 )";
end;
event.respond say;
end;
To avoid race conditions in multithreaded code like this, the main thing you want to look for are side effects.
Think about the bot.message(contains:"$Wset") do |event| block as a mini program or a thread. Everything in here should be self contained - there should be no way for it to effect any other threads.
Looking through your code initially, what I'm searching for are any shared variables. These produce a race condition if they are read/written by multiple threads at the same time.
In this case, there are 2 obvious offenders - #player and #user. These should be refactored to local variables rather than instance variables. Define them within the block so they don't affect any other scope, for example:
# Note, for this to work, you will have to change
# the method definition to return [player, user]
player, user = check_user_or_nick(event)
Sometimes, making side effects from threads is unavoidable (say you wanted to make a counter for how many times the thread was run). To prevent race conditions in these scenarios, a Mutex is generally the solution but also sometimes a distributed lock if the code is being run on multiple machines. However, from the code you've shown, it doesn't look like you need either of these things here.

Compound Boolean Expr: Void Value Expression

def success?
return #fhosts.empty? and #khosts.empty? and #shosts.any?
end
When I run that instance method, I get an error:
/home/fandingo/code/management/lib/ht.rb:37: void value expression
return #fhosts.empty? and #khosts.empty? and #shosts.any?
I'm confused by what's happening since this works
def success?
#fhosts.empty? and #khosts.empty? and #shosts.any?
# This also works
# r = #fhosts.empty? and #khosts.empty? and #shosts.any?
# return r
end
I'm coming from a Python background, and I don't want anything to do with implicit returns. Programming has plenty of landmines as it is.
If we have an arbitrary expression, E, that consists of boolean operations and and or together, here are some operations we could perform:
if E -- works
E -- works
* v = E -- works
return E -- broken
Why doesn't the last case work?
Edit: Actually v = E doesn't work. Only
v = Ei
is evaluated. Ei+1...k are ignored.
This is likely due to the very weak binding of and which causes it to parse out differently than you expect:
return x and y
This actually means:
(return x) and y
Since you're returning immediately it doesn't have a chance to evaluate the remainder of the expression.
Your version without return is correct:
x and y
This doesn't have a binding issue and is more idiomatic Ruby. Remember you only need to put an explicit return if you're trying to force an exit before the last line of the method. Being opposed to implicit returns is going to make your code look heavily non-Ruby. They're one of the reasons Ruby is so clean and simple, and how things like a.map { |v| v * 2 } works.
The When in Rome principle applies here. If you want to write Python-style Ruby you're going to be going against the grain. It's like saying "I don't like how you say X in your spoken language, so I'll just ignore that and do it my way."
This should also work:
return x && y
The && method is very strongly bound so return is the last thing evaluated here.
Or if you really want to use and for whatever reason:
return (x and y)

Sketchup Ruby ComponentDefinition.count_instances only in selection

Given a Sketchup::ComponentDefinition object c_def, if I use c_def.count_instances or cdef.instances.length I have the total number of instances of my component in the whole model, just like documentation says it should.
ComponentDefinition::count_instances
ComponentDefinition::instances
Unfortunately I need to count instances separating by groups or sub-components.
E.g. suppose I have two different components in a model that use the same basic component.
The first one has 3 basic component instances and the second one has 5.
c_def.count_instances will always return 8, as it is the total number of instances, but I need to be able to tell that the first component has only 3 and the second one only 5.
How to do that?
Thanks!
You would then need to recursively traverse the entities of the instance you're interested in. I'm afraid there is no API method for doing this.
module Example
def self.count_definition_in_entities(entities, find_definition, count = 0)
entities.each { |entity|
definition = self.get_definition(entity)
next if definition.nil?
count += 1 if find_definition == definition
count = self.count_definition_in_entities(definition.entities, find_definition, count)
}
count
end
def self.get_definition(entity)
if entity.is_a?(Sketchup::ComponentInstance)
entity.definition
elsif entity.is_a?(Sketchup::Group)
entity.entities.parent
else
nil
end
end
end # module
d = Sketchup.active_model.definitions["Sophie"]
Example.count_definition_in_entities(Sketchup.active_model.entities, d)
Also, beware that count_instances doesn't a complete full model count. If you have an component C1 placed two times in another component C2. Then C1.count_instances return 2. If you add another copy C2 you might expect C1.count_instances to yield 4 - but it doesn't it still yields 2. The method only counts how many times the instance is placed in any Entities collection, but doesn't take into account the whole model three.

Bizzare "attempt to call a table value" in Lua

The following code snippet:
for weight, item in itemlist do
weight_total=weight_total+weight
end
is causing the error "attempt to call table value" on the first line in that snippet. Why?
Itemlist is a table of tables of weights and strings, like such:
local itemlist = {
{4,"weapon_pistol"},
{2,"weapon_357"},
...
Nothing is being called as far as I can tell; why is this error coming up?
The generic for expects 3 arguments: a callable value, some value which is repeatedly passed to it, and the key where the iteration shall start.
Stock lua does not call pairs on the first value passed to for if that's not callable, though some derivatives do.
Thus, you must use ipairs(itemlist), pairs(itemlist), next, itemlist or whatever you want (the last two have identical behavior, and are what most derivatives do).
As an example, an iterator unpacking the value sequence:
function awesome_next(t, k)
k, t = next(t, k)
if not t then return end
return k, table.unpack(t)
end
for k, a, b, c, d in awesome_next, t do
end

OR between two function call

What is the meaning of a || between two function call
like
{
//some code
return Find(n.left,req)||Find(n.right,req);
}
http://www.careercup.com/question?id=7560692
can some one help me to understand . Many thanks in advance.
It means that it returns true if one of the two functions is true (or both of them).
Depends on the programming language, the method calls Find(n.left,req) -> if it's true - returns true. if it's false, it calls Find(n.right,req) and returns its Boolean value.
In Java (and C and C#) || means "lazy or". The single stroke | also means "or", but operates slightly differently.
To calculate a||b, the computer calculates the truth value (true or false) of a, and if a is true it returns the value true without bothering to calculate b, hence the word "lazy". Only if a is false, will it checks b to see if it is true (and so if a or b is true).
To calculate a|b, the computer works out the value of a and b first, then "ors" the answers together.
The "lazy or" || is more efficient, because it sometimes does not need to calculate b at all. The only reason you might want to use a|b is if b is actually a function (method) call, and because of some side-effect of the method you want to be sure it executes exactly once. I personally consider this poor programming technique, and on the very few occasions that I want b to always be explicitly calculated I do this explicitly and then use a lazy or.
Eg consider a function or method foo() which returns a boolean. Instead of
boolean x = a|foo(something);
I would write
boolean c=foo(something);
boolean x = a||c;
Which explicitly calls foo() exactly once, so you know what is going on.
Much better programming practice, IMHO. Indeed the best practice would be to eliminate the side effect in foo() entirely, but sometimes that's hard to do.
If you are using lazy or || think about the order you evaluate it in. If a is easy to calculate and usually true, a||b will be more efficient than b||a, as most of the time a simple calculation for a is all that is needed. Conversely if b is usually false and is difficult to calculate, b||a will not be much more efficient than a|b. If one of a or b is a constant and the other a method call, you should have the constant as the first term a||foo() rather than foo()||a as a method call will always be slower than using a simple local variable.
Hope this helps.
Peter Webb
return Find(n.left,req)||Find(n.right,req);
means execute first find {Find(n.left,req)} and return true if it returns true or
execute second find return the value true if it return true, otherwise false.

Resources