Reading from the command line in Rails - ruby-on-rails

I am trying to run the following mplayer command in rails using session:
mplayer -identify -vo null -ao null -frames 0 text.mov
I use require "session" and the following code works great in an individual ruby file.
mb = "mplayer"
mi = "-identify -vo null -ao null -frames 0"
dimensions_bitrate = Hash.new
stdout, stderr = '', ''
shell = Session::Shell.new
shell.execute "#{mb} #{mi} #{filename}", :stdout => stdout, :stderr => stderr
vars = (stdout.split(/\n/).collect! { |o| o if o =~ /^ID_/ } ).compact!
vars.each { |v|
a, b = v.split("=")
eval "##{a.to_s.downcase} = \"#{b}\""
if a == "ID_VIDEO_WIDTH"
dimensions_bitrate[0] = b.to_i
elsif a == "ID_VIDEO_HEIGHT"
dimensions_bitrate[1] = b.to_i
elsif a == "ID_VIDEO_BITRATE"
dimensions_bitrate[2] = b.to_i
end
}
HOWEVER, I am unable to load the session gem into ROR. I am not sure what the problem is. If I add require "session", I get the following error:
no such file to load -- session
I figure I am missing something relatively straightforward.
Any ideas?

I could not get this to work, so I did the following:
stdout = %x["mplayer" "-identify" "-vo" "-ao" "null" "-frames" "0" "#{filename}"]
vars = (stdout.split(/\n/).collect! { |o| o if o =~ /^ID_/ } ).compact!
vars.each { |v|
a, b = v.split("=")
eval "##{a.to_s.downcase} = \"#{b}\""
if a == "ID_VIDEO_WIDTH"
dimensions_bitrate[0] = b.to_i
elsif a == "ID_VIDEO_HEIGHT"
dimensions_bitrate[1] = b.to_i
elsif a == "ID_VIDEO_BITRATE"
dimensions_bitrate[2] = b.to_i
end
}
and it worked great. hope this is of use to someone running command line from ROR. The key is to set each parameter as a string.

Related

Garry's mod lua code error not working (Entity X, got nil)

I tried to fix some Garry's Mod addon and this is what happens. I tried to fix it for long time, but I'm not the best in Lua coding :/ . What is wrong with this code? I get this error:
[ERROR] addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80: bad argument #1 to 'SetPhysicsAttacker' (Entity expected, got nil)
1. SetPhysicsAttacker - [C]:-1
2. unknown - addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80
And the code is pretty long. I have every file working fine, but this file is not working
AddCSLuaFile()
DEFINE_BASECLASS( "base_anim" )
if (SERVER) then
util.AddNetworkString( "gb5_net_sound_lowsh" )
end
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.PrintName = ""
ENT.Author = ""
ENT.Contact = ""
ENT.GBOWNER = nil
ENT.MAX_RANGE = 0
ENT.SHOCKWAVE_INCREMENT = 0
ENT.DELAY = 0
ENT.SOUND = ""
net.Receive( "gb5_net_sound_lowsh", function( len, pl )
local sound = net.ReadString()
LocalPlayer():EmitSound(sound)
end );
function ENT:Initialize()
if (SERVER) then
self.FILTER = {}
self:SetModel("models/props_junk/watermelon01_chunk02c.mdl")
self:SetSolid( SOLID_NONE )
self:SetMoveType( MOVETYPE_NONE )
self:SetUseType( ONOFF_USE )
self.Bursts = 0
self.CURRENTRANGE = 0
self.GBOWNER = self:GetVar("GBOWNER")
self.SOUND = self:GetVar("SOUND")
end
end
function ENT:Think()
if (SERVER) then
if not self:IsValid() then return end
local pos = self:GetPos()
self.CURRENTRANGE = self.CURRENTRANGE+(self.SHOCKWAVE_INCREMENT*10)
if(GetConVar("gb5_realistic_sound"):GetInt() >= 1) then
for k, v in pairs(ents.FindInSphere(pos,self.CURRENTRANGE)) do
if v:IsPlayer() then
if not (table.HasValue(self.FILTER,v)) then
net.Start("gb5_net_sound_lowsh")
net.WriteString(self.SOUND)
net.Send(v)
v:SetNWString("sound", self.SOUND)
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
if GetConVar("gb5_sound_shake"):GetInt()== 1 then
util.ScreenShake( v:GetPos(), 5555, 555, self.shocktime, 500 )
end
table.insert(self.FILTER, v)
end
end
end
else
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
local ent = ents.Create("gb5_shockwave_sound_instant")
ent:SetPos( pos )
ent:Spawn()
ent:Activate()
ent:SetPhysicsAttacker(ply)
ent:SetVar("GBOWNER", self.GBOWNER)
ent:SetVar("MAX_RANGE",50000)
ent:SetVar("DELAY",0.01)
ent:SetVar("Shocktime",self.shocktime)
ent:SetVar("SOUND", self:GetVar("SOUND"))
self:Remove()
end
self.Bursts = self.Bursts + 1
if (self.CURRENTRANGE >= self.MAX_RANGE) then
self:Remove()
end
self:NextThink(CurTime() + (self.DELAY*10))
return true
end
end
function ENT:OnRemove()
if SERVER then
if self.FILTER==nil then return end
for k, v in pairs(self.FILTER) do
if not v:IsValid() then return end
v:SetNWBool("waiting", true)
end
end
end
function ENT:Draw()
return false
end
Is there a chance someone fix this for me? Or even just telling me what's wrong? I would be pleased. If needed I can send all files. Well... It's not my addon but I'm trying to fix an existing one. Someone tried to fix it too but he didn't (actually he broke it even more).
What the error means
Inside your ENT:Think() function, you are calling ent:SetPhysicsAttacker(ply)
ply is not defined anywhere inside that function, so is nil (Entity expected, got nil)
How to fix this
If no player is responsible for the damage caused by this entity, delete the line ent:SetPhysicsAttacker(ply).
Otherwise, assign an Owner to the entity at the point of creation, using SetOwner.
This would then allow you to use self:GetOwner() inside your Think hook
Example
hook.Add("PlayerSay", "SpawnEntity", function(ply, text)
if string.lower(text) == "!spawnentity" then
-- Create your entity
local myEntity = ents.Create("gb5_shockwave_sound_lowsh")
myEntity:SetPos(ply:GetPos())
myEntity:SetAngles(ply:GetAngles())
myEntity:Spawn()
-- Sets the owner to the player that typed the command
myEntity:SetOwner(ply)
return ""
end
end)
-- Inside your entity code
function ENT:Think()
print("My owner is: " .. tostring(self:GetOwner()))
-- ...
ent:SetPhysicsAttacker(self:GetOwner())
end

ruby scripts - (NameError) undefined local variable or method `null' for main:Object

My code
require "json"
require "erb"
flowvar = $workflowvar
path = 'src/main/resources/'+$workflowvar+'.drl'
rule = ""
File.open(path,"w") do |f|
f.puts "package com.drools.demo\;"+"\n"+"import org.mule.MessageExchangePattern\;"+"\n"+"import com.drools.demo.cashliquidassets\;"+"\n"+"global org.mule.module.bpm.MessageService mule\;"+"\n"+
"dialect \"mvel\""+"\n"+"dialect \"java\""+"\n"+"declare cashliquidassets"+"\n"+"#role\(\'event\'\)"+"\n"+"end"+"\n"
f.close
end
def concateRule(attribute,val)
if(val==null || val=="")
return "";
end
if(attribute != null)
if (attribute == "taxonomy_code" || attribute == "parent_taxonomy_code" || attribute == "report_name")
return "";
end
end
if val.start_with('<>')
return attribute+" != "+val[3,val.length].strip
elsif val.start_with('>')
return attribute+" > "+val
elsif val.start_with('<')
return attribute+" < "+val
elsif val.include? ","
return attribute+".contains("+val+"\)"
else
return attribute+" == "+ val
end
end
json = JSON.parse($payload)
json.each do |hash1|
hash1.keys.each do |key|
hash1[key].each do |inner_hash,value|
#inner_hash = inner_hash
#values = value
str = concateRule #inner_hash,$values
end
end
end
Compile is working fine, but in runtime, I am getting this following error. Any suggestions
Root Exception stack trace:
org.jruby.exceptions.RaiseException: (NameError) undefined local
variable or method `null' for main:Object
at RUBY.concateRule(<script>:15)
at RUBY.block in (root)(<script>:43)
at org.jruby.RubyHash.each(org/jruby/RubyHash.java:1350)
at RUBY.block in (root)(<script>:40)
at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1735)
at RUBY.block in (root)(<script>:39)
at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1735)
at RUBY.<main>(<script>:38)
You need to use nil instead of null.
So, just replace it.
Following the conversation in the comments above, here is how I would write the method:
def concat_rule(attribute, val)
val = val.to_s
if val == '' || ['taxonomy_code', 'parent_taxonomy_code', 'report_name'].include?(attribute)
return ''
end
if val.start_with?('<>')
"#{attribute} != #{val[3..-1].strip}"
elsif val.start_with?('>')
"#{attribute} > #{val}"
elsif val.start_with?('<')
"#{attribute} < #{val}"
elsif val.include?(',')
"#{attribute}.contains(#{val})"
else
"#{attribute} == #{val}"
end
end
A few notes:
Using snake_case method names and 2 space tabs, is a very strongly adhered to style guide in the ruby community.
Similarly, you can make use of ruby's implicit return, to shorten the code: The final value at the end of a method is returned automatically.
Adding val = val.to_s to the top of this method simplifies the rest of the code; eliminating the need to repeatedly convert to a string or perform nil checks.
You can use ruby's string interpolation ("#{code-to-evaluate}") syntax as a more elegant way to define strings than repeated use of + for concatenation.

Replace until all occurrences are removed

I have the following strings:
",||||||||||||||"
",|||||a|||||,|"
I would like to achieve that all occurrences of ",|" are replaced with ",,"
The output should be the following:
",,,,,,,,,,,,,,,"
",,,,,,a|||||,,"
When I run .gsub(',|', ',,') on the strings I get not the desired output.
",,|||||||||||||"
",,||||a|||||,,"
That's because it does not run gsub several times.
Is there a similar method that runs recursively.
A regular expression matches can not overlap. Since matches are what is used for replacement, you can't do it that way. Here's two workarounds:
str = ",|||||a|||||,|"
while str.gsub!(/,\|/, ',,'); end
str = ",|||||a|||||,|"
str.gsub!(/,(\|+)/) { "," * ($1.length + 1) }
smoke_weed_every_day = lambda do |piper|
commatosed = piper.gsub(',|', ',,')
commatosed == piper ? piper : smoke_weed_every_day.(commatosed)
end
smoke_weed_every_day.(",||||||||||||||") # => ",,,,,,,,,,,,,,,"
smoke_weed_every_day.(",|||||a|||||,|") # => ",,,,,,a|||||,,"
From an old library of mine. This method iterates until the block output is equal to its input :
def loop_until_convergence(x)
x = yield(previous = x) until previous == x
x
end
puts loop_until_convergence(',||||||||||||||') { |s| s.gsub(',|', ',,') }
# ",,,,,,,,,,,,,,,"
puts loop_until_convergence(',|||||a|||||,|') { |s| s.gsub(',|', ',,') }
# ",,,,,,a|||||,,"
As a bonus, you can calculate a square root in very few iterations :
def root(n)
loop_until_convergence(1) { |x| 0.5 * (x + n / x) }
end
p root(2)
# 1.414213562373095
p root(3)
# 1.7320508075688772
As with #Amandan's second solution there is no need to iterate until no further changes are made.
COMMA = ','
PIPE = '|'
def replace_pipes_after_comma(str)
run = false
str.gsub(/./) do |s|
case s
when PIPE
run ? COMMA : PIPE
when COMMA
run = true
COMMA
else
run = false
s
end
end
end
replace_pipes_after_comma ",||||||||||||||"
#=> ",,,,,,,,,,,,,,,"
replace_pipes_after_comma ",|||||a|||||,|"
#=> ",,,,,,a|||||,,"

lua variable name from user input

I am trying to make a "shell" in lua.
But the main problem is, I can not define the variable name from user input.
Here is the core of what I currently have. I am having an issue with the what[2] = what[3] line with the comment below.
How can I better implement this?
function lsplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
function def(what)
if (what[1] == "end") then
os.exit(0)
elseif (what[1] == "help") then
print("Commander version 0.0")
elseif (what[1] == "var") then
what[2] = what[3] --Can not define
else
print("[ERR] not a command!")
end
end
while(true) do
io.write("-->")
local usr = io.read("*l")
local cmd = lsplit(usr, " ")
def(cmd)
end
you are overwriting you first parameter with you second one, and not creating a new var... try this code! Should work but it is untested!
local userdefinedVars = { }
function lsplit(inputstr)
words = {}
for word in s:gmatch("%w+") do
table.insert(words, word)
end
end
function def(what)
if (what[1] == "end") then
os.exit(0)
elseif (what[1] == "help") then
print("Commander version 0.0")
elseif (what[1] == "var") then
-- This is how you get your things done!
userdefinedVars[what[2]] = what[3]
else
print("[ERR] not a command!")
end
end
while(true) do
io.write("--> ")
local usr = io.read("*line")
local cmd = lsplit(usr)
def(cmd)
end

Check if a Lua table member exists at any level

I need to check if a member exists in a table that isn't at the next level, but along a path of members.
foo = {}
if foo.bar.joe then
print(foo.bar.joe)
end
this will cast an attempt to index field 'bar' (a nil value) because bar isn't defined.
My usual solution is to test the chain, piece-by-piece.
foo = {}
if foo.bar and foo.bar.joe then
print(foo.bar.joe)
end
but this can be very tedious when there are many nested tables. Are there a better way to do this test than piece-by-piece?
I don't understand what you try to mean by "along a path of members". From the example, I assume you are trying to find a value in a "subtable"?
local function search(master, target) --target is a string
for k,v in next, master do
if type(v)=="table" and v[target] then return true end
end
end
A simple example. If you use such a function, you can pass the foo table and the joe string to see if foo.*.joe exists. Hope this helps.
debug.setmetatable(nil, {__index = {}})
foo = {}
print(foo.bar.baz.quux)
print(({}).prd.krt.skrz.drn.zprv.zhlt.hrst.zrn) -- sorry ))
To search for an element that is at any level of a table, I would use a method such as this one:
function exists(tab, element)
local v
for _, v in pairs(tab) do
if v == element then
return true
elseif type(v) == "table" then
return exists(v, element)
end
end
return false
end
testTable = {{"Carrot", {"Mushroom", "Lettuce"}, "Mayonnaise"}, "Cinnamon"}
print(exists(testTable, "Mushroom")) -- true
print(exists(testTable, "Apple")) -- false
print(exists(testTable, "Cinnamon")) -- true
I think you're looking for something along these lines:
local function get(Obj, Field, ...)
if Obj == nil or Field == nil then
return Obj
else
return get(Obj[Field], ...)
end
end
local foo = {x = {y = 7}}
assert(get() == nil)
assert(get(foo) == foo)
assert(get(foo, "x") == foo.x)
assert(get(foo, "x", "y") == 7)
assert(get(foo, "x", "z") == nil)
assert(get(foo, "bar", "joe") == nil)
assert(get(foo, "x", "y") or 41 == 7)
assert(get(foo, "bar", "joe") or 41 == 41)
local Path = {foo, "x", "y"}
assert(get(table.unpack(Path)) == 7)
get simply traverses the given path until a nil is encountered. Seems to do the job. Feel free to think up a better name than "get" though.
As usual, exercise care when combining with or.
I'm impressed by Egor's clever answer, but in general I think we ought to not rely on such hacks.
See also
The 'Safe Table Navigation' patch for Lua 5.2 : http://lua-users.org/wiki/LuaPowerPatches
Lengthy discussion on this matter : http://lua-users.org/lists/lua-l/2010-08/threads.html#00519
Related technique : http://lua-users.org/wiki/AutomagicTables
I suspect something relevant has been implemented in MetaLua, but I can't find at the moment.
If I understood your problem correctly, here's one possibility:
function isField(s)
local t
for key in s:gmatch('[^.]+') do
if t == nil then
if _ENV[ key ] == nil then return false end
t = _ENV[ key ]
else
if t[ key ] == nil then return false end
t = t[ key ]
end
--print(key) --for DEBUGGING
end
return true
end
-- To test
t = {}
t.a = {}
t.a.b = {}
t.a.b.c = 'Found me'
if isField('t.a.b.c') then print(t.a.b.c) else print 'NOT FOUND' end
if isField('t.a.b.c.d') then print(t.a.b.c.d) else print 'NOT FOUND' end
UPDATE: As per cauterite's suggestion, here's a version that also works with locals but has to take two arguments :(
function isField(t,s)
if t == nil then return false end
local t = t
for key in s:gmatch('[^.]+') do
if t[ key ] == nil then return false end
t = t[ key ]
end
return true
end
-- To test
local
t = {}
t.a = {}
t.a.b = {}
t.a.b.c = 'Found me'
if isField(t,'a.b.c') then print(t.a.b.c) else print 'NOT FOUND' end
if isField(t,'a.b.c.d') then print(t.a.b.c.d) else print 'NOT FOUND' end
foo = {}
foo.boo = {}
foo.boo.jeo = {}
foo.boo.joe is foo['boo']['joe'] and so
i make next function
function exist(t)
local words = {}
local command
for i,v in string.gmatch(t, '%w+') do words[#words+1] = i end
command = string.format('a = %s', words[1])
loadstring(command)()
if a == nil then return false end
for count=2, #words do
a = a[words[count]]
if a == nil then return false end
end
a = nil
return true
end
foo = {}
foo.boo = {}
foo.boo.joe = {}
print(exist('foo.boo.joe.b.a'))
using loadstring to make temp variable. my lua ver is 5.1
remove loadstring at 5.2 5.3, instead using load

Resources