Construct dynamic timer with lua - timer

I have created a timer called "timer", but I'm trying to create a function that will arm or disarm timer which is specified in it parameters
timer = sys.timer.create()
function MainTimer(timerName, action, time)
if action == "arm" then
timerName:arm(time)
else
timerName:disarm()
end
end
MainTimer("timer", "arm", 30)
but I'm getting an error from lua saying lua:272: attempt to call method 'arm' (a nil value)
where you think I did a mistake.
Thank you

Extra quotes :-)
MainTimer(timer, "arm", 30)

Related

LUA - Hammerspoon - Loop - eventtap keeps triggering

I'm trying to write a fairly simple script for Hammerspoon where I am looping through a table of app windows. The problem is for some reason when I call hs.eventtap inside the loop it keeps firing.
Any help much appreciated 🙏
function toggleMute()
local teams = hs.application.find("com.microsoft.teams"):allWindows()
if not (teams == null) then
for i, v in pairs(teams) do
hs.eventtap.keyStroke({"cmd", "shift"}, "m", 0, v)
end
end
hs.alert.show('Mute Toggled')
end

What method am I not using right?

I'm new to Julia and currently trying to run the following code:
Using DelimitedFiles
M=readdlm(data)
ts,A=M[:,1],M[:,2:end]
(nsweeps,N)=size(A)
dx=0.01;
x=[minimum(collect(A)):dx:maximum(collect(A))];
bx=[x-dx/2,x[end]+dx/2];
But, when I try to run the last line of code, it gives me the following error:
MethodError: no method
matching(::Array{StepRangeLen{Float64,Base.TwicePrecision
{Float64},Base.TwicePrecision{Float64}},1}, ::Float64)
Closest candidates are:
-(!Matched::BigFloat, ::Union{Float16, Float32, Float64}) at
mpfr.jl:437
-(!Matched::Complex{Bool}, ::Real) at complex.jl:307
-(!Matched::Missing, ::Number) at missing.jl:115
Can you please help me? Also, the data I'm using it's
30×6 Array{Float64,2}
UPDATE here's the whole function I'm trying to run is the following:
function mymain(filename,nsamples)
start_time=time()
M=readdlm(filename)
ts,A=M[:,1],M[:,2:end]
(nsweeps,N)=size(A)
dx=0.01;
x=[minimum(collect(A)):dx:maximum(collect(A))];
bx=[x-dx/2,x[end]+dx/2];
(bx,hA)=hist(A[:],bx);
f1=figure()
subplot(2,1,1); plot(ts,A,"-o"); xlabel("Time [ms]"); ylabel("Amps
[mV]");
subplot(2,1,2); plot(x,hA,"-"); xlabel("Amps [mV]");
ylabel("Density");draw()
nparams=8
Sx=Array(ASCIIString,1,nparams)
Rx=zeros(2,nparams)
nx=zeros(Int,1,nparams)
Sx[1,1]="p"; Rx[1:2,1]=[0.02,0.98]; nx[1]=49
Sx[1,2]="n"; Rx[1:2,2]=[1,20]; nx[2]=20
Sx[1,3]="tD"; Rx[1:2,3]=[50,200]; nx[3]=46
Sx[1,4]="a"; Rx[1:2,4]=[0.05,0.5]; nx[4]=46
Sx[1,5]="siga"; Rx[1:2,5]=[0.01,0.2]; nx[5]=39
Sx[1,6]="sigb"; Rx[1:2,6]=[0.01,0.1]; nx[6]=19
Sx[1,7]="tauf"; Rx[1:2,7]=[50,200]; nx[7]=46
Sx[1,8]="u1"; Rx[1:2,8]=Rx[1:2,1]; nx[8]=nx[1]
x=zeros(maximum(nx),nparams)
p=zeros(maximum(nx),nparams)
dx=zeros(1,nparams)
for j=1:nparams
x[1:nx[j],j]=linspace(Rx[1,j],Rx[2,j],nx[j])'
dx[j]=x[2,j]-x[1,j]
end
S=zeros(Int,nsamples,nparams)
sold=zeros(Int,1,nparams)
for j=1:nparams
sold[j]=rand(1:nx[j])
end
while x[sold[4],4]<=x[sold[5],5]
sold[4]=rand(1:nx[4])
sold[5]=rand(1:nx[5])
end
while x[sold[8],8]<=x[sold[1],1]
sold[1]=rand(1:nx[1])
sold[8]=rand(1:nx[8])
end
xold=zeros(1,nparams)
xnew=zeros(1,nparams)
for j=1:nparams
xold[j]=x[sold[j],j]
end
llold=myloglikelihood(xold,ts,A)
for k=1:nsamples
snew=sold+rand(-1:1,1,nparams)
if all(ones(1,nparams).<=snew.<=nx)
allowed2=x[snew[4],4]>x[snew[5],5]
allowed3=x[snew[8],8]>x[snew[1],1]
if allowed2&allowed3
for j=1:nparams
xnew[j]=x[snew[j],j]
end
llnew=myloglikelihood(xnew,ts,A)
if rand()<exp(llnew-llold)
sold,llold=snew,llnew
end
end
end
S[k,:]=sold
end
for k=1:nsamples
for j=1:nparams
p[S[k,j],j]+=1/(nsamples*dx[j])
end
end
f2=figure()
for j=1:nparams
subplot(2,4,j)
plot(x[1:nx[j],j],p[1:nx[j],j]);
xlabel(Sx[j])
end
diff_time=time()-start_time;
println("Total runtime
",round(diff_time,3),"s=",round(diff_time/60,1),"mins." );
return S
end
This goes in line with some other functions, but as you can see, this is the main function, so I really can't move forward without first runnning this one.
It isn't clear what outcome you are hoping for here. So I'll just give some pointers that hopefully help.
First, in this line:
x=[minimum(collect(A)):dx:maximum(collect(A))];
the calls to collect are redundant. Also, I suspect you are trying to construct a StepRangeLen, but by putting it in [] you actually are getting a Vector{StepRangeLen}. I think what you want in this line is actually this:
x=minimum(A):dx:maximum(A);
Second, in this line:
bx=[x-dx/2,x[end]+dx/2];
note that dx/2 is a Float64 while x is a StepRangeLen. This is important because the latter is a collection so if you want to perform this operation element-wise across the collection you need to broadcast, that is, x .- dx/2. Note, I suspect you may not be on the latest version of Julia, because when I run this the error message actually tells me explicitly I need to broadcast. Anyway, in contrast, x[end]+dx/2 is fine and does not need to be broadcast because x[end] is Float64. So I think you want:
bx=[x .- dx/2, x[end] + dx/2];
Having said that, it isn't clear to me why you want this bx, which is why I said at the start I'm not sure what outcome you were hoping for.

Lua : timer.cancel --> 'Attempt to index a nil value'

I'm fairly new to Lua, and one particular command in my code has been causing me some major problems.
I've been trying to cancel the timer:
currentPuddleDelay = timer.performWithDelay(puddleDelay, createPuddle);
The error that I am shown is:
Attempt to index a nil value
File: ?
stack traceback:
?: in function 'cancel'
game.lua:534: in function '?'
?: in function 'dispatchEvent'
?: in function '_saveSceneAndHide'
?: in function 'gotoScene'
game.lua:452: in function '?'
?: in function <?:182>
From what I've researched already, this problem can occur when the timer is within a function and is local, however, the timer in my code is global, so I don't think that that is the problem.
Below is the bit of code with the issue:
local function createPuddle()
local function constantDelay()
local puddle = display.newImage( sceneGroup, "images/puddle.png" )
puddle.x = puddleLane
puddle.y = -200
physics.addBody( puddle, "dynamic", {density=0, filter=puddleCollisionFilter} )
puddle:applyForce( 0, puddleSpeed, puddle.x, puddle.y )
sceneGroup:insert(3,puddle)
local function onPuddleCollision( self, event )
if ( event.phase == "began" ) then
print('puddle collision')
puddle:removeSelf( )
puddle = nil
composer.gotoScene( "menu" )
end
end
puddle.collision = onPuddleCollision
puddle:addEventListener( "collision" )
end
local constantDelayTimer = timer.performWithDelay(puddleDelay/2,constantDelay,1)
currentPuddleDelayHold = timer.performWithDelay(puddleDelay, createPuddle);
end
currentPuddleDelay = timer.performWithDelay(puddleDelay, createPuddle);
And then later on in the program:
timer.cancel(currentPuddleDelay)
Any help would be greatly appreciated.
I can only guess as you most likely did not provide all relevant code.
It obviously doesn't make sense to cancel a non-existing timer so for the start just do
if currentPuddleDelay then timer.cancel(currentPuddleDelay) end
If there is any reason why currentPuddleDelay should still exist you should find out why it is nil.

how to fetch value from an array and check its range in rails

I have included given code and its working fine
def check_ip
start = IPAddr.new(10.10.0.10).to_i
last = IPAddr.new(20.10.10.16).to_i
begin
ip_pool = IpPool.pluck(:start_ip, :end_ip)
# [["10.10.10.12", "10.10.10.15"], ["192.168.1.13", "192.168.1.13"]]
low = IPAddr.new("10.10.10.12").to_i
high = IPAddr.new("10.10.10.15").to_i
# it will check so on with ["192.168.1.13", "192.168.1.13"] values too
raise ArgumentError, I18n.t('errors.start') if ((low..high)===start or (low..high)===last
end
rescue ArgumentError => msg
self.errors.add(:start, msg)
return false
end
return true
end
Please guide me on how to implement this code without giving static value IPAddr.new("10.10.10.12").to_i I want to add values dynamically which I am fetching in ip_pool array so in low and high I am giving static values which are present in an array how could I give this values dynamically.
Since you have an array of low/high, you probably want to check all items in it:
begin
IpPool.pluck(:start_ip, :end_ip).each do |(low,high)|
raise ArgumentError, I18n.t('errors.start') \
if (low..high) === start || (low..high) === last
end
true
rescue ArgumentError => msg
self.errors.add(:start, msg)
false
end
Please note that I have the code a bit cleaned up:
removed superfluous returns;
corrected begin-rescue clause (there was a superfluous end right before rescue, that actually addressed rescue to the whole function body.

Creating a timer using Lua

I would like to create a timer using Lua, in a way that I could specify a callback function to be triggered after X seconds have passed.
What would be the best way to achieve this? ( I need to download some data from a webserver that will be parsed once or twice an hour )
Cheers.
If milisecond accuracy is not needed, you could just go for a coroutine solution, which you resume periodically, like at the end of your main loop, Like this:
require 'socket' -- for having a sleep function ( could also use os.execute(sleep 10))
timer = function (time)
local init = os.time()
local diff=os.difftime(os.time(),init)
while diff<time do
coroutine.yield(diff)
diff=os.difftime(os.time(),init)
end
print( 'Timer timed out at '..time..' seconds!')
end
co=coroutine.create(timer)
coroutine.resume(co,30) -- timer starts here!
while coroutine.status(co)~="dead" do
print("time passed",select(2,coroutine.resume(co)))
print('',coroutine.status(co))
socket.sleep(5)
end
This uses the sleep function in LuaSocket, you could use any other of the alternatives suggested on the Lua-users Wiki
Try lalarm, here:
http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/
Example (based on src/test.lua):
-- alarm([secs,[func]])
alarm(1, function() print(2) end); print(1)
Output:
1
2
If it's acceptable for you, you can try LuaNode. The following code sets a timer:
setInterval(function()
console.log("I run once a minute")
end, 60000)
process:loop()
use Script.SetTimer(interval, callbackFunction)
After reading this thread and others I decided to go with Luv lib. Here is my solution:
uv = require('luv') --luarocks install luv
function set_timeout(timeout, callback)
local timer = uv.new_timer()
local function ontimeout()
uv.timer_stop(timer)
uv.close(timer)
callback()
end
uv.timer_start(timer, timeout, 0, ontimeout)
return timer
end
set_timeout(1000, function() print('ok') end) -- time in ms
uv.run() --it will hold at this point until every timer have finished
On my Debian I've install lua-lgi packet to get access to the GObject based libraries.
The following code show you an usage demonstrating that you can use few asynchronuous callbacks:
local lgi = require 'lgi'
local GLib = lgi.GLib
-- Get the main loop object that handles all the events
local main_loop = GLib.MainLoop()
cnt = 0
function tictac()
cnt = cnt + 1
print("tic")
-- This callback will be called until the condition is true
return cnt < 10
end
-- Call tictac function every 2 senconds
GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, tictac)
-- You can also use an anonymous function like that
GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1,
function()
print( "There have been ", cnt, "tic")
-- This callback will never stop
return true
end)
-- Once everything is setup, you can start the main loop
main_loop:run()
-- Next instructions will be still interpreted
print("Main loop is running")
You can find more documentation about LGI here

Resources