LUA - Hammerspoon - Loop - eventtap keeps triggering - loops

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

Related

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.

Is there a way to check if any content of a array is in another array in Roblox

So I am trying to make a script which allows me to ban people but the main script which checks if a player is in the game and in the banned users list to be killed or kicked. Here is my code:
local BannedUsers = {"littleBitsman"}
local Players = game.Players:GetChildren()
wait(10)
for index1,value1 in ipairs(Players) do
for index2,value2 in ipairs(BannedUsers) do
if Players[index1] == BannedUsers[tonumber(index2)] then
local HumanoidToKill = workspace[value1].Character:FindFirstChildWhichIsA("Humanoid")
if HumanoidToKill.Health >= 0 then
HumanoidToKill.Health = 0
print("killed " .. tostring(value1))
end
end
end
end
The wait(10) is so I can test the script without executing too early, and the use of my username is for testing.
Also when I do test it it does nothing at all.
You can use the table.find function.
local BannedUsers = {"littleBitsman"}
for _, player in ipairs(game.Players:GetChildren()) do
if table.find(BannedUsers, player.Name) then
player:Kick("You are banned!")
end
end

Error: Can't Assign Function Call / Don't want to

It's friday and I'm tired and my brain obvs doesn't want to find this answer. Please help.
I want to assign the value to an array. It works in subsequent lines but not in one particular line, even though syntax seems the same to me? It seems to think I'm calling a function??
for entry in PROJECT:
i = i + 1
#A
if entry.startswith("A") :
ProjectA(i) = entry
#B
elif entry.startswith("B"):
ProjectB(i)= entry
#C
elif entry.startswith("C") :
ProjectC(i) = entry
# and Programme
elif entry.startswith("D") :
ProjectD(i) = entry
I'm told the problem is the last line: "ProjectD(i) = entry". Which to me seems like a replica of "ProjectC(i) = entry"
ProjectA(i) looks like you are calling a function; ProjectA[i] looks like an array element.

Retry loop until condition met

I am trying to navigate my mouse on object but I want to create a condition that will check if "surowiec" is still on the screen, if not I want to skip loop and go to another one. After it finish the second one get back to first and repeat.
[error] script [ Documents ] stopped with error in line 12 [error] FindFailed ( can not find surowiec.png in R[0,0 1920x1080]#S(0) )
w_lewo = Location(345,400)
w_prawo = Location(1570,400)
w_gore = Location(345,400)
w_dol = Location(345,400)
surowiec = "surowiec.png"
while surowiec:
if surowiec == surowiec:
exists("surowiec.png")
if exists != None:
click("surowiec.png")
wait(3)
exists("surowiec.png")
elif exists == None:
surowiec = None
click(w_prawo)
wait(8)
surowiec = surowiec
How about a small example:
while True:
if exists(surowiec):
print('A')
click(surowiec)
else:
print('B')
break
A while loop that is True will always run, until it it meets a break to exit the loop. Also have a look at the functions that are available in Sikuli, it can somethimes be hard to find them, that they are available. So here are a few nice ones:
Link: Link 1 and Pushing keys and Regions
The commands that I found myself very usefull are is exists and if not exists, and find that will allow to locate an image on the screen. Then you don't have to find an image over and over again if it stays on the same location. image1 = find(surowiec)

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