commit
stringlengths 40
40
| old_file
stringlengths 6
181
| new_file
stringlengths 6
181
| old_contents
stringlengths 448
7.17k
| new_contents
stringlengths 449
7.17k
| subject
stringlengths 0
450
| message
stringlengths 6
4.92k
| lang
stringclasses 1
value | license
stringclasses 12
values | repos
stringlengths 9
33.9k
|
---|---|---|---|---|---|---|---|---|---|
1a58efd77fddcd08c5ac8be877df965f592a695d
|
testserver/questsystem/Gravestone/trigger11.lua
|
testserver/questsystem/Gravestone/trigger11.lua
|
require("handler.createeffect")
require("questsystem.base")
module("questsystem.Gravestone.trigger11", package.seeall)
local QUEST_NUMBER = 10000
local PRECONDITION_QUESTSTATE = 88
local POSTCONDITION_QUESTSTATE = 99
local POSITION = position(605, 344, 0)
local RADIUS = 1
local LOOKAT_TEXT_DE = "Die Namen der Liebenden leuchten fr einen kurzen Moment auf."
local LOOKAT_TEXT_EN = "The names of the lovers brighten up for a brief moment."
function LookAtItem(PLAYER, item)
if PLAYER:isInRangeToPosition(POSITION,RADIUS)
and ADDITIONALCONDITIONS(PLAYER)
and questsystem.base.fulfilsPrecondition(PLAYER, QUEST_NUMBER, PRECONDITION_QUESTSTATE) then
base.lookat.SetSpecialDescription(item, LOOKAT_TEXT_DE, LOOKAT_TEXT_EN)
world:itemInform(PLAYER,item,base.lookat.GenerateLookAt(PLAYER, item, base.lookat.NONE));
HANDLER(PLAYER)
questsystem.base.setPostcondition(PLAYER, QUEST_NUMBER, POSTCONDITION_QUESTSTATE)
return true
end
return false
end
function HANDLER(PLAYER)
handler.createeffect.createEffect(position(605, 344, 0), 53):execute()
end
function ADDITIONALCONDITIONS(PLAYER)
return true
end
|
require("handler.createeffect")
require("questsystem.base")
module("questsystem.Gravestone.trigger11", package.seeall)
local QUEST_NUMBER = 10000
local PRECONDITION_QUESTSTATE = 88
local POSTCONDITION_QUESTSTATE = 99
local ADDITIONAL_QUESTSTATE = 104
local POSITION = position(605, 344, 0)
local RADIUS = 1
local LOOKAT_TEXT_DE = "Die Namen der Liebenden leuchten fr einen kurzen Moment auf."
local LOOKAT_TEXT_EN = "The names of the lovers brighten up for a brief moment."
function LookAtItem(PLAYER, item)
if PLAYER:isInRangeToPosition(POSITION,RADIUS)
and ADDITIONALCONDITIONS(PLAYER)
and PLAYER:getQuestProgress(QUEST_NUMBER) < ADDITIONAL_QUESTSTATE then
base.lookat.SetSpecialDescription(item, LOOKAT_TEXT_DE, LOOKAT_TEXT_EN)
world:itemInform(PLAYER,item,base.lookat.GenerateLookAt(PLAYER, item, base.lookat.NONE));
HANDLER(PLAYER)
questsystem.base.setPostcondition(PLAYER, QUEST_NUMBER, POSTCONDITION_QUESTSTATE)
return true
end
return false
end
function HANDLER(PLAYER)
handler.createeffect.createEffect(position(605, 344, 0), 53):execute()
end
function ADDITIONALCONDITIONS(PLAYER)
return true
end
|
lookat fix and precondition fix
|
lookat fix and precondition fix
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
|
1a671b2baeab163703ec9486d6950835272190b7
|
test_scripts/Polices/Policy_Table_Update/030_ATF_P_TC_Apply_PTU_and_OnPermissionChange_notify.lua
|
test_scripts/Polices/Policy_Table_Update/030_ATF_P_TC_Apply_PTU_and_OnPermissionChange_notify.lua
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PolicyTableUpdate] Apply PTU changes and OnPermissionChange notifying the apps
--
-- Description:
-- Right after the PoliciesManager merges the UpdatedPT with Local PT, it must apply the changes
-- and send onPermissionChange() notification to any registered mobile app in case the Updated PT
-- affected to this app`s policies.
-- a. SDL and HMI are running
-- b. AppID_1 is connected to SDL.
-- c. The device the app is running on is consented, appID1 requires PTU
-- d. Policy Table Update procedure is on stage waiting for:
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
-- e. 'policyfile' corresponds to PTU validation rules
-- Action:
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
-- Expected:
-- 1. PoliciesManager validates the updated PT (policyFile) e.i. verifyes, saves the updated fields
-- and everything that is defined with related requirements)
-- 2. On validation success:
-- SDL->HMI:OnStatusUpdate("UP_TO_DATE")
-- 3. SDL replaces the following sections of the Local Policy Table with the corresponding sections from PTU:
-- module_config,
-- functional_groupings,
-- app_policies
-- 4. SDL removes 'policyfile' from the directory
-- 5. SDL->appID_1: onPermissionChange(permisssions)
-- 6. SDL->HMI: SDL.OnAppPermissionChanged(appID_1, permissions)
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local json = require('json')
--[[ Local Variables ]]
local HMIAppID
-- Basic PTU file
local basic_ptu_file = "files/ptu.json"
-- PTU for registered app
local ptu_app_registered = "files/ptu_app.json"
-- Prepare parameters for app to save it in json file
local function PrepareJsonPTU1(name, new_ptufile)
local json_app = [[ {
"keep_context": false,
"steal_focus": false,
"priority": "NONE",
"default_hmi": "NONE",
"groups": [
"Base-4", "Emergency-1"
],
"RequestType":[
"TRAFFIC_MESSAGE_CHANNEL",
"PROPRIETARY",
"HTTP",
"QUERY_APPS"
]
}]]
local app = json.decode(json_app)
testCasesForPolicyTable:AddApplicationToPTJsonFile(basic_ptu_file, new_ptufile, name, app)
end
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
local mobile_session = require('mobile_session')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_initHMI()
self:initHMI()
end
function Test:Precondition_initHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
end
function Test.Precondition_PreparePTData()
PrepareJsonPTU1(config.application1.registerAppInterfaceParams.appID, ptu_app_registered)
end
--[[ end of Preconditions ]]
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:RegisterApp()
self.mobileSession:StartService(7)
:Do(function (_,_)
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
HMIAppID = data.params.application.appID
end)
EXPECT_RESPONSE(correlationId, { success = true })
EXPECT_NOTIFICATION("OnPermissionsChange")
end)
end
function Test:ActivateAppInFull()
commonSteps:ActivateAppInSpecificLevel(self,HMIAppID,"FULL")
end
function Test:UpdatePolicy_ExpectOnAppPermissionChangedWithAppID()
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptu_app_registered,
config.application1.registerAppInterfaceParams.appName,
self.mobileSession)
EXPECT_NOTIFICATION("OnPermissionsChange")
:ValidIf(function (_, data)
if data.payload~=nil then
return true
else
print("OnPermissionsChange came without permissions")
return false
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_RemovePTUfiles()
os.remove(ptu_app_registered)
end
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PolicyTableUpdate] Apply PTU changes and OnPermissionChange notifying the apps
--
-- Description:
-- Right after the PoliciesManager merges the UpdatedPT with Local PT, it must apply the changes
-- and send onPermissionChange() notification to any registered mobile app in case the Updated PT
-- affected to this app`s policies.
-- a. SDL and HMI are running
-- b. AppID_1 is connected to SDL.
-- c. The device the app is running on is consented, appID1 requires PTU
-- d. Policy Table Update procedure is on stage waiting for:
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
-- e. 'policyfile' corresponds to PTU validation rules
-- Action:
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
-- Expected:
-- 1. PoliciesManager validates the updated PT (policyFile) e.i. verifyes, saves the updated fields
-- and everything that is defined with related requirements)
-- 2. On validation success:
-- SDL->HMI:OnStatusUpdate("UP_TO_DATE")
-- 3. SDL replaces the following sections of the Local Policy Table with the corresponding sections from PTU:
-- module_config,
-- functional_groupings,
-- app_policies
-- 4. SDL removes 'policyfile' from the directory
-- 5. SDL->appID_1: onPermissionChange(permisssions)
-- 6. SDL->HMI: SDL.OnAppPermissionChanged(appID_1, permissions)
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local json = require('json')
--[[ Local Variables ]]
local HMIAppID
-- Basic PTU file
local basic_ptu_file = "files/ptu.json"
-- PTU for registered app
local ptu_app_registered = "files/ptu_app.json"
-- Prepare parameters for app to save it in json file
local function PrepareJsonPTU1(name, new_ptufile)
local json_app = [[ {
"keep_context": false,
"steal_focus": false,
"priority": "NONE",
"default_hmi": "NONE",
"groups": [
"Base-4", "Emergency-1"
]
}]]
local app = json.decode(json_app)
testCasesForPolicyTable:AddApplicationToPTJsonFile(basic_ptu_file, new_ptufile, name, app)
end
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
local mobile_session = require('mobile_session')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_initHMI()
self:initHMI()
end
function Test:Precondition_initHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
end
function Test.Precondition_PreparePTData()
PrepareJsonPTU1(config.application1.registerAppInterfaceParams.appID, ptu_app_registered)
end
--[[ end of Preconditions ]]
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:RegisterApp()
self.mobileSession:StartService(7)
:Do(function (_,_)
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
HMIAppID = data.params.application.appID
end)
EXPECT_RESPONSE(correlationId, { success = true })
EXPECT_NOTIFICATION("OnPermissionsChange")
end)
end
function Test:ActivateAppInFull()
commonSteps:ActivateAppInSpecificLevel(self,HMIAppID,"FULL")
end
function Test:UpdatePolicy_ExpectOnAppPermissionChangedWithAppID()
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function()
testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptu_app_registered,
config.application1.registerAppInterfaceParams.appName,
self.mobileSession)
end)
EXPECT_NOTIFICATION("OnPermissionsChange")
:ValidIf(function (_, data)
if data.payload~=nil then
return true
else
print("OnPermissionsChange came without permissions")
return false
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_RemovePTUfiles()
os.remove(ptu_app_registered)
end
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
Fix issue in script
|
Fix issue in script
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
02628622c7e5769fcc8f4c91ed29c8459bb256ad
|
MMOCoreORB/bin/scripts/managers/loot_manager.lua
|
MMOCoreORB/bin/scripts/managers/loot_manager.lua
|
--Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--Determines how often exceptional and legendary items can drop.
exceptionalChance = 100000 --1 in 100,000
legendaryChance = 1000000 --1 in 1,000,000
--exceptionalChance = 100 --1 in 100 for testing
--legendaryChance = 1000 --1 in 1000 for testing
--Determines how much of an increase in the base stats will be applied to the object.
exceptionalModifier = 2.5
legendaryModifier = 5.0
lootableStatMods = {
"aim",
"alert",
"armor_assembly",
"armor_experimentation",
"armor_repair",
"berserk",
"blind_defense",
"block",
"camouflage",
"carbine_accuracy",
"carbine_aim",
"carbine_hit_while_moving",
"carbine_speed",
"clothing_assembly",
"clothing_experimentation",
"clothing_repair",
"combat_bleeding_defense",
"combat_healing_ability",
"combat_medicine_assembly",
"combat_medicine_experimentation",
"counterattack",
"cover",
"dizzy_defense",
"dodge",
"droid_assembly",
"droid_complexity",
"droid_customization",
"droid_experimentation",
"droid_find_chance",
"droid_find_speed",
"droid_track_chance",
"droid_track_speed",
"food_assembly",
"food_experimentation",
"foraging",
"general_assembly",
"general_experimentation",
"grenade_assembly",
"grenade_experimentation",
"group_slope_move",
"healing_ability",
"healing_dance_mind",
"healing_dance_shock",
"healing_dance_wound",
"healing_injury_speed",
"healing_injury_treatment",
"healing_music_mind",
"healing_music_shock",
"healing_music_wound",
"healing_range",
"healing_range_speed",
"healing_wound_speed",
"healing_wound_treatment",
"heavy_rifle_lightning_accuracy",
"heavy_rifle_lightning_speed",
"heavyweapon_accuracy",
"heavyweapon_speed",
"instrument_assembly",
"intimidate",
"intimidate_defense",
"keep_creature",
"knockdown_defense",
"knockdown_defense",
"medical_foraging",
"medicine_assembly",
"medicine_experimentation",
"melee_defense",
"onehandmelee_accuracy",
"onehandmelee_damage",
"onehandmelee_speed",
"pistol_accuracy",
"pistol_aim",
"pistol_hit_while_moving",
"pistol_speed",
"pistol_standing",
"polearm_accuracy",
"polearm_speed",
"posture_change_down_defense",
"posture_change_up_defense",
"ranged_defense",
"rescue",
"resistance_bleeding",
"resistance_disease",
"resistance_fire",
"resistance_poison",
"rifle_accuracy",
"rifle_aim",
"rifle_hit_while_moving",
"rifle_prone",
"rifle_speed",
"slope_move",
"steadyaim",
"stored_pets",
"structure_assembly",
"structure_complexity",
"structure_experimentation",
"stun_defense",
"surveying",
"take_cover",
"tame_bonus",
"thrown_accuracy",
"thrown_speed",
"twohandmelee_accuracy",
"twohandmelee_damage",
"twohandmelee_speed",
"unarmed_accuracy",
"unarmed_damage",
"unarmed_speed",
"volley",
"warcry",
"weapon_assembly",
"weapon_experimentation",
"weapon_repair"
}
|
--Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--Determines how often exceptional and legendary items can drop.
exceptionalChance = 100000 --1 in 100,000
legendaryChance = 1000000 --1 in 1,000,000
--exceptionalChance = 100 --1 in 100 for testing
--legendaryChance = 1000 --1 in 1000 for testing
-- Determines what weapon templates will drop with DoTs on them. See Weapon Object for names.
weaponDotTemplates = {
"onehandmelee",
"pistol",
"polearm",
"twohandmelee"
}
-- Determines how often a Dot can drop off a weapon.
dotChance = 350 --1 in 350
-- Determines the maximum stats a DoT weapon can have.
dotPotencyMax = 100 --Percentage of potency (default 100%)
dotStrengthMax = 500 -- Amount of Strength max for the DoT.
dotDurationMax = 200 -- Max amount of duration in seconds possible to drop.
--Determines how much of an increase in the base stats will be applied to the object.
exceptionalModifier = 2.5
legendaryModifier = 5.0
lootableStatMods = {
"aim",
"alert",
"armor_assembly",
"armor_experimentation",
"armor_repair",
"berserk",
"blind_defense",
"block",
"camouflage",
"carbine_accuracy",
"carbine_aim",
"carbine_hit_while_moving",
"carbine_speed",
"clothing_assembly",
"clothing_experimentation",
"clothing_repair",
"combat_bleeding_defense",
"combat_healing_ability",
"combat_medicine_assembly",
"combat_medicine_experimentation",
"counterattack",
"cover",
"dizzy_defense",
"dodge",
"droid_assembly",
"droid_complexity",
"droid_customization",
"droid_experimentation",
"droid_find_chance",
"droid_find_speed",
"droid_track_chance",
"droid_track_speed",
"food_assembly",
"food_experimentation",
"foraging",
"general_assembly",
"general_experimentation",
"grenade_assembly",
"grenade_experimentation",
"group_slope_move",
"healing_ability",
"healing_dance_mind",
"healing_dance_shock",
"healing_dance_wound",
"healing_injury_speed",
"healing_injury_treatment",
"healing_music_mind",
"healing_music_shock",
"healing_music_wound",
"healing_range",
"healing_range_speed",
"healing_wound_speed",
"healing_wound_treatment",
"heavy_rifle_lightning_accuracy",
"heavy_rifle_lightning_speed",
"heavyweapon_accuracy",
"heavyweapon_speed",
"instrument_assembly",
"intimidate",
"intimidate_defense",
"keep_creature",
"knockdown_defense",
"knockdown_defense",
"medical_foraging",
"medicine_assembly",
"medicine_experimentation",
"melee_defense",
"onehandmelee_accuracy",
"onehandmelee_damage",
"onehandmelee_speed",
"pistol_accuracy",
"pistol_aim",
"pistol_hit_while_moving",
"pistol_speed",
"pistol_standing",
"polearm_accuracy",
"polearm_speed",
"posture_change_down_defense",
"posture_change_up_defense",
"ranged_defense",
"rescue",
"resistance_bleeding",
"resistance_disease",
"resistance_fire",
"resistance_poison",
"rifle_accuracy",
"rifle_aim",
"rifle_hit_while_moving",
"rifle_prone",
"rifle_speed",
"slope_move",
"steadyaim",
"stored_pets",
"structure_assembly",
"structure_complexity",
"structure_experimentation",
"stun_defense",
"surveying",
"take_cover",
"tame_bonus",
"thrown_accuracy",
"thrown_speed",
"twohandmelee_accuracy",
"twohandmelee_damage",
"twohandmelee_speed",
"unarmed_accuracy",
"unarmed_damage",
"unarmed_speed",
"volley",
"warcry",
"weapon_assembly",
"weapon_experimentation",
"weapon_repair"
}
|
[fixed] Loot manager script from my previous review.
|
[fixed] Loot manager script from my previous review.
Change-Id: Iaa58d170f363fd0f653f9fdc70d8246fa3ea43fd
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
512255b9006909969b22704fcdb57bbcc34d836c
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPlayerWeapon(source, prevSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif (weapons[source][1] ~= nil) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPlayerWeapon(source, prevSlot)
local newWeapon = getPlayerWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif (weapons[source][1] ~= nil and newWeapon == 30 or newWeapon == 31) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
Bug fix for weapon on back
|
Bug fix for weapon on back
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1656 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
9e18bf674b5480dc258a9d3237468f1b088972b4
|
share/media/guardian.lua
|
share/media/guardian.lua
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local Guardian = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Guardian.can_parse_url(qargs),
domains = table.concat({'guardian.co.uk'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = Guardian.fetch(qargs)
qargs.duration_ms = tonumber(p:match('duration%:%s+"?(%d+)"?') or 0) * 1000
qargs.title = p:match('"og:title" content="(.-)"') or ''
qargs.id = (p:match('containerID%s+=%s+["\'](.-)["\']')
or p:match('audioID%s+=%s+["\'](.-)["\']')
or ''):match('(%d+)') or ''
qargs.thumb_url = p:match('"thumbnail" content="(.-)"')
or p:match('"og:image" content="(.-)"') or ''
qargs.streams = Guardian.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function Guardian.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^https?$')
and t.host and t.host:lower():match('guardian%.co%.uk$')
and t.path and (t.path:lower():match('/video/')
or t.path:lower():match('/audio/'))
then
return true
else
return false
end
end
function Guardian.fetch(qargs)
local p = quvi.http.fetch(qargs.input_url).data
local e = p:match('<div class="expired">.-<p>(.-)</p>.-</div>') or ''
if #e >0 then error(e) end
return p
end
function Guardian.iter_streams(p)
local u = p:match('file:%s+"(.-)"')
or error("no match: media stream URL")
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local Guardian = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Guardian.can_parse_url(qargs),
domains = table.concat({'theguardian.com'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = Guardian.fetch(qargs)
qargs.duration_ms = Guardian.parse_duration(p)
qargs.title = (p:match('"og:title" content="(.-)"') or '')
:gsub('%s+%-%s+video','')
qargs.id = (p:match('prop8%s+=%s+["\'](.-)["\']') or '')
:match('(%d+)') or ''
qargs.thumb_url = p:match('"thumbnail" content="(.-)"')
or p:match('"og:image" content="(.-)"') or ''
qargs.streams = Guardian.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function Guardian.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^https?$')
and t.host and t.host:lower():match('theguardian%.com$')
and t.path and (t.path:lower():match('/video/')
or t.path:lower():match('/audio/'))
then
return true
else
return false
end
end
function Guardian.fetch(qargs)
local p = quvi.http.fetch(qargs.input_url).data
local e = p:match('<div class="expired">.-<p>(.-)</p>.-</div>') or ''
if #e >0 then error(e) end
return p
end
function Guardian.iter_streams(p)
local u = p:match("%s+file.-:%s+'(.-)'")
or error('no match: media stream URL')
local S = require 'quvi/stream'
local s = S.stream_new(u)
s.video.height = tonumber(p:match('itemprop="height" content="(%d+)"') or 0)
s.video.width = tonumber(p:match('itemprop="width" content="(%d+)"') or 0)
return {s}
end
function Guardian.parse_duration(p)
local n = tonumber(p:match('duration%:%s+"?(%d+)"?') or 0) * 1000
if n ==0 then
local m,s = p:match('T(%d+)M(%d+)S')
n = (tonumber(m)*60 + tonumber(s)) * 1000
end
return n
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/guardian.lua: Multiple patterns
|
FIX: media/guardian.lua: Multiple patterns
Notable changes:
* Update to support the new domain name ("theguardian.com")
* Add Guardian.parse_duration: use an additional pattern
* Update media stream URL pattern
* Remove "- video" from title
* Parse video {width,height}
* Update media ID pattern
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
|
b5089e2ad7597aea17ffa182f3760689c82e6b51
|
ffi/kobolight.lua
|
ffi/kobolight.lua
|
local ffi = require("ffi")
-- for closing on garbage collection, we need a pointer or aggregate
-- cdata object (not a plain "int"). So we encapsulate in a struct.
ffi.cdef[[
typedef struct light_fd { int ld; } light_fd;
]]
-- for ioctl header definition:
local dummy = require("ffi/posix_h")
local kobolight = {}
local kobolight_mt = {__index={}}
function kobolight_mt.__index:close()
-- this is redundant to garbage collection of the
-- whole object and not strictly needed.
-- it allows to force-close immediately, though.
if self.light_fd and self.light_fd.ld ~= -1 then
ffi.C.close(self.light_fd.ld)
self.light_fd.ld = -1
end
end
function kobolight_mt.__index:toggle()
if self.isOn then
self.savedBrightness = self.brightness
self:setBrightness(0)
else
self:setBrightness(self.savedBrightness or 0)
end
end
function kobolight_mt.__index:sleep()
if self.isOn then
self.sleepLight = true
self:toggle()
end
end
function kobolight_mt.__index:restore()
if self.sleepLight then
self:toggle()
end
end
function kobolight_mt.__index:setBrightness(brightness)
assert(brightness >= 0 and brightness <= 100,
"Wrong brightness value given!")
assert(ffi.C.ioctl(self.light_fd.ld, 241, ffi.cast("int", brightness)) == 0,
"cannot change brightess value")
self.brightness = brightness
if brightness > 0 then
self.isOn = true
else
self.isOn = false
end
end
function kobolight_mt.__index:restoreBrightness(brightness)
self.brightness = brightness
self.savedBrightness = brightness
end
function kobolight.open(device)
local light = {
light_fd = nil,
brightness = 0,
isOn = false
}
local ld = ffi.C.open(device or "/dev/ntx_io", ffi.C.O_RDWR)
assert(ld ~= -1, "cannot open light device")
light.light_fd = ffi.gc(
ffi.new("light_fd", ld),
function (light_fd) ffi.C.close(light_fd.ld) end
)
setmetatable(light, kobolight_mt)
return light
end
return kobolight
|
local ffi = require("ffi")
-- for closing on garbage collection, we need a pointer or aggregate
-- cdata object (not a plain "int"). So we encapsulate in a struct.
ffi.cdef[[
typedef struct light_fd { int ld; } light_fd;
]]
-- for ioctl header definition:
local dummy = require("ffi/posix_h")
local kobolight = {}
local kobolight_mt = {__index={}}
function kobolight_mt.__index:close()
-- this is redundant to garbage collection of the
-- whole object and not strictly needed.
-- it allows to force-close immediately, though.
if self.light_fd and self.light_fd.ld ~= -1 then
ffi.C.close(self.light_fd.ld)
self.light_fd.ld = -1
end
end
function kobolight_mt.__index:toggle()
if self.isOn then
self.savedBrightness = self.brightness
self:setBrightness(0)
else
self:setBrightness(self.savedBrightness or 0)
end
end
function kobolight_mt.__index:sleep()
if self.isOn then
self.sleepLight = true
self:toggle()
else
self.sleepLight = false
end
end
function kobolight_mt.__index:restore()
if self.sleepLight then
self:toggle()
end
end
function kobolight_mt.__index:setBrightness(brightness)
assert(brightness >= 0 and brightness <= 100,
"Wrong brightness value given!")
assert(ffi.C.ioctl(self.light_fd.ld, 241, ffi.cast("int", brightness)) == 0,
"cannot change brightess value")
self.brightness = brightness
if brightness > 0 then
self.isOn = true
else
self.isOn = false
end
end
function kobolight_mt.__index:restoreBrightness(brightness)
self.brightness = brightness
self.savedBrightness = brightness
end
function kobolight.open(device)
local light = {
light_fd = nil,
brightness = 0,
isOn = false
}
local ld = ffi.C.open(device or "/dev/ntx_io", ffi.C.O_RDWR)
assert(ld ~= -1, "cannot open light device")
light.light_fd = ffi.gc(
ffi.new("light_fd", ld),
function (light_fd) ffi.C.close(light_fd.ld) end
)
setmetatable(light, kobolight_mt)
return light
end
return kobolight
|
Fixes the bug that once true, self.sleepLight remains true
|
Fixes the bug that once true, self.sleepLight remains true
The issue occurred by suspending with the light on at least once.
From that moment, every consecutive resume would toggle the light
back on.
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,koreader/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,koreader/koreader-base,houqp/koreader-base,houqp/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,houqp/koreader-base
|
be9323f0d6f47e4ce48a2d8f30d6b5ab1ad4424d
|
twitpic.lua
|
twitpic.lua
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
if item_type == "image" then
if string.match(url, "twitpic%.com/"..item_value.."[^/]+/") then
if not html then
html = read_file(file)
end
for videourl in string.match(html, '<meta name="twitter:player:stream" value="(http[^"]+)"') do
table.insert(urls, { url=videourl })
end
for videosource in string.match(html, '<source src="(http[^"]+)"') do
table.insert(urls, { url=videosource })
end
end
end
return urls
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local ishtml = urlpos["link_expect_html"]
local parenturl = parent["url"]
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if item_type == "image" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "user" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "tag" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
-- Check if we are on the last page of a tag
elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then
if not html then
html = read_file(file)
end
if not string.match(url, '<div class="user%-photo%-content right">') then
return false
else
return verdict
end
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
if string.match(url["host"], "twitpic%.com") or
string.match(url["host"], "cloudfront%.net") or
string.match(url["host"], "twimg%.com") or
string.match(url["host"], "amazonaws%.com") then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
if item_type == "image" then
if string.match(url, "twitpic%.com/"..item_value.."[^/]+/") then
html = read_file(file)
for videourl in string.match(html, '<meta name="twitter:player:stream" value="(http[^"]+)"') do
table.insert(urls, { url=videourl })
end
for videosource in string.match(html, '<source src="(http[^"]+)"') do
table.insert(urls, { url=videosource })
end
end
end
return urls
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local ishtml = urlpos["link_expect_html"]
local parenturl = parent["url"]
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if item_type == "image" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "user" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "tag" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
-- Check if we are on the last page of a tag
elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then
if not html then
html = read_file(file)
end
if not string.match(url, '<div class="user%-photo%-content right">') then
return false
else
return verdict
end
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
if string.match(url["host"], "twitpic%.com") or
string.match(url["host"], "cloudfront%.net") or
string.match(url["host"], "twimg%.com") or
string.match(url["host"], "amazonaws%.com") then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
twitpic.lua: fix again for url scraping
|
twitpic.lua: fix again for url scraping
|
Lua
|
unlicense
|
ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab
|
2f2b80a1462d0f8f3c2ede6b1722a44501ac7bf1
|
splash/scripts/splash.lua
|
splash/scripts/splash.lua
|
--
-- Lua wrapper for Splash Python object.
--
-- It hides attributes that should not be exposed
-- and wraps async methods to `coroutine.yield`.
--
Splash = function (splash)
local self = {args=splash.args}
--
-- Create Lua splash:<...> methods from Python Splash object.
--
for key, is_async in pairs(splash.commands) do
local command = splash[key]
if is_async then
self[key] = function(self, ...)
-- XXX: can Lua code access command(...) result
-- from here? It should be prevented.
return coroutine.yield(command(...))
end
else
self[key] = function(self, ...)
return command(...)
end
end
end
function self._wait_restart_on_redirects(self, time, max_redirects)
if not time then
return true
end
local redirects_remaining = max_redirects
while redirects_remaining do
local ok, reason = self:wait(time)
if reason ~= 'redirect' then
return ok, reason
end
redirects_remaining = redirects_remaining - 1
end
error("Maximum number of redirects happen")
end
--
-- Default rendering script which implements
-- a common workflow: go to a page, wait for some time
-- (similar to splash.qtrender.DefaultRenderScript).
-- Currently it is incomplete.
--
function self.go_and_wait(self, args)
-- content-type for error messages. Callers should set their
-- own content-type before returning the result.
self:set_result_content_type("text/plain; charset=utf-8")
-- prepare & validate arguments
local args = args or self.args
local url = args.url
if not url then
error("'url' argument is required")
end
local wait = tonumber(args.wait)
if not wait and args.viewport == "full" then
error("non-zero 'wait' is required when viewport=='full'")
end
self:set_images_enabled(self.args.images)
-- if viewport is 'full' it should be set only after waiting
if args.viewport ~= "full" then
self:set_viewport(args.viewport)
end
local ok, reason = self:go{url=url, baseurl=args.baseurl}
if not ok then
-- render.xxx endpoints don't return HTTP errors as errors
if reason:sub(0,4) ~= 'http' then
error(reason)
end
end
assert(self:_wait_restart_on_redirects(wait, 10))
if args.viewport == "full" then
self:set_viewport(args.viewport)
end
end
return self
end
|
--
-- Lua wrapper for Splash Python object.
--
-- It hides attributes that should not be exposed
-- and wraps async methods to `coroutine.yield`.
--
Splash = function (splash)
local self = {args=splash.args}
--
-- Create Lua splash:<...> methods from Python Splash object.
--
for key, is_async in pairs(splash.commands) do
local command = splash[key]
if is_async then
self[key] = function(self, ...)
-- XXX: can Lua code access command(...) result
-- from here? It should be prevented.
return coroutine.yield(command(...))
end
else
self[key] = function(self, ...)
return command(...)
end
end
end
function self._wait_restart_on_redirects(self, time, max_redirects)
if not time then
return true
end
local redirects_remaining = max_redirects
while redirects_remaining do
local ok, reason = self:wait{time=time, cancel_on_redirect=true}
if reason ~= 'redirect' then
return ok, reason
end
redirects_remaining = redirects_remaining - 1
end
error("Maximum number of redirects happen")
end
--
-- Default rendering script which implements
-- a common workflow: go to a page, wait for some time
-- (similar to splash.qtrender.DefaultRenderScript).
-- Currently it is incomplete.
--
function self.go_and_wait(self, args)
-- content-type for error messages. Callers should set their
-- own content-type before returning the result.
self:set_result_content_type("text/plain; charset=utf-8")
-- prepare & validate arguments
local args = args or self.args
local url = args.url
if not url then
error("'url' argument is required")
end
local wait = tonumber(args.wait)
if not wait and args.viewport == "full" then
error("non-zero 'wait' is required when viewport=='full'")
end
self:set_images_enabled(self.args.images)
-- if viewport is 'full' it should be set only after waiting
if args.viewport ~= "full" then
self:set_viewport(args.viewport)
end
local ok, reason = self:go{url=url, baseurl=args.baseurl}
if not ok then
-- render.xxx endpoints don't return HTTP errors as errors
if reason:sub(0,4) ~= 'http' then
error(reason)
end
end
assert(self:_wait_restart_on_redirects(wait, 10))
if args.viewport == "full" then
self:set_viewport(args.viewport)
end
end
return self
end
|
fix _wait_restart_on_redirects function
|
fix _wait_restart_on_redirects function
|
Lua
|
bsd-3-clause
|
dwdm/splash,pawelmhm/splash,pombredanne/splash,kod3r/splash,pawelmhm/splash,kmike/splash,kmike/splash,Youwotma/splash,sunu/splash,Youwotma/splash,sunu/splash,kod3r/splash,kod3r/splash,sunu/splash,pombredanne/splash,dwdm/splash,dwdm/splash,pawelmhm/splash,Youwotma/splash,kmike/splash,pombredanne/splash
|
92fe63b6fdc7d8efece6306ec03ee3da38f80cf9
|
controller/probe.lua
|
controller/probe.lua
|
-- Module for interacting with the probe itself
require "config"
require "posix"
local sockets = require("socket")
probe = {}
-- some common utility functions
probe.leds_off = function() probe.set_leds(0,0,0) end
probe.green_glow = function() probe.set_leds(0,30,0) end
probe.fast_green_blink = function() probe.set_leds(0,255,0,50,100) end
probe.fast_red_blink = function() probe.set_leds(255,0,0,200,200) end
probe.slow_blue_blink = function(off_time) print(off_time) probe.set_leds(0,0,255,200,off_time) end
if config.spaceprobe_name == "simulation" then
-- shortcut the probe_sim module in its place
dofile("probe_sim.lua")
return
end
-- real probe functions follow
local function flush_input()
-- make a fake socket wrapper around a new file ref to read from, so we can see if there is dud data left in it
-- in case we got out of sync
-- needs to be new because we're closing it when we're done, it's a smelly hack
local tempread = io.open("/dev/" .. config.spaceprobe_name, "r")
if not tempread then
return nil
end
tempread:setvbuf("no")
local socket = sockets.tcp()
log("Flushing input...")
socket:connect("*", 0)
socket:setfd(posix.fileno(tempread))
local readers
repeat
readers = sockets.select({socket}, {}, 0.001) -- can't be zero to poll!
if #readers > 0 then
tempread:read(1)
end
until #readers == 0
tempread:close()
socket:close()
posix.sleep(1)
end
local function send_command(cmd)
--log("Sending command " .. cmd)
if not ttyr then
flush_input()
end
if not (ttyr and ttyw) then
ttyr = io.open("/dev/" .. config.spaceprobe_name, "r")
ttyw = io.open("/dev/" .. config.spaceprobe_name, "w")
if not (ttyr and ttyw) then
log("Failed to open /dev/" .. config.spaceprobe_name .. ". Not configured?")
return nil
end
ttyr:setvbuf("no")
ttyw:setvbuf("no")
end
ttyw:write(cmd .. "\n")
ttyw:flush()
local timeout = os.time() + 5 -- 5 second timeout
local res
while res==nil and os.time() < timeout do
res=ttyr:read("*line")
ttyr:flush()
end
if res then
res = res:gsub("[^%w]*", "")
--log("Got response " .. res)
else
log("Read timed out, device not available (command was " .. cmd .. ")")
ttyr:close()
ttyw:close()
ttyr = nil
ttyw = nil
end
return res
end
local function get_offline()
rsp = send_command("P") -- ping!
return (not rsp) or rsp ~= "OK"
end
local function set_dial(raw_value)
return send_command(string.format("D%04d", raw_value))
end
local function set_leds(r,g,b,blink_on_time,blink_off_time)
return send_command(string.format("L%04d,%04d,%04d,%04d,%04d",r,g,b,blink_on_time or 1,blink_off_time or 0))
end
local function buzz(seconds)
return send_command(string.format("B%04d", seconds*1000))
end
local last_position = nil
local function get_position()
res = tonumber(send_command("K"))
if res >= 1014 then
return last_position -- our probe has a bug where 0 and 1014 are interchangeable, so ignore any 1014s
end
last_position = res
return res
end
probe.get_position=get_position
probe.ping=get_offline
probe.get_offline=get_offline
probe.set_dial=set_dial
probe.set_leds=set_leds
probe.buzz=buzz
|
-- Module for interacting with the probe itself
require "config"
require "posix"
local sockets = require("socket")
probe = {}
-- some common utility functions
probe.leds_off = function() probe.set_leds(0,0,0) end
probe.green_glow = function() probe.set_leds(0,30,0) end
probe.fast_green_blink = function() probe.set_leds(0,255,0,50,100) end
probe.fast_red_blink = function() probe.set_leds(255,0,0,200,200) end
probe.slow_blue_blink = function(off_time) print(off_time) probe.set_leds(0,0,255,200,off_time) end
if config.spaceprobe_name == "simulation" then
-- shortcut the probe_sim module in its place
dofile("probe_sim.lua")
return
end
-- real probe functions follow
local function flush_input()
-- make a fake socket wrapper around a new file ref to read from, so we can see if there is dud data left in it
-- in case we got out of sync
-- needs to be new because we're closing it when we're done, it's a smelly hack
local tempread = io.open("/dev/" .. config.spaceprobe_name, "r")
if not tempread then
return nil
end
tempread:setvbuf("no")
local socket = sockets.tcp()
log("Flushing input...")
socket:connect("*", 0)
oldfd = socket:getfd()
socket:setfd(posix.fileno(tempread))
local readers
repeat
readers = sockets.select({socket}, {}, 0.001) -- can't be zero to poll!
if #readers > 0 then
tempread:read(1)
end
until #readers == 0
socket:setfd(oldfd)
socket:close()
tempread:close()
posix.sleep(1)
end
local function send_command(cmd)
--log("Sending command " .. cmd)
if not ttyr then
flush_input()
end
if not (ttyr and ttyw) then
ttyr = io.open("/dev/" .. config.spaceprobe_name, "r")
ttyw = io.open("/dev/" .. config.spaceprobe_name, "w")
if not (ttyr and ttyw) then
log("Failed to open /dev/" .. config.spaceprobe_name .. ". Not configured?")
return nil
end
ttyr:setvbuf("no")
ttyw:setvbuf("no")
end
ttyw:write(cmd .. "\n")
ttyw:flush()
local timeout = os.time() + 5 -- 5 second timeout
local res
while res==nil and os.time() < timeout do
res=ttyr:read("*line")
ttyr:flush()
end
if res then
res = res:gsub("[^%w]*", "")
--log("Got response " .. res)
else
log("Read timed out, device not available (command was " .. cmd .. ")")
ttyr:close()
ttyw:close()
ttyr = nil
ttyw = nil
end
return res
end
local function get_offline()
rsp = send_command("P") -- ping!
return (not rsp) or rsp ~= "OK"
end
local function set_dial(raw_value)
return send_command(string.format("D%04d", raw_value))
end
local function set_leds(r,g,b,blink_on_time,blink_off_time)
return send_command(string.format("L%04d,%04d,%04d,%04d,%04d",r,g,b,blink_on_time or 1,blink_off_time or 0))
end
local function buzz(seconds)
return send_command(string.format("B%04d", seconds*1000))
end
local last_position = nil
local function get_position()
res = tonumber(send_command("K"))
if res and (res >= 1014) then
return last_position -- our probe has a bug where 0 and 1014 are interchangeable, so ignore any 1014s
end
if res then
last_position = res
end
return res
end
probe.get_position=get_position
probe.ping=get_offline
probe.get_offline=get_offline
probe.set_dial=set_dial
probe.set_leds=set_leds
probe.buzz=buzz
|
Fix socket leak w/ socket hack, fix bug w/ last_pos when offline
|
Fix socket leak w/ socket hack, fix bug w/ last_pos when offline
|
Lua
|
mit
|
makehackvoid/MHV-Space-Probe
|
b7ce66f3f3e6827024e7588920d8bafbf85bc87d
|
plugins/set.lua
|
plugins/set.lua
|
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'user' then
return 'user:' .. msg.from.id .. ':variables'
end
return false
end
local function set_value(msg, name, value)
if (not name or not value) then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, name, value)
return name .. lang_text('saved')
end
end
local function set_media(msg, name)
if not name then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, 'waiting', name)
return lang_text('sendMedia')
end
end
local function callback(extra, success, result)
if success then
local file
if extra.media == 'photo' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg'
elseif extra.media == 'audio' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg'
end
file = file:gsub(':', '.')
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
redis:hset(extra.hash, extra.name, file)
redis:hdel(extra.hash, 'waiting')
print(file)
else
send_large_msg(extra.receiver, lang_text('errorDownloading') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver)
end
end
local function run(msg, matches)
local hash = get_variables_hash(msg)
if msg.media then
if hash then
local name = redis:hget(hash, 'waiting')
if is_momod(msg) then
if msg.media.type == 'photo' and name then
load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
return lang_text('mediaSaved')
elseif msg.media.type == 'audio' and name then
load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
return lang_text('mediaSaved')
end
else
return lang_text('require_mod')
end
return
else
return lang_text('nothingToSet')
end
end
if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then
if is_momod(msg) then
redis:hdel(hash, 'waiting')
return lang_text('cancelled')
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
return set_media(msg, name)
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
local value = string.sub(matches[3], 1, 4096)
return set_value(msg, name, value)
else
return lang_text('require_mod')
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '[' .. msg.media.type .. ']'
end
return msg
end
return {
description = "SET",
patterns =
{
"^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$",
"^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$",
"%[(photo)%]",
"%[(audio)%]",
-- set
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
"^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
-- setmedia
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
-- cancel
"^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
"^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
},
run = run,
min_rank = 1
-- usage
-- MOD
-- (#set|[sasha] setta) <var_name> <text>
-- (#setmedia|[sasha] setta media) <var_name>
-- (#cancel|[sasha] annulla)
}
|
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'user' then
return 'user:' .. msg.from.id .. ':variables'
end
return false
end
local function set_value(msg, name, value)
if (not name or not value) then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, name, value)
return name .. lang_text('saved')
end
end
local function set_media(msg, name)
if not name then
return lang_text('errorTryAgain')
end
local hash = get_variables_hash(msg)
if hash then
redis:hset(hash, 'waiting', name)
return lang_text('sendMedia')
end
end
local function callback(extra, success, result)
if success then
local file
if extra.media == 'photo' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg'
elseif extra.media == 'audio' then
file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg'
end
file = file:gsub(':', '.')
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
redis:hset(extra.hash, extra.name, file)
redis:hdel(extra.hash, 'waiting')
print(file)
else
send_large_msg(extra.receiver, lang_text('errorDownloading') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver)
end
end
local function run(msg, matches)
local hash = get_variables_hash(msg)
if msg.media then
if hash then
local name = redis:hget(hash, 'waiting')
if name then
if is_momod(msg) then
if msg.media.type == 'photo' then
load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
return lang_text('mediaSaved')
elseif msg.media.type == 'audio' then
load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type })
return lang_text('mediaSaved')
end
else
return lang_text('require_mod')
end
end
return
else
return lang_text('nothingToSet')
end
end
if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then
if is_momod(msg) then
redis:hdel(hash, 'waiting')
return lang_text('cancelled')
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
return set_media(msg, name)
else
return lang_text('require_mod')
end
elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then
if is_momod(msg) then
local name = string.sub(matches[2]:lower(), 1, 50)
local value = string.sub(matches[3], 1, 4096)
return set_value(msg, name, value)
else
return lang_text('require_mod')
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '[' .. msg.media.type .. ']'
end
return msg
end
return {
description = "SET",
patterns =
{
"^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$",
"^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$",
"%[(photo)%]",
"%[(audio)%]",
-- set
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
"^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$",
-- setmedia
"^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
"^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$",
-- cancel
"^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
"^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$",
},
run = run,
min_rank = 1
-- usage
-- MOD
-- (#set|[sasha] setta) <var_name> <text>
-- (#setmedia|[sasha] setta media) <var_name>
-- (#cancel|[sasha] annulla)
}
|
fix wrong message
|
fix wrong message
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
14fd25798f4f14537b59f001efcc80d11ed1e6d8
|
protocols/ppp/luasrc/model/network/proto_ppp.lua
|
protocols/ppp/luasrc/model/network/proto_ppp.lua
|
--[[
LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" or p == "pptp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
end
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh")
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
--[[
LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" or p == "pptp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
end
end
function proto.is_installed(self)
if nixio.fs.access("/lib/network/" .. p .. ".sh") then
return true
elseif p == "pppoa" then
return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil)
elseif p == "pppoe" then
return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil)
elseif p == "3g" then
return nixio.fs.access("/lib/netifd/proto/3g.sh")
else
return nixio.fs.access("/lib/netifd/proto/ppp.sh")
end
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
protocols/ppp: fix install state detection with netifd
|
protocols/ppp: fix install state detection with netifd
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8657 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
zwhfly/openwrt-luci,Flexibity/luci,Flexibity/luci,stephank/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,stephank/luci,freifunk-gluon/luci,vhpham80/luci,gwlim/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,vhpham80/luci,ch3n2k/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,yeewang/openwrt-luci,stephank/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,freifunk-gluon/luci,freifunk-gluon/luci,ch3n2k/luci,phi-psi/luci,8devices/carambola2-luci,jschmidlapp/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,gwlim/luci,phi-psi/luci,Flexibity/luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,stephank/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,stephank/luci,freifunk-gluon/luci,Canaan-Creative/luci,yeewang/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,saraedum/luci-packages-old,stephank/luci,Flexibity/luci,gwlim/luci,saraedum/luci-packages-old,8devices/carambola2-luci,saraedum/luci-packages-old,jschmidlapp/luci,freifunk-gluon/luci,gwlim/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ch3n2k/luci,eugenesan/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,zwhfly/openwrt-luci
|
1749ab7227bda347d167569e536382027f04de88
|
reader.lua
|
reader.lua
|
#!./luajit
io.stdout:write([[
---------------------------------------------
launching...
_ _____ ____ _
| |/ / _ \| _ \ ___ __ _ __| | ___ _ __
| ' / | | | |_) / _ \/ _` |/ _` |/ _ \ '__|
| . \ |_| | _ < __/ (_| | (_| | __/ |
|_|\_\___/|_| \_\___|\__,_|\__,_|\___|_|
[*] Current time: ]], os.date("%x-%X"), "\n\n")
io.stdout:flush()
-- load default settings
require("defaults")
local DataStorage = require("datastorage")
pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua")
require("setupkoenv")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = require("luasettings"):open(
DataStorage:getDataDir().."/settings.reader.lua")
local lang_locale = G_reader_settings:readSetting("language")
local _ = require("gettext")
if lang_locale then
_.changeLang(lang_locale)
end
-- option parsing:
local longopts = {
debug = "d",
profile = "p",
help = "h",
}
local function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-v debug in verbose mode")
print("-p enable Lua code profiling")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the AGPLv3.")
print("See http://github.com/koreader/koreader for more info.")
end
-- should check DEBUG option in arg and turn on DEBUG before loading other
-- modules, otherwise DEBUG in some modules may not be printed.
local dbg = require("dbg")
if G_reader_settings:readSetting("debug") then dbg:turnOn() end
local Profiler = nil
local ARGV = arg
local argidx = 1
while argidx <= #ARGV do
local arg = ARGV[argidx]
argidx = argidx + 1
if arg == "--" then break end
-- parse longopts
if arg:sub(1,2) == "--" then
local opt = longopts[arg:sub(3)]
if opt ~= nil then arg = "-"..opt end
end
-- code for each option
if arg == "-h" then
return showusage()
elseif arg == "-d" then
dbg:turnOn()
elseif arg == "-v" then
dbg:setVerbose(true)
elseif arg == "-p" then
Profiler = require("jit.p")
Profiler.start("la")
else
-- not a recognized option, should be a filename
argidx = argidx - 1
break
end
end
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Font = require("ui/font")
local ConfirmBox = require("ui/widget/confirmbox")
local function retryLastFile()
return ConfirmBox:new{
text = _("Cannot open last file.\nThis could be because it was deleted or because external storage is still being mounted.\nDo you want to retry?"),
ok_callback = function()
local last_file = G_reader_settings:readSetting("lastfile")
if lfs.attributes(last_file, "mode") == "file" then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(last_file)
end)
else
UIManager:show(retryLastFile())
end
end,
}
end
-- read some global reader setting here:
-- font
local fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
for k, v in pairs(fontmap) do
Font.fontmap[k] = v
end
end
-- last file
local last_file = G_reader_settings:readSetting("lastfile")
if last_file and lfs.attributes(last_file, "mode") ~= "file" then
UIManager:show(retryLastFile())
last_file = nil
end
-- load last opened file
local open_last = G_reader_settings:readSetting("open_last")
-- night mode
if G_reader_settings:readSetting("night_mode") then
Device.screen:toggleNightMode()
end
-- restore kobo frontlight settings and probe kobo touch coordinates
if Device:isKobo() then
if Device:hasFrontlight() then
local powerd = Device:getPowerDevice()
if powerd and powerd.restore_settings then
-- UIManager:init() should have sanely set up the frontlight_stuff by this point
local intensity = G_reader_settings:readSetting("frontlight_intensity")
powerd.fl_intensity = intensity or powerd.fl_intensity
local is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on")
if is_frontlight_on then
-- default powerd.is_fl_on is false, turn it on
powerd:toggleFrontlight()
else
-- the light can still be turned on manually outside of KOReader
-- or Nickel. so we always set the intensity to 0 here to keep it
-- in sync with powerd.is_fl_on (false by default)
-- NOTE: we cant use setIntensity method here because for Kobo the
-- min intensity is 1 :(
powerd.fl:setBrightness(0)
end
end
end
end
if Device:needsTouchScreenProbe() then
Device:touchScreenProbe()
end
if ARGV[argidx] and ARGV[argidx] ~= "" then
local file = nil
if lfs.attributes(ARGV[argidx], "mode") == "file" then
file = ARGV[argidx]
elseif open_last and last_file then
file = last_file
end
-- if file is given in command line argument or open last document is set
-- true, the given file or the last file is opened in the reader
if file then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(file)
end)
-- we assume a directory is given in command line argument
-- the filemanger will show the files in that path
else
local FileManager = require("apps/filemanager/filemanager")
local home_dir =
G_reader_settings:readSetting("home_dir") or ARGV[argidx]
UIManager:nextTick(function()
FileManager:showFiles(home_dir)
end)
end
UIManager:run()
elseif last_file then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(last_file)
end)
UIManager:run()
else
return showusage()
end
local function exitReader()
local ReaderActivityIndicator =
require("apps/reader/modules/readeractivityindicator")
G_reader_settings:close()
-- Close lipc handles
ReaderActivityIndicator:coda()
-- shutdown hardware abstraction
Device:exit()
if Profiler then Profiler.stop() end
os.exit(0)
end
exitReader()
|
#!./luajit
io.stdout:write([[
---------------------------------------------
launching...
_ _____ ____ _
| |/ / _ \| _ \ ___ __ _ __| | ___ _ __
| ' / | | | |_) / _ \/ _` |/ _` |/ _ \ '__|
| . \ |_| | _ < __/ (_| | (_| | __/ |
|_|\_\___/|_| \_\___|\__,_|\__,_|\___|_|
[*] Current time: ]], os.date("%x-%X"), "\n\n")
io.stdout:flush()
-- load default settings
require("defaults")
local DataStorage = require("datastorage")
pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua")
require("setupkoenv")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = require("luasettings"):open(
DataStorage:getDataDir().."/settings.reader.lua")
local lang_locale = G_reader_settings:readSetting("language")
local _ = require("gettext")
if lang_locale then
_.changeLang(lang_locale)
end
-- option parsing:
local longopts = {
debug = "d",
profile = "p",
help = "h",
}
local function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-v debug in verbose mode")
print("-p enable Lua code profiling")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the AGPLv3.")
print("See http://github.com/koreader/koreader for more info.")
end
-- should check DEBUG option in arg and turn on DEBUG before loading other
-- modules, otherwise DEBUG in some modules may not be printed.
local dbg = require("dbg")
if G_reader_settings:readSetting("debug") then dbg:turnOn() end
local Profiler = nil
local ARGV = arg
local argidx = 1
while argidx <= #ARGV do
local arg = ARGV[argidx]
argidx = argidx + 1
if arg == "--" then break end
-- parse longopts
if arg:sub(1,2) == "--" then
local opt = longopts[arg:sub(3)]
if opt ~= nil then arg = "-"..opt end
end
-- code for each option
if arg == "-h" then
return showusage()
elseif arg == "-d" then
dbg:turnOn()
elseif arg == "-v" then
dbg:setVerbose(true)
elseif arg == "-p" then
Profiler = require("jit.p")
Profiler.start("la")
else
-- not a recognized option, should be a filename
argidx = argidx - 1
break
end
end
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Font = require("ui/font")
local ConfirmBox = require("ui/widget/confirmbox")
local function retryLastFile()
return ConfirmBox:new{
text = _("Cannot open last file.\nThis could be because it was deleted or because external storage is still being mounted.\nDo you want to retry?"),
ok_callback = function()
local last_file = G_reader_settings:readSetting("lastfile")
if lfs.attributes(last_file, "mode") == "file" then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(last_file)
end)
else
UIManager:show(retryLastFile())
end
end,
}
end
-- read some global reader setting here:
-- font
local fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
for k, v in pairs(fontmap) do
Font.fontmap[k] = v
end
end
-- last file
local last_file = G_reader_settings:readSetting("lastfile")
-- load last opened file
local open_last = G_reader_settings:readSetting("open_last")
if open_last and last_file and lfs.attributes(last_file, "mode") ~= "file" then
UIManager:show(retryLastFile())
last_file = nil
end
-- night mode
if G_reader_settings:readSetting("night_mode") then
Device.screen:toggleNightMode()
end
-- restore kobo frontlight settings and probe kobo touch coordinates
if Device:isKobo() then
if Device:hasFrontlight() then
local powerd = Device:getPowerDevice()
if powerd and powerd.restore_settings then
-- UIManager:init() should have sanely set up the frontlight_stuff by this point
local intensity = G_reader_settings:readSetting("frontlight_intensity")
powerd.fl_intensity = intensity or powerd.fl_intensity
local is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on")
if is_frontlight_on then
-- default powerd.is_fl_on is false, turn it on
powerd:toggleFrontlight()
else
-- the light can still be turned on manually outside of KOReader
-- or Nickel. so we always set the intensity to 0 here to keep it
-- in sync with powerd.is_fl_on (false by default)
-- NOTE: we cant use setIntensity method here because for Kobo the
-- min intensity is 1 :(
powerd.fl:setBrightness(0)
end
end
end
end
if Device:needsTouchScreenProbe() then
Device:touchScreenProbe()
end
if ARGV[argidx] and ARGV[argidx] ~= "" then
local file = nil
if lfs.attributes(ARGV[argidx], "mode") == "file" then
file = ARGV[argidx]
elseif open_last and last_file then
file = last_file
end
-- if file is given in command line argument or open last document is set
-- true, the given file or the last file is opened in the reader
if file then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(file)
end)
-- we assume a directory is given in command line argument
-- the filemanger will show the files in that path
else
local FileManager = require("apps/filemanager/filemanager")
local home_dir =
G_reader_settings:readSetting("home_dir") or ARGV[argidx]
UIManager:nextTick(function()
FileManager:showFiles(home_dir)
end)
end
UIManager:run()
elseif last_file then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(last_file)
end)
UIManager:run()
else
return showusage()
end
local function exitReader()
local ReaderActivityIndicator =
require("apps/reader/modules/readeractivityindicator")
G_reader_settings:close()
-- Close lipc handles
ReaderActivityIndicator:coda()
-- shutdown hardware abstraction
Device:exit()
if Profiler then Profiler.stop() end
os.exit(0)
end
exitReader()
|
Fix 2716
|
Fix 2716
|
Lua
|
agpl-3.0
|
poire-z/koreader,pazos/koreader,mihailim/koreader,robert00s/koreader,Markismus/koreader,koreader/koreader,Frenzie/koreader,Frenzie/koreader,houqp/koreader,NiLuJe/koreader,Hzj-jie/koreader,lgeek/koreader,NiLuJe/koreader,apletnev/koreader,koreader/koreader,mwoz123/koreader,poire-z/koreader
|
54577de024fc35b6904994afe1906bcceeb8981c
|
libs/web/luasrc/dispatcher.lua
|
libs/web/luasrc/dispatcher.lua
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w-]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c or c.leaf then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
tpl.viewns.REQUEST_URI = luci.http.env.SCRIPT_NAME .. luci.http.env.PATH_INFO
if c and type(c.target) == "function" then
dispatched = c
stat, mod = pcall(require, c.module)
if stat then
luci.util.updfenv(c.target, mod)
end
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
--[[if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end]]--
createindex_plain(path, suff)
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cache = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cache = luci.fs.mtime(indexcache)
if not cache then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
cache = luci.fs.mtime(indexcache)
end
end
for i,c in ipairs(controllers) do
local module = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
local cachefile = indexcache .. "/" .. module
local stime
local ctime
if cache then
stime = luci.fs.mtime(c) or 0
ctime = luci.fs.mtime(cachefile) or 0
end
if not cache or stime > ctime then
stat, mod = pcall(require, module)
if stat and mod and type(mod.index) == "function" then
index[module] = mod.index
if cache then
luci.fs.writefile(cachefile, luci.util.dump(mod.index))
end
end
else
index[module] = loadfile(cachefile)
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
require("luci.i18n")
-- Load default translation
luci.i18n.loadc("default")
local scope = luci.util.clone(_G)
for k,v in pairs(_M) do
if type(v) == "function" then
scope[k] = v
end
end
for k, v in pairs(index) do
scope._NAME = k
setfenv(v, scope)
local stat, err = pcall(v)
if not stat then
error500(err)
os.exit(1)
end
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
c.module = getfenv(2)._NAME
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}, module=getfenv(2)._NAME}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function rewrite(n, ...)
local req = arg
return function()
for i=1,n do
table.remove(request, 1)
end
for i,r in ipairs(req) do
table.insert(request, i, r)
end
dispatch()
end
end
function call(name)
return function() getfenv()[name]() end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Dirty OpenWRT fix
if (os.time() < luci.fs.mtime(luci.sys.libpath() .. "/dispatcher.lua")) then
os.execute('date -s '..os.date('%m%d%H%M%Y', luci.fs.mtime(luci.sys.libpath() .. "/dispatcher.lua")))
end
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w-]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c or c.leaf then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
tpl.viewns.REQUEST_URI = luci.http.env.SCRIPT_NAME .. luci.http.env.PATH_INFO
if c and type(c.target) == "function" then
dispatched = c
stat, mod = pcall(require, c.module)
if stat then
luci.util.updfenv(c.target, mod)
end
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
--[[if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end]]--
createindex_plain(path, suff)
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cache = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cache = luci.fs.mtime(indexcache)
if not cache then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
cache = luci.fs.mtime(indexcache)
end
end
for i,c in ipairs(controllers) do
local module = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
local cachefile = indexcache .. "/" .. module
local stime
local ctime
if cache then
stime = luci.fs.mtime(c) or 0
ctime = luci.fs.mtime(cachefile) or 0
end
if not cache or stime > ctime then
stat, mod = pcall(require, module)
if stat and mod and type(mod.index) == "function" then
index[module] = mod.index
if cache then
luci.fs.writefile(cachefile, luci.util.dump(mod.index))
end
end
else
index[module] = loadfile(cachefile)
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
require("luci.i18n")
-- Load default translation
luci.i18n.loadc("default")
local scope = luci.util.clone(_G)
for k,v in pairs(_M) do
if type(v) == "function" then
scope[k] = v
end
end
for k, v in pairs(index) do
scope._NAME = k
setfenv(v, scope)
local stat, err = pcall(v)
if not stat then
error500(err)
os.exit(1)
end
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
c.module = getfenv(2)._NAME
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}, module=getfenv(2)._NAME}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function rewrite(n, ...)
local req = arg
return function()
for i=1,n do
table.remove(request, 1)
end
for i,r in ipairs(req) do
table.insert(request, i, r)
end
dispatch()
end
end
function call(name)
return function() getfenv()[name]() end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
* Added timing fix
|
* Added timing fix
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci
|
22ea445ef2df5245ca9a4864dd0a5b8897df83df
|
tools/structmsgTest/Lua/wsProvisioningServer.lua
|
tools/structmsgTest/Lua/wsProvisioningServer.lua
|
accessPointData=""
useBig=false
dofile("myConfig.lua")
dofile("buildStmsgAPList.lua")
dofile("buildStmsgAPListDefinition.lua")
function dbgPrint(s)
print(s)
end
-- Print AP list that is easier to read
function listap(t) -- (SSID : Authmode, RSSI, BSSID, Channel)
dbgPrint(string.format("%32s","SSID").."\tBSSID\t\t\t\t RSSI\t\tAUTHMODE\tCHANNEL")
--accessPointData="SSID\tBSSID\tRSSI\tAUTHMODE\tCHANNEL"
--sendAck("PROV","P","AA")
for ssid,v in pairs(t) do
local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)")
dbgPrint(string.format("%32s",ssid).."\t"..bssid.."\t "..rssi.."\t\t"..authmode.."\t\t\t"..channel)
--accessPointData=ssid.."\t"..bssid.."\t"..rssi.."\t"..authmode.."\t"..channel
--sendAck("MCU","P","AA")
end
end
function getNumRows(t)
local numRows=0
for ssid,v in pairs(t) do
print("t: "..tostring(ssid).." "..tostring(v))
numRows=numRows+1
end
print("numRows: "..tostring(numRows))
return numRows
end
--srv_sck=nil
junk=100
offset=0
cnt=1
function part2()
if (cnt > 10) then
return
end
print("part2")
if (offset == 0) then
return
end
len=string.len(encryptedDef)
if (offset+junk > len) then
endOffset = len
else
endOffset = offset+junk-1
end
if (endOffset == len) then
func=srv_close
else
func=nil
end
print("offset: "..tostring(offset).." endOffset: "..tostring(endOffset))
srv_sck:send(string.sub(encryptedDef,offset,endOffset),2,func)
offset=endOffset+1
if (endOffset == len) then
offset=0
end
cnt=cnt+1
end
function srv_listen(sck)
print("srv_listen")
srv_sck=sck
sck:on("receive",function(sck,payload)
print("receive: ".."!"..tostring(payload).."!")
srv_sck=sck
if (payload == "getaplist\r\n") then
wifi.sta.getap(buildAPList)
return
end
if (tostring(payload) == "getapdeflist\r\n") then
-- srv_sck:send("Hello World",1)
-- return
numRows=2
encryptedDef=buildStmsgAPDefList(t,useBig,numRows)
print("encryptedDef: "..tostring(string.len(encryptedDef)))
-- encryptedDef=crypto.encrypt("AES-CBC", cryptkey, "Hello world 1234",cryptkey)
-- srv_sck:send("HELLO: "..encryptedDef,1)
offset=1
srv_sck:send("",2,part2)
return
end
srv_sck:send("bad request",srv_close)
end)
-- numRows=2
-- encryptedDef=buildStmsgAPDefList(t,useBig,numRows)
--print("encryptedDef: "..tostring(string.len(encryptedDef)))
-- srv_sck:send(encryptedDef,srv_close)
end
function srv_connected(sck)
print("srv_connected")
sck:listen(port,srv_listen)
end
function srv_close(sck)
sck:close()
end
function buildAPList(t)
numRows=getNumRows(t)
encrypted=buildStmsgAPList(t,useBig,numRows)
srv_sck:send(encrypted,srv_close)
end
function chkRouterConnected(sck)
dbgPrint("is connected\r\n")
isConnected=true
end
function ProvisioningServerStart(big)
useBig=big
if srv ~= nil then
srv:close()
srv=nil
end
wifi.sta.disconnect()
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="SPIRIT21_Connect",auth=wifi.AUTH_OPEN})
if (not tmr.alarm(1,1000,tmr.ALARM_AUTO,function()
ip=wifi.ap.getip()
if (ip ~= nil) then
tmr.stop(1)
dbgPrint('Provisioning: wifi mode: '..tostring(wifi.getmode()))
dbgPrint("Provisioning: AP IP: "..tostring(wifi.ap.getip()))
dbgPrint("Provisioning: STA IP: "..tostring(wifi.sta.getip()))
-- wifi.sta.getap(listap)
srv=websocket.createServer(30,"/getapdeflist",srv_connected)
else
dbgPrint("IP: "..tostring(ip))
end
end)) then
dbgPrint("could not start timer for getap")
end
end
|
accessPointData=""
useBig=false
dofile("myConfig.lua")
dofile("buildStmsgAPList.lua")
dofile("buildStmsgAPListDefinition.lua")
function dbgPrint(s)
print(s)
end
-- Print AP list that is easier to read
function listap(t) -- (SSID : Authmode, RSSI, BSSID, Channel)
dbgPrint(string.format("%32s","SSID").."\tBSSID\t\t\t\t RSSI\t\tAUTHMODE\tCHANNEL")
--accessPointData="SSID\tBSSID\tRSSI\tAUTHMODE\tCHANNEL"
--sendAck("PROV","P","AA")
for ssid,v in pairs(t) do
local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)")
dbgPrint(string.format("%32s",ssid).."\t"..bssid.."\t "..rssi.."\t\t"..authmode.."\t\t\t"..channel)
--accessPointData=ssid.."\t"..bssid.."\t"..rssi.."\t"..authmode.."\t"..channel
--sendAck("MCU","P","AA")
end
end
function getNumRows(t)
local numRows=0
for ssid,v in pairs(t) do
print("t: "..tostring(ssid).." "..tostring(v))
numRows=numRows+1
end
print("numRows: "..tostring(numRows))
return numRows
end
--srv_sck=nil
junk=100
offset=0
cnt=1
function part2()
if (cnt > 10) then
return
end
print("part2")
if (offset == 0) then
return
end
len=string.len(encryptedDef)
if (offset+junk > len) then
endOffset = len
else
endOffset = offset+junk-1
end
if (endOffset == len) then
func=srv_close
else
func=nil
end
print("offset: "..tostring(offset).." endOffset: "..tostring(endOffset))
srv_sck:send(string.sub(encryptedDef,offset,endOffset),2,func)
offset=endOffset+1
if (endOffset == len) then
offset=0
end
cnt=cnt+1
end
numMsg=0
function srv_listen(sck)
print("srv_listen")
srv_sck=sck
sck:on("receive",function(sck,payload)
print("receive: ".."!"..tostring(payload).."!")
srv_sck=sck
if (payload == "getaplist\r\n") then
print("++getaplist")
wifi.sta.getap(buildAPList)
return
end
if (tostring(payload) == "getapdeflist\r\n") then
-- srv_sck:send("Hello World",1)
-- return
if (numMsg == 0) then
numRows=2
encryptedDef=buildStmsgAPDefList(t,useBig,numRows)
numMsg = numMsg+1
else
print("++getaplist")
wifi.sta.getap(buildAPList)
end
print("encryptedDef: "..tostring(string.len(encryptedDef)))
-- encryptedDef=crypto.encrypt("AES-CBC", cryptkey, "Hello world 1234",cryptkey)
-- srv_sck:send("HELLO: "..encryptedDef,1)
offset=1
srv_sck:send("",2,part2)
return
end
srv_sck:send("bad request",srv_close)
end)
-- numRows=2
-- encryptedDef=buildStmsgAPDefList(t,useBig,numRows)
--print("encryptedDef: "..tostring(string.len(encryptedDef)))
-- srv_sck:send(encryptedDef,srv_close)
end
function srv_connected(sck)
print("srv_connected")
sck:listen(port,srv_listen)
end
function srv_close(sck)
sck:close()
end
function buildAPList(t)
numRows=getNumRows(t)
encrypted=buildStmsgAPList(t,useBig,numRows)
srv_sck:send(encrypted,srv_close)
end
function chkRouterConnected(sck)
dbgPrint("is connected\r\n")
isConnected=true
end
function ProvisioningServerStart(big)
useBig=big
if srv ~= nil then
srv:close()
srv=nil
end
wifi.sta.disconnect()
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="testDevice_connect",auth=wifi.AUTH_OPEN})
if (not tmr.alarm(1,1000,tmr.ALARM_AUTO,function()
ip=wifi.ap.getip()
if (ip ~= nil) then
tmr.stop(1)
dbgPrint('Provisioning: wifi mode: '..tostring(wifi.getmode()))
dbgPrint("Provisioning: AP IP: "..tostring(wifi.ap.getip()))
dbgPrint("Provisioning: STA IP: "..tostring(wifi.sta.getip()))
-- wifi.sta.getap(listap)
srv=websocket.createServer(30,"/getapdeflist",srv_connected)
else
dbgPrint("IP: "..tostring(ip))
end
end)) then
dbgPrint("could not start timer for getap")
end
end
|
fixes.
|
fixes.
|
Lua
|
mit
|
apwiede/nodemcu-firmware,apwiede/nodemcu-firmware,apwiede/nodemcu-firmware,apwiede/nodemcu-firmware
|
c571e80eb353a18d29e191ef0076d97b4f39f72c
|
src/cosy/string.lua
|
src/cosy/string.lua
|
local Platform = require "cosy.platform"
local metatable = getmetatable ""
metatable.__mod = Platform.i18n.interpolate
-- > require "cosy.string"
-- > print ("%{key}" % { key = "some text" })
-- ...
-- some text
function string:quote ()
if not self:find ('"') then
return '"' .. self .. '"'
elseif not self:find ("'") then
return "'" .. self .. "'"
end
local pattern = ""
while true do
if not ( self:find ("%[" .. pattern .. "%[")
or self:find ("%]" .. pattern .. "%]")) then
return "[" .. pattern .. "[" .. self .. "]" .. pattern .. "]"
end
pattern = pattern .. "="
end
end
-- > require "cosy.string"
-- > local text = "abc"
-- > print (text:quote ())
-- ...
-- "abc"
-- > local text = [[a"bc]]
-- > print (text:quote ())
-- ...
-- 'a"bc'
-- > local text = [[a'bc]]
-- > print (text:quote ())
-- ...
-- "a'bc"
-- > local text = [[a"b'c]]
-- > print (text:quote ())
-- ...
-- [[a"b'c]]
-- > local text = [=[a[["b']]c]=]
-- > print (text:quote ())
-- ...
-- [=[a[["b']]c]=]
function string:is_identifier ()
local i, j = self:find ("[_%a][_%w]*")
return i == 1 and j == #self
end
-- > require "cosy.string"
-- > local text = "abc"
-- > print (text:is_identifier ())
-- ...
-- true
-- > local text = "0abc"
-- > print (text:is_identifier ())
-- ...
-- false
-- http://lua-users.org/wiki/StringTrim
function string:trim ()
return self:match "^()%s*$" and "" or self:match "^%s*(.*%S)"
end
-- > require "cosy.string"
-- > local text = " abc def "
-- > print (text:trim ())
-- ...
-- abc def
|
local metatable = getmetatable ""
-- > require "cosy.string"
-- taken from i18n/interpolate
metatable.__mod = function (pattern, variables)
variables = variables or {}
return pattern:gsub ("(.?)%%{(.-)}", function (previous, key)
if previous == "%" then
return
end
local value = tostring (variables [key])
return previous .. value
end)
end
-- > = "%{_1}-%{_2}-%{_3}" % {
-- > _1 = "abc",
-- > _2 = true,
-- > _3 = nil,
-- > }
-- "abc-true-nil"
-- > = "%%{_1}-%%{_2}-%%{_3}" % {
-- > _1 = "abc",
-- > _2 = true,
-- > _3 = nil,
-- > }
-- "%%{_1}-%%{_2}-%%{_3}"
-- http://stackoverflow.com/questions/9790688/escaping-strings-for-gsub
function string.escape (string)
return string
:gsub('%%', '%%%%')
:gsub('%^', '%%%^')
:gsub('%$', '%%%$')
:gsub('%(', '%%%(')
:gsub('%)', '%%%)')
:gsub('%.', '%%%.')
:gsub('%[', '%%%[')
:gsub('%]', '%%%]')
:gsub('%*', '%%%*')
:gsub('%+', '%%%+')
:gsub('%-', '%%%-')
:gsub('%?', '%%%?')
end
metatable.__div = function (pattern, string)
local names = {}
pattern = pattern:escape ()
pattern = pattern:gsub ("(.?)%%%%{(.-)}", function (previous, key)
if previous == "%" then
return
end
names [#names+1] = key
return previous .. "(.*)"
end)
if pattern:sub (1,1) ~= "^" then
pattern = "^" .. pattern
end
if pattern:sub (-1,1) ~= "$" then
pattern = pattern .. "$"
end
local results = { string:match (pattern) }
if #results == 0 then
return nil
end
local result = {}
for i = 1, #names do
result [names [i]] = results [i]
end
return result
end
-- > = "abc%{key}xyz" / "abcdefxyz"
-- { key = "def" }
-- > = "abc%{key}xyz" / "abcdefijk"
-- nil
-- > = "abc%%{key}xyz" / "abcdefxyz"
-- nil
function string.quote (s)
return string.format ("%q", s)
end
-- > local text = "abc"
-- > = text:quote ()
-- [["abc"]]
function string.is_identifier (s)
local i, j = s:find ("[_%a][_%w]*")
return i == 1 and j == #s
end
-- > local text = "abc"
-- > = text:is_identifier ()
-- true
-- > local text = "0abc"
-- > = text:is_identifier ()
-- false
-- http://lua-users.org/wiki/StringTrim
function string.trim (s)
return s:match "^()%s*$" and "" or s:match "^%s*(.*%S)"
end
-- > local text = " abc def "
-- > = text:trim ()
-- "abc def"
|
Fix string manipulation module.
|
Fix string manipulation module.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
f6a4436d84309da9bce7a5552a631ed1ffbb896c
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/memory.lua
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/memory.lua
|
--[[
(c) 2011 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.statistics.rrdtool.definitions.memory",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Memory usage",
vlabel = "MB",
number_format = "%5.1lf%s",
data = {
instances = {
memory = { "free", "buffered", "cached", "used" }
},
options = {
memory_buffered = { color = "0000ff", title = "Buffered" },
memory_cached = { color = "ff00ff", title = "Cached" },
memory_used = { color = "ff0000", title = "Used" },
memory_free = { color = "00ff00", title = "Free" }
}
}
}
end
|
--[[
(c) 2011 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.statistics.rrdtool.definitions.memory",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Memory usage",
vlabel = "MB",
number_format = "%5.1lf%s",
y_min = "0",
alt_autoscale_max = true,
data = {
instances = {
memory = { "free", "buffered", "cached", "used" }
},
options = {
memory_buffered = { color = "0000ff", title = "Buffered" },
memory_cached = { color = "ff00ff", title = "Cached" },
memory_used = { color = "ff0000", title = "Used" },
memory_free = { color = "00ff00", title = "Free" }
}
}
}
end
|
statistics: memory plugin - improve graph by better scaling of y-axis
|
statistics: memory plugin - improve graph by better scaling of y-axis
Utilise alt_autoscale_max to make the memory chart y-axis to scale better
for devices with e.g. 128 MB RAM.
Also fix the axis min value to 0.
Signed-off-by: Hannu Nyman <[email protected]>
(cherry picked from commit 9a06498dbdf5f5878d2ce86a4b9ac8abc9173bdc)
|
Lua
|
apache-2.0
|
db260179/openwrt-bpi-r1-luci,david-xiao/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,david-xiao/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,david-xiao/luci,david-xiao/luci,RuiChen1113/luci,david-xiao/luci,RuiChen1113/luci,RuiChen1113/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,david-xiao/luci,david-xiao/luci,RuiChen1113/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci
|
c0ee2f56f6b42dbae1376fe5d7d010861ec409a6
|
Modules/Shared/Time/Throttle/ThrottledFunction.lua
|
Modules/Shared/Time/Throttle/ThrottledFunction.lua
|
--- Throttles execution of a functon. Does both leading, and following
-- @classmod ThrottledFunction
local ThrottledFunction = {}
ThrottledFunction.ClassName = "ThrottledFunction"
ThrottledFunction.__index = ThrottledFunction
function ThrottledFunction.new(timeoutInSeconds, func, config)
local self = setmetatable({}, ThrottledFunction)
self._nextCallTimeStamp = 0
self._timeout = timeoutInSeconds or error("No timeoutInSeconds")
self._func = func or error("No func")
self._trailingValue = nil
self._callLeading = true
self._callTrailing = true
self:_configureOrError(config)
return self
end
function ThrottledFunction:Call(...)
if self._trailingValue then
-- Update the next value to be dispatched
self._trailingValue = table.pack(...)
elseif tick() >= self._nextCallTimeStamp then
if self._callLeading then
-- Dispatch immediately
self._nextCallTimeStamp = tick() + self._timeout
self._func(...)
elseif self._callTrailing then
-- Schedule for trailing at exactly timeout
self._trailingValue = table.pack(...)
delay(self._timeout, function()
if self.Destroy then
self:_dispatch()
end
end)
else
error("[ThrottledFunction.Cleanup] - Trailing and leading are both disabled")
end
else
-- As long as either leading or trailing are set to true, we are good
local remainingTime = tick() - self._nextCallTimeStamp
self._trailingValue = table.pack(...)
delay(remainingTime, function()
if self.Destroy then
self:_dispatch()
end
end)
end
end
function ThrottledFunction:_dispatch()
self._nextCallTimeStamp = tick() + self._timeout
local trailingValue = self._trailingValue
if trailingValue then
-- Clear before call so we are in valid state!
self._trailingValue = nil
self._func(unpack(trailingValue, 1, trailingValue.n))
end
end
function ThrottledFunction:_configureOrError(throttleConfig)
if throttleConfig == nil then
return
end
assert(type(throttleConfig) == "table")
for key, value in pairs(throttleConfig) do
assert(type(value) == "boolean")
if key == "leading" then
self._callLeading = value
elseif key == "trailing" then
self._callTrailing = value
else
error(("Bad key %q in config"):format(tostring(key)))
end
end
assert(self._callLeading or self._callTrailing, "Cannot configure both leading and trailing disabled")
end
function ThrottledFunction:Destroy()
self._trailingValue = nil
self._func = nil
setmetatable(self, nil)
end
return ThrottledFunction
|
--- Throttles execution of a functon. Does both leading, and following
-- @classmod ThrottledFunction
local ThrottledFunction = {}
ThrottledFunction.ClassName = "ThrottledFunction"
ThrottledFunction.__index = ThrottledFunction
function ThrottledFunction.new(timeoutInSeconds, func, config)
local self = setmetatable({}, ThrottledFunction)
self._nextCallTimeStamp = 0
self._timeout = timeoutInSeconds or error("No timeoutInSeconds")
self._func = func or error("No func")
self._trailingValue = nil
self._callLeading = true
self._callTrailing = true
self:_configureOrError(config)
return self
end
function ThrottledFunction:Call(...)
if self._trailingValue then
-- Update the next value to be dispatched
self._trailingValue = table.pack(...)
elseif self._nextCallTimeStamp <= tick() then
if self._callLeading then
-- Dispatch immediately
self._nextCallTimeStamp = tick() + self._timeout
self._func(...)
elseif self._callTrailing then
-- Schedule for trailing at exactly timeout
self._trailingValue = table.pack(...)
delay(self._timeout, function()
if self.Destroy then
self:_dispatch()
end
end)
else
error("[ThrottledFunction.Cleanup] - Trailing and leading are both disabled")
end
elseif self._callLeading or self._callTrailing then
-- As long as either leading or trailing are set to true, we are good
local remainingTime = self._nextCallTimeStamp - tick()
self._trailingValue = table.pack(...)
delay(remainingTime, function()
if self.Destroy then
self:_dispatch()
end
end)
end
end
function ThrottledFunction:_dispatch()
self._nextCallTimeStamp = tick() + self._timeout
local trailingValue = self._trailingValue
if trailingValue then
-- Clear before call so we are in valid state!
self._trailingValue = nil
self._func(unpack(trailingValue, 1, trailingValue.n))
end
end
function ThrottledFunction:_configureOrError(throttleConfig)
if throttleConfig == nil then
return
end
assert(type(throttleConfig) == "table")
for key, value in pairs(throttleConfig) do
assert(type(value) == "boolean")
if key == "leading" then
self._callLeading = value
elseif key == "trailing" then
self._callTrailing = value
else
error(("Bad key %q in config"):format(tostring(key)))
end
end
assert(self._callLeading or self._callTrailing, "Cannot configure both leading and trailing disabled")
end
function ThrottledFunction:Destroy()
self._trailingValue = nil
self._func = nil
setmetatable(self, nil)
end
return ThrottledFunction
|
Fix throttle
|
Fix throttle
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
07ece391af1e2f94316c6a9e7337dcd066957fb2
|
testserver/item/seeds.lua
|
testserver/item/seeds.lua
|
-- sowing seeds
require("base.common")
module("item.seeds", package.seeall)
-- UPDATE common SET com_script='item.seeds' WHERE com_itemid IN (259,291,534,2494,2917,728,773,779);
-- UPDATE common SET com_agingspeed = 2, com_objectafterrot = 247 WHERE com_itemid = 246;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 248 WHERE com_itemid = 247;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 246 WHERE com_itemid = 248;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 259 WHERE com_itemid = 259;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 289 WHERE com_itemid = 288;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 290 WHERE com_itemid = 289;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 291 WHERE com_itemid = 290;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 291 WHERE com_itemid = 291;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 536 WHERE com_itemid = 535;
-- UPDATE common SET com_agingspeed = 2, com_objectafterrot = 537 WHERE com_itemid = 536;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 534 WHERE com_itemid = 537;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 534 WHERE com_itemid = 534;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 2491 WHERE com_itemid = 2490;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 2492 WHERE com_itemid = 2491;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2494 WHERE com_itemid = 2492;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2494 WHERE com_itemid = 2494;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 539 WHERE com_itemid = 538;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 540 WHERE com_itemid = 539;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2917 WHERE com_itemid = 540;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2917 WHERE com_itemid = 2917;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 730 WHERE com_itemid = 729;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 731 WHERE com_itemid = 730;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 732 WHERE com_itemid = 731;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 732 WHERE com_itemid = 732;
function UseItem(User, SourceItem, ltstate)
content.gathering.InitGathering();
local farming = content.gathering.farming;
if ( seedPlantList == nil ) then
seedPlantList = {};
seedPlantList[259] = 246; -- grain
seedPlantList[291] = 288; --cabbage
seedPlantList[534] = 535; --onions
seedPlantList[2494] = 2490; --carrots
seedPlantList[2917] = 538; --tomatoes
seedPlantList[728] = 729; --hop
seedPlantList[773] = 774; --tobacco
seedPlantList[779] = 780; --sugarcane
end
if ( seedPlantList[SourceItem.id] == nil ) then
User:inform("[ERROR] Unknown seed item id: " .. SourceItem.id .. ". Please inform a developer.");
return;
end
-- is the target position needed?
local TargetPos = base.common.GetFrontPosition(User);
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
if (SourceItem:getType() ~= 4) then -- tool in Hand
base.common.HighInformNLS( User,
"Du musst das Saatgut in der Hand haben!",
"You have to hold the seeds in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
if not base.common.IsLookingAt( User, TargetPos ) then -- check looking direction
base.common.TurnTo( User, TargetPos ); -- turn if necessary
end
-- only on farm land
local Field = world:getField( TargetPos )
local groundType = base.common.GetGroundType( Field:tile() );
if ( groundType ~= 1 ) then
base.common.HighInformNLS(User,
"Du kannst nur auf Ackerboden Saatgut aussen.",
"Sowing seeds is only possible on farm land.");
return
end
-- not in winter
local month=world:getTime("month");
local season=math.ceil(month/4);
if (season == 4) then
base.common.HighInformNLS(User,
"Der Boden ist tief gefroren. Im Winter wirst du nichts anbauen knnen.",
"The ground is frozen deeply. You won't be able to plant anything in winter.");
return
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
farming.SavedWorkTime[User.id] = farming:GenWorkTime(User,nil);
User:startAction( farming.SavedWorkTime[User.id], 0, 0, 0, 0);
-- this is no batch action => no emote message, only inform player
if farming.SavedWorkTime[User.id] > 15 then
base.common.InformNLS(User,
"Du sst Saatgut aus.",
"You sow seeds.");
end
return
end
-- since we're here, we're working
if farming:FindRandomItem(User) then
return
end
User:learn( farming.LeadSkill, farming.SavedWorkTime[User.id], 20);
local amount = math.random(1,3); -- set the amount of items that are produced
world:createItemFromId( seedPlantList[SourceItem.id], 1, TargetPos, true, 333 ,{["amount"] = "" .. amount});
world:erase( SourceItem, 1 ); -- erase the seed
end
-- some plants rot to seeds again, those have a different data value
function MoveItemBeforeMove(User, SourceItem, TargetItem)
local amount = SourceItem:getData("amount");
if (amount ~= "") then
amount = tonumber(amount);
if (TargetItem:getType() == 3) then -- item on the map
local notCreated = User:createItem(SourceItem.id, amount, 333, nil);
if (notCreated > 0) then
world:createItemFromId( SourceItem.id, notCreated, SourceItem.pos, true, 333, nil );
end
else
world:createItemFromId( SourceItem.id, amount, SourceItem.pos, true, 333, nil );
end
world:erase( SourceItem, SourceItem.number );
end
return true;
end
function MoveItemAfterMove(User, SourceItem, TargetItem)
if (SourceItem:getData("amount") ~= "") then
world:erase( SourceItem, SourceItem.number );
end
end
|
-- sowing seeds
require("base.common")
module("item.seeds", package.seeall)
-- UPDATE common SET com_script='item.seeds' WHERE com_itemid IN (259,291,534,2494,2917,728,773,779);
-- UPDATE common SET com_agingspeed = 2, com_objectafterrot = 247 WHERE com_itemid = 246;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 248 WHERE com_itemid = 247;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 246 WHERE com_itemid = 248;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 259 WHERE com_itemid = 259;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 289 WHERE com_itemid = 288;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 290 WHERE com_itemid = 289;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 291 WHERE com_itemid = 290;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 291 WHERE com_itemid = 291;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 536 WHERE com_itemid = 535;
-- UPDATE common SET com_agingspeed = 2, com_objectafterrot = 537 WHERE com_itemid = 536;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 534 WHERE com_itemid = 537;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 534 WHERE com_itemid = 534;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 2491 WHERE com_itemid = 2490;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 2492 WHERE com_itemid = 2491;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2494 WHERE com_itemid = 2492;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2494 WHERE com_itemid = 2494;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 539 WHERE com_itemid = 538;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 540 WHERE com_itemid = 539;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2917 WHERE com_itemid = 540;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 2917 WHERE com_itemid = 2917;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 730 WHERE com_itemid = 729;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 731 WHERE com_itemid = 730;
-- UPDATE common SET com_agingspeed = 3, com_objectafterrot = 732 WHERE com_itemid = 731;
-- UPDATE common SET com_agingspeed = 4, com_objectafterrot = 732 WHERE com_itemid = 732;
function UseItem(User, SourceItem, ltstate)
content.gathering.InitGathering();
local farming = content.gathering.farming;
if ( seedPlantList == nil ) then
seedPlantList = {};
seedPlantList[259] = 246; -- grain
seedPlantList[291] = 288; --cabbage
seedPlantList[534] = 535; --onions
seedPlantList[2494] = 2490; --carrots
seedPlantList[2917] = 538; --tomatoes
seedPlantList[728] = 729; --hop
seedPlantList[773] = 774; --tobacco
seedPlantList[779] = 780; --sugarcane
end
if ( seedPlantList[SourceItem.id] == nil ) then
User:inform("[ERROR] Unknown seed item id: " .. SourceItem.id .. ". Please inform a developer.");
return;
end
-- is the target position needed?
local TargetPos = base.common.GetFrontPosition(User);
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
if (SourceItem:getType() ~= 4) then -- tool in Hand
base.common.HighInformNLS( User,
"Du musst das Saatgut in der Hand haben!",
"You have to hold the seeds in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
if not base.common.IsLookingAt( User, TargetPos ) then -- check looking direction
base.common.TurnTo( User, TargetPos ); -- turn if necessary
end
-- only on farm land
local Field = world:getField( TargetPos )
local groundType = base.common.GetGroundType( Field:tile() );
if ( groundType ~= 1 ) then
base.common.HighInformNLS(User,
"Du kannst nur auf Ackerboden Saatgut aussen.",
"Sowing seeds is only possible on farm land.");
return
end
-- not in winter
local month=world:getTime("month");
local season=math.ceil(month/4);
if (season == 4) then
base.common.HighInformNLS(User,
"Der Boden ist tief gefroren. Im Winter wirst du nichts anbauen knnen.",
"The ground is frozen deeply. You won't be able to plant anything in winter.");
return
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
farming.SavedWorkTime[User.id] = farming:GenWorkTime(User,nil);
User:startAction( farming.SavedWorkTime[User.id], 0, 0, 0, 0);
-- this is no batch action => no emote message, only inform player
if farming.SavedWorkTime[User.id] > 15 then
base.common.InformNLS(User,
"Du sst Saatgut aus.",
"You sow seeds.");
end
return
end
-- since we're here, we're working
if farming:FindRandomItem(User) then
return
end
User:learn( farming.LeadSkill, farming.SavedWorkTime[User.id], 20);
local amount = math.random(1,3); -- set the amount of items that are produced
world:createItemFromId( seedPlantList[SourceItem.id], 1, TargetPos, true, 333 ,{["amount"] = "" .. amount});
world:erase( SourceItem, 1 ); -- erase the seed
end
-- some plants rot to seeds again, those have a different data value
function MoveItemBeforeMove(User, SourceItem, TargetItem)
local amount = SourceItem:getData("amount");
if (amount ~= "") then
amount = tonumber(amount);
if (TargetItem:getType() == 3) then
-- item is dragged to the map
world:createItemFromId( SourceItem.id, amount, SourceItem.pos, true, 333, nil );
else
-- item is dragged to the User
local notCreated = User:createItem(SourceItem.id, amount, 333, nil);
if (notCreated > 0) then
world:createItemFromId( SourceItem.id, notCreated, SourceItem.pos, true, 333, nil );
end
end
world:erase( TargetItem, TargetItem.number );
end
return true;
end
function MoveItemAfterMove(User, SourceItem, TargetItem)
if (SourceItem:getData("amount") ~= "") then
world:erase( TargetItem, TargetItem.number );
end
end
|
fix seed duplicating bug
|
fix seed duplicating bug
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content
|
ff9286a4977072e95b033aefbf04cb4389ec420d
|
ffi/framebuffer_SDL2_0.lua
|
ffi/framebuffer_SDL2_0.lua
|
-- load common SDL input/video library
local SDL = require("ffi/SDL2_0")
local BB = require("ffi/blitbuffer")
local util = require("ffi/util")
local framebuffer = {
-- this blitbuffer will be used when we use refresh emulation
sdl_bb = nil,
}
function framebuffer:init()
if not self.dummy then
SDL.open()
self:_newBB()
else
self.bb = BB.new(600, 800)
end
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
framebuffer.parent.init(self)
end
function framebuffer:resize(w, h)
w = w or SDL.w
h = h or SDL.h
if not self.dummy then
self:_newBB(w, h)
else
self.bb:free()
self.bb = BB.new(600, 800)
end
if SDL.texture then SDL.destroyTexture(SDL.texture) end
SDL.texture = SDL.createTexture(w, h)
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
end
function framebuffer:_newBB(w, h)
w = w or SDL.w
h = h or SDL.h
if self.sdl_bb then self.sdl_bb:free() end
if self.bb then self.bb:free() end
if self.invert_bb then self.invert_bb:free() end
-- we present this buffer to the outside
local bb = BB.new(w, h, BB.TYPE_BBRGB32)
local flash = os.getenv("EMULATE_READER_FLASH")
if flash then
-- in refresh emulation mode, we use a shadow blitbuffer
-- and blit refresh areas from it.
self.sdl_bb = bb
self.bb = BB.new(w, h, BB.TYPE_BBRGB32)
else
self.bb = bb
end
self.invert_bb = BB.new(w, h, BB.TYPE_BBRGB32)
end
function framebuffer:_render(bb)
if bb:getInverse() == 1 then
self.invert_bb:invertblitFrom(bb)
SDL.SDL.SDL_UpdateTexture(SDL.texture, nil, self.invert_bb.data, self.invert_bb.pitch)
else
SDL.SDL.SDL_UpdateTexture(SDL.texture, nil, bb.data, bb.pitch)
end
SDL.SDL.SDL_RenderClear(SDL.renderer)
SDL.SDL.SDL_RenderCopy(SDL.renderer, SDL.texture, nil, nil)
SDL.SDL.SDL_RenderPresent(SDL.renderer)
end
function framebuffer:refreshFullImp(x, y, w, h)
if self.dummy then return end
local bb = self.full_bb or self.bb
if not (x and y and w and h) then
x = 0
y = 0
w = bb:getWidth()
h = bb:getHeight()
end
self.debug("refresh on physical rectangle", x, y, w, h)
local flash = os.getenv("EMULATE_READER_FLASH")
if flash then
self.sdl_bb:invertRect(x, y, w, h)
self:_render(bb)
util.usleep(tonumber(flash)*1000)
self.sdl_bb:setRotation(bb:getRotation())
self.sdl_bb:setInverse(bb:getInverse())
self.sdl_bb:blitFrom(bb, x, y, x, y, w, h)
end
self:_render(bb)
end
function framebuffer:setWindowTitle(new_title)
framebuffer.parent.setWindowTitle(self, new_title)
SDL.SDL.SDL_SetWindowTitle(SDL.screen, self.window_title)
end
function framebuffer:close()
SDL.SDL.SDL_Quit()
end
return require("ffi/framebuffer"):extend(framebuffer)
|
-- load common SDL input/video library
local SDL = require("ffi/SDL2_0")
local BB = require("ffi/blitbuffer")
local util = require("ffi/util")
local framebuffer = {
-- this blitbuffer will be used when we use refresh emulation
sdl_bb = nil,
}
function framebuffer:init()
if not self.dummy then
SDL.open()
self:_newBB()
else
self.bb = BB.new(600, 800)
end
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
framebuffer.parent.init(self)
end
function framebuffer:resize(w, h)
w = w or SDL.w
h = h or SDL.h
if not self.dummy then
self:_newBB(w, h)
else
self.bb:free()
self.bb = BB.new(600, 800)
end
if SDL.texture then SDL.destroyTexture(SDL.texture) end
SDL.texture = SDL.createTexture(w, h)
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
end
function framebuffer:_newBB(w, h)
w = w or SDL.w
h = h or SDL.h
local inverse
if self.sdl_bb then self.sdl_bb:free() end
if self.bb then
inverse = self.bb:getInverse() == 1
self.bb:free()
end
if self.invert_bb then self.invert_bb:free() end
-- we present this buffer to the outside
local bb = BB.new(w, h, BB.TYPE_BBRGB32)
local flash = os.getenv("EMULATE_READER_FLASH")
if flash then
-- in refresh emulation mode, we use a shadow blitbuffer
-- and blit refresh areas from it.
self.sdl_bb = bb
self.bb = BB.new(w, h, BB.TYPE_BBRGB32)
else
self.bb = bb
end
self.invert_bb = BB.new(w, h, BB.TYPE_BBRGB32)
-- reinit inverse mode on resize
if inverse then
self.bb:invert()
end
end
function framebuffer:_render(bb)
if bb:getInverse() == 1 then
self.invert_bb:invertblitFrom(bb)
SDL.SDL.SDL_UpdateTexture(SDL.texture, nil, self.invert_bb.data, self.invert_bb.pitch)
else
SDL.SDL.SDL_UpdateTexture(SDL.texture, nil, bb.data, bb.pitch)
end
SDL.SDL.SDL_RenderClear(SDL.renderer)
SDL.SDL.SDL_RenderCopy(SDL.renderer, SDL.texture, nil, nil)
SDL.SDL.SDL_RenderPresent(SDL.renderer)
end
function framebuffer:refreshFullImp(x, y, w, h)
if self.dummy then return end
local bb = self.full_bb or self.bb
if not (x and y and w and h) then
x = 0
y = 0
w = bb:getWidth()
h = bb:getHeight()
end
self.debug("refresh on physical rectangle", x, y, w, h)
local flash = os.getenv("EMULATE_READER_FLASH")
if flash then
self.sdl_bb:invertRect(x, y, w, h)
self:_render(bb)
util.usleep(tonumber(flash)*1000)
self.sdl_bb:setRotation(bb:getRotation())
self.sdl_bb:setInverse(bb:getInverse())
self.sdl_bb:blitFrom(bb, x, y, x, y, w, h)
end
self:_render(bb)
end
function framebuffer:setWindowTitle(new_title)
framebuffer.parent.setWindowTitle(self, new_title)
SDL.SDL.SDL_SetWindowTitle(SDL.screen, self.window_title)
end
function framebuffer:close()
SDL.SDL.SDL_Quit()
end
return require("ffi/framebuffer"):extend(framebuffer)
|
[fix] SDL2: apply night mode on window resize (#627)
|
[fix] SDL2: apply night mode on window resize (#627)
|
Lua
|
agpl-3.0
|
houqp/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,houqp/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,koreader/koreader-base,houqp/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base
|
9653139e395f94fce925803db9e82fd1a8053886
|
godmode/server/godmode.lua
|
godmode/server/godmode.lua
|
class 'GodMode'
local admins = {
"STEAM_0:0:26199873",
"STEAM_0:0:28323431",
}
local gods = {}
function GodMode:__init()
Events:Subscribe("PlayerChat", self, self.PlayerChat)
Events:Subscribe("PreTick", self, self.keepGodsAlive)
end
function isAdmin(player)
local adminstring = ""
for i,line in ipairs(admins) do
adminstring = adminstring .. line .. " "
end
if string.match(adminstring, player:GetSteamId().string) then
return true
end
return false
end
function isGod(player)
local godstring = ""
for i,line in ipairs(gods) do
godstring = godstring .. line .. " "
end
if string.match(godstring, player:GetSteamId().string) then
return true
end
return false
end
function getPlayerName(steamid)
for player in Server:GetPlayers() do
if steamid == player:GetSteamId().string then
return player:GetName()
end
end
end
function GodMode:addGod(player)
table.insert(gods,player:GetSteamId().string)
Chat:Broadcast(player:GetName() .. " is ", Color(200, 200, 200))
end
function GodMode:removeGod(player)
for i,v in ipairs(gods) do
if player:GetSteamId().string == v then
table.remove(gods,i)
Chat:Broadcast(player:GetName() .. " is mortal again!", Color(200, 200, 200))
end
end
end
function GodMode:keepGodsAlive()
for player in Server:GetPlayers() do
if isGod(player) then
if player:GetHealth() ~= 1 then
player:SetHealth(1)
end
end
end
end
function GodMode:PlayerChat(args)
if isAdmin(args.player) then
if args.text == "/godmode" then
if isGod(args.player) then
self:removeGod(args.player)
else
self:addGod(args.player)
end
return false
end
if args.text == "/gods" then
godNames = "No one is in Godmode."
for i,line in ipairs(gods) do
godNames = "Gods: "
if(i > 1) then
godNames = godNames .. ", "
end
godNames = godNames .. getPlayerName(line)
end
Chat:Broadcast(godNames,Color(200, 200, 200))
return false
end
return true
end
end
local godmode = GodMode()
|
class 'GodMode'
local admins = {
"STEAM_0:0:26199873",
"STEAM_0:0:28323431",
}
local gods = {}
function GodMode:__init()
Events:Subscribe("PlayerChat", self, self.PlayerChat)
Events:Subscribe("PreTick", self, self.keepGodsAlive)
end
function isAdmin(player)
local adminstring = ""
for i,line in ipairs(admins) do
adminstring = adminstring .. line .. " "
end
if string.match(adminstring, player:GetSteamId().string) then
return true
end
return false
end
function isGod(player)
local godstring = ""
for i,line in ipairs(gods) do
godstring = godstring .. line .. " "
end
if string.match(godstring, player:GetSteamId().string) then
return true
end
return false
end
function getPlayerName(steamid)
for player in Server:GetPlayers() do
if steamid == player:GetSteamId().string then
return player:GetName()
end
end
end
function GodMode:addGod(player)
table.insert(gods, player:GetSteamId().string)
Chat:Send(player, "You are now immortal!", Color(200, 200, 200))
end
function GodMode:removeGod(player)
for i,v in ipairs(gods) do
if player:GetSteamId().string == v then
table.remove(gods,i)
Chat:Send(player, "You are mortal again.", Color(200, 200, 200))
end
end
end
function GodMode:keepGodsAlive()
for player in Server:GetPlayers() do
if isGod(player) then
if player:GetHealth() ~= 1 then
player:SetHealth(1)
end
end
end
end
function GodMode:PlayerChat(args)
if args.text == "/godmode" then
if isAdmin(args.player) then
if isGod(args.player) then
self:removeGod(args.player)
else
self:addGod(args.player)
end
return false
else
Chat:Send(args.player, "[SERVER] You must be an admin to use this command.", Color(255, 0, 0))
end
end
if args.text == "/gods" then
if isAdmin(args.player) then
godNames = "No one is in Godmode."
for i,line in ipairs(gods) do
godNames = "Gods: "
if(i > 1) then
godNames = godNames .. ", "
end
if getPlayerName(line) == nil then
godNames = godNames .. line
else
godNames = godNames .. getPlayerName(line)
end
end
Chat:Send(args.player, godNames, Color(200, 200, 200))
return false
else
Chat:Send(args.player, "[SERVER] You must be an admin to use this command.", Color(255, 0, 0))
end
end
return true
end
local godmode = GodMode()
|
Fixed a small bug in the Godmode-script and added a message if you are not an admin
|
Fixed a small bug in the Godmode-script and added a message if you are not an admin
|
Lua
|
mit
|
Jokler/JC2MP-Scripts
|
9916a0c2f903b3388e51eab201eef04eb78163d6
|
modules/textadept/run.lua
|
modules/textadept/run.lua
|
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
---
-- Module for running/executing source files.
module('_m.textadept.run', package.seeall)
---
-- Executes the command line parameter and prints the output to Textadept.
-- @param command The command line string.
-- It can have the following macros:
-- * %(filepath) The full path of the current file.
-- * %(filedir) The current file's directory path.
-- * %(filename) The name of the file including extension.
-- * %(filename_noext) The name of the file excluding extension.
function execute(command)
local filepath = textadept.iconv(buffer.filename, _CHARSET, 'UTF-8')
local filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$')
local filename_noext = filename:match('^(.+)%.')
command = command:gsub('%%%b()', {
['%(filepath)'] = filepath,
['%(filedir)'] = filedir,
['%(filename)'] = filename,
['%(filename_noext)'] = filename_noext,
})
local current_dir = lfs.currentdir()
lfs.chdir(filedir)
local p = io.popen(command..' 2>&1')
local out = p:read('*all')
p:close()
lfs.chdir(current_dir)
textadept.print(textadept.iconv('> '..command..'\n'..out, 'UTF-8', _CHARSET))
buffer:goto_pos(buffer.length)
end
---
-- File extensions and their associated 'compile' actions.
-- Each key is a file extension whose value is a either a command line string to
-- execute or a function returning one.
-- @class table
-- @name compile_commands
compile_commands = {
c = 'gcc -pedantic -Os -o "%(filename_noext)" %(filename)',
cpp = 'g++ -pedantic -Os -o "%(filename_noext)" %(filename)',
java = 'javac "%(filename)"'
}
---
-- Compiles the file as specified by its extension in the compile_commands
-- table.
-- @see compile_commands
function compile()
if not buffer.filename then return end
local action = compile_commands[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- File extensions and their associated 'go' actions.
-- Each key is a file extension whose value is either a command line string to
-- execute or a function returning one.
-- @class table
-- @name run_commands
run_commands = {
c = '%(filedir)%(filename_noext)',
cpp = '%(filedir)%(filename_noext)',
java = function()
local buffer = buffer
local text = buffer:get_text()
local s, e, package
repeat
s, e, package = text:find('package%s+([^;]+)', e or 1)
until not s or buffer:get_style_name(buffer.style_at[s]) ~= 'comment'
if package then
local classpath = ''
for dot in package:gmatch('%.') do classpath = classpath..'../' end
return 'java -cp '..(WIN32 and '%CLASSPATH%;' or '$CLASSPATH:')..
classpath..'../ '..package..'.%(filename_noext)'
else
return 'java %(filename_noext)'
end
end,
lua = 'lua %(filename)',
pl = 'perl %(filename)',
php = 'php -f %(filename)',
py = 'python %(filename)',
rb = 'ruby %(filename)',
}
---
-- Runs/executes the file as specified by its extension in the run_commands
-- table.
-- @see run_commands
function run()
if not buffer.filename then return end
local action = run_commands[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- [Local table] A table of error string details.
-- Each entry is a table with the following fields:
-- pattern: the Lua pattern that matches a specific error string.
-- filename: the index of the Lua capture that contains the filename the error
-- occured in.
-- line: the index of the Lua capture that contains the line number the error
-- occured on.
-- message: [Optional] the index of the Lua capture that contains the error's
-- message. A call tip will be displayed if a message was captured.
-- When an error message is double-clicked, the user is taken to the point of
-- error.
-- @class table
-- @name error_details
local error_details = {
-- c, c++, and java errors and warnings have the same format as ruby ones
lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
perl = {
pattern = '^(.+) at (.-) line (%d+)',
message = 1, filename = 2, line = 3
},
php_error = {
pattern = '^Parse error: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
php_warning = {
pattern = '^Warning: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
python = {
pattern = '^%s*File "([^"]+)", line (%d+)',
filename = 1, line = 2
},
ruby = {
pattern = '^(.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
}
---
-- When the user double-clicks an error message, go to the line in the file
-- the error occured at and display a calltip with the error message.
-- @param pos The position of the caret.
-- @param line_num The line double-clicked.
-- @see error_details
function goto_error(pos, line_num)
local type = buffer._type
if type == locale.MESSAGE_BUFFER or type == locale.ERROR_BUFFER then
line = buffer:get_line(line_num)
for _, error_detail in pairs(error_details) do
local captures = { line:match(error_detail.pattern) }
if #captures > 0 then
local lfs = require 'lfs'
local utf8_filename = captures[error_detail.filename]
local filename = textadept.iconv(utf8_filename, _CHARSET, 'UTF-8')
if lfs.attributes(filename) then
textadept.io.open(utf8_filename)
_m.textadept.editing.goto_line(captures[error_detail.line])
local msg = captures[error_detail.message]
if msg then buffer:call_tip_show(buffer.current_pos, msg) end
else
error(string.format(
locale.M_TEXTADEPT_RUN_FILE_DOES_NOT_EXIST, utf8_filename))
end
break
end
end
end
end
textadept.events.add_handler('double_click', goto_error)
|
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
---
-- Module for running/executing source files.
module('_m.textadept.run', package.seeall)
---
-- Executes the command line parameter and prints the output to Textadept.
-- @param command The command line string.
-- It can have the following macros:
-- * %(filepath) The full path of the current file.
-- * %(filedir) The current file's directory path.
-- * %(filename) The name of the file including extension.
-- * %(filename_noext) The name of the file excluding extension.
function execute(command)
local filepath = textadept.iconv(buffer.filename, _CHARSET, 'UTF-8')
local filedir, filename
if filepath:find('[/\\]') then
filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$')
else
filedir, filename = '', filepath
end
local filename_noext = filename:match('^(.+)%.')
command = command:gsub('%%%b()', {
['%(filepath)'] = filepath,
['%(filedir)'] = filedir,
['%(filename)'] = filename,
['%(filename_noext)'] = filename_noext,
})
local current_dir = lfs.currentdir()
lfs.chdir(filedir)
local p = io.popen(command..' 2>&1')
local out = p:read('*all')
p:close()
lfs.chdir(current_dir)
textadept.print(textadept.iconv('> '..command..'\n'..out, 'UTF-8', _CHARSET))
buffer:goto_pos(buffer.length)
end
---
-- File extensions and their associated 'compile' actions.
-- Each key is a file extension whose value is a either a command line string to
-- execute or a function returning one.
-- @class table
-- @name compile_commands
compile_commands = {
c = 'gcc -pedantic -Os -o "%(filename_noext)" %(filename)',
cpp = 'g++ -pedantic -Os -o "%(filename_noext)" %(filename)',
java = 'javac "%(filename)"'
}
---
-- Compiles the file as specified by its extension in the compile_commands
-- table.
-- @see compile_commands
function compile()
if not buffer.filename then return end
local action = compile_commands[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- File extensions and their associated 'go' actions.
-- Each key is a file extension whose value is either a command line string to
-- execute or a function returning one.
-- @class table
-- @name run_commands
run_commands = {
c = '%(filedir)%(filename_noext)',
cpp = '%(filedir)%(filename_noext)',
java = function()
local buffer = buffer
local text = buffer:get_text()
local s, e, package
repeat
s, e, package = text:find('package%s+([^;]+)', e or 1)
until not s or buffer:get_style_name(buffer.style_at[s]) ~= 'comment'
if package then
local classpath = ''
for dot in package:gmatch('%.') do classpath = classpath..'../' end
return 'java -cp '..(WIN32 and '%CLASSPATH%;' or '$CLASSPATH:')..
classpath..'../ '..package..'.%(filename_noext)'
else
return 'java %(filename_noext)'
end
end,
lua = 'lua %(filename)',
pl = 'perl %(filename)',
php = 'php -f %(filename)',
py = 'python %(filename)',
rb = 'ruby %(filename)',
}
---
-- Runs/executes the file as specified by its extension in the run_commands
-- table.
-- @see run_commands
function run()
if not buffer.filename then return end
local action = run_commands[buffer.filename:match('[^.]+$')]
if action then execute(type(action) == 'function' and action() or action) end
end
---
-- [Local table] A table of error string details.
-- Each entry is a table with the following fields:
-- pattern: the Lua pattern that matches a specific error string.
-- filename: the index of the Lua capture that contains the filename the error
-- occured in.
-- line: the index of the Lua capture that contains the line number the error
-- occured on.
-- message: [Optional] the index of the Lua capture that contains the error's
-- message. A call tip will be displayed if a message was captured.
-- When an error message is double-clicked, the user is taken to the point of
-- error.
-- @class table
-- @name error_details
local error_details = {
-- c, c++, and java errors and warnings have the same format as ruby ones
lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
perl = {
pattern = '^(.+) at (.-) line (%d+)',
message = 1, filename = 2, line = 3
},
php_error = {
pattern = '^Parse error: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
php_warning = {
pattern = '^Warning: (.+) in (.-) on line (%d+)',
message = 1, filename = 2, line = 3
},
python = {
pattern = '^%s*File "([^"]+)", line (%d+)',
filename = 1, line = 2
},
ruby = {
pattern = '^(.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
},
}
---
-- When the user double-clicks an error message, go to the line in the file
-- the error occured at and display a calltip with the error message.
-- @param pos The position of the caret.
-- @param line_num The line double-clicked.
-- @see error_details
function goto_error(pos, line_num)
local type = buffer._type
if type == locale.MESSAGE_BUFFER or type == locale.ERROR_BUFFER then
line = buffer:get_line(line_num)
for _, error_detail in pairs(error_details) do
local captures = { line:match(error_detail.pattern) }
if #captures > 0 then
local lfs = require 'lfs'
local utf8_filename = captures[error_detail.filename]
local filename = textadept.iconv(utf8_filename, _CHARSET, 'UTF-8')
if lfs.attributes(filename) then
textadept.io.open(utf8_filename)
_m.textadept.editing.goto_line(captures[error_detail.line])
local msg = captures[error_detail.message]
if msg then buffer:call_tip_show(buffer.current_pos, msg) end
else
error(string.format(
locale.M_TEXTADEPT_RUN_FILE_DOES_NOT_EXIST, utf8_filename))
end
break
end
end
end
end
textadept.events.add_handler('double_click', goto_error)
|
Fixed bug for running filename with no path; modules/textadept/run.lua
|
Fixed bug for running filename with no path; modules/textadept/run.lua
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
0f2617fbc7afcab399284da1e4881a6dc7da8490
|
UCDanticheat/togglecontrol.lua
|
UCDanticheat/togglecontrol.lua
|
addCommandHandler("tog",
function ()
outputDebugString(tostring(not isControlEnabled("fire")))
toggleControl("fire", not isControlEnabled("fire"))
end
)
local fireKeys = getBoundKeys("fire")
local exceptedWeapons = {[41] = true}
local exceptedSlots = {[0] = true, [1] = true, [8] = true, [10] = true, [11] = true, [12] = true}
function aimCheck(button, state)
if (localPlayer.vehicle) then return end
if (fireKeys[button] and state == true) then
if (exceptedSlots[localPlayer.weaponSlot] or exceptedWeapons[localPlayer:getWeapon()]) then
return
end
--outputDebugString("fire")
if (getControlState("aim_weapon")) then
--outputDebugString("is aiming")
else
toggleControl("fire", false)
--outputDebugString("not aiming")
end
end
if (fireKeys[button] and state == false) then
if (exports.UCDsafeZones:isElementWithinSafeZone(localPlayer) or localPlayer.frozen) then return end
toggleControl("fire", true)
end
end
addEventHandler("onClientKey", root, aimCheck)
|
addCommandHandler("tog",
function ()
outputDebugString(tostring(not isControlEnabled("fire")))
toggleControl("fire", not isControlEnabled("fire"))
end
)
local aimKeys = getBoundKeys("aim_weapon")
local fireKeys = getBoundKeys("fire")
local exceptedWeapons = {[41] = true}
local exceptedSlots = {[0] = true, [1] = true, [8] = true, [10] = true, [11] = true, [12] = true}
local disallowedTeams = {["Citizens"] = true, ["Not logged in"] = true}
function fireCheck(button, state)
if (localPlayer.vehicle) then return end
if (fireKeys[button] and state == true) then
if (exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
toggleControl("fire", false)
return
end
if (exceptedSlots[localPlayer.weaponSlot] or exceptedWeapons[localPlayer:getWeapon()]) then
return
end
--outputDebugString("fire")
if (not getControlState("aim_weapon")) then
toggleControl("fire", false)
--outputDebugString("not aiming")
end
end
if (fireKeys[button] and state == false) then
if (not exports.UCDsafeZones:isElementWithinSafeZone(localPlayer) and not localPlayer.frozen) then
toggleControl("fire", true)
end
end
end
addEventHandler("onClientKey", root, fireCheck)
function aimCheck(button, state)
if (localPlayer.vehicle) then return end
if (aimKeys[button] and state == true) then
--if ((disallowedTeams[localPlayer.team.name] and not exports.UCDturfing:isElementInLV(localPlayer)) and localPlayer.weaponSlot ~= 11 and not exceptedWeapons[localPlayer:getWeapon()] and not exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
if ((disallowedTeams[localPlayer.team.name] and not exports.UCDturfing:isElementInLV(localPlayer)) or exports.UCDsafeZones:isElementWithinSafeZone(localPlayer)) then
outputDebugString("true")
toggleControl("aim_weapon", false)
toggleControl("fire", false)
else
outputDebugString("false")
toggleControl("aim_weapon", true)
toggleControl("fire", true)
end
end
end
addEventHandler("onClientKey", root, aimCheck)
|
UCDanticheat
|
UCDanticheat
- Fixed fireCheck allowing nades to be thrown in safe zones.
- Added an aim check, so if you're in a team that's not allowed to shoot (unless in LV) or you're in a safezone, you can't shoot or aim.
- Fixed some other syntax and formatting errors.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
6075f8e78acd44e139e96dca11a28864ce1aa388
|
scripts/tundra/path.lua
|
scripts/tundra/path.lua
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Tundra. If not, see <http://www.gnu.org/licenses/>.
module(..., package.seeall)
local native = require "tundra.native"
function split(fn)
local dir, file = fn:match("^(.*)[/\\]([^\\/]*)$")
if not dir then
return ".", fn
else
return dir, file
end
end
normalize = native.sanitize_path
function join(dir, fn)
return normalize(dir .. '/' .. fn)
end
function get_filename_dir(fn)
return select(2, split(fn))
end
function get_extension(fn)
return fn:match("(%.[^.]+)$") or ""
end
function drop_suffix(fn)
assert(type(fn) == "string")
return fn:match("^(.*)%.[^./\\]+$") or fn
end
function get_filename_base(fn)
assert(fn, "nil filename")
local _,_,stem = fn:find("([^/\\]+)%.[^.]*$")
if stem then return stem end
_,_,stem = fn:find("([^/\\]+)$")
return stem
end
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Tundra. If not, see <http://www.gnu.org/licenses/>.
module(..., package.seeall)
local native = require "tundra.native"
function split(fn)
local dir, file = fn:match("^(.*)[/\\]([^\\/]*)$")
if not dir then
return ".", fn
else
return dir, file
end
end
normalize = native.sanitize_path
function join(dir, fn)
return normalize(dir .. '/' .. fn)
end
function get_filename_dir(fn)
return select(1, split(fn))
end
function get_filename(fn)
return select(2, split(fn))
end
function get_extension(fn)
return fn:match("(%.[^.]+)$") or ""
end
function drop_suffix(fn)
assert(type(fn) == "string")
return fn:match("^(.*)%.[^./\\]+$") or fn
end
function get_filename_base(fn)
assert(fn, "nil filename")
local _,_,stem = fn:find("([^/\\]+)%.[^.]*$")
if stem then return stem end
_,_,stem = fn:find("([^/\\]+)$")
return stem
end
|
lua path module: fixed get_filename_dir, added get_filename
|
lua path module: fixed get_filename_dir, added get_filename
|
Lua
|
mit
|
deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra
|
6b2eb8018863296b39e3477a5d8bb011df56048c
|
service/service_mgr.lua
|
service/service_mgr.lua
|
local skynet = require "skynet"
require "skynet.manager" -- import skynet.register
local snax = require "snax"
local cmd = {}
local service = {}
local function request(name, func, ...)
local ok, handle = pcall(func, ...)
local s = service[name]
assert(type(s) == "table")
if ok then
service[name] = handle
else
service[name] = tostring(handle)
end
for _,v in ipairs(s) do
skynet.wakeup(v)
end
if ok then
return handle
else
error(tostring(handle))
end
end
local function waitfor(name , func, ...)
local s = service[name]
if type(s) == "number" then
return s
end
local co = coroutine.running()
if s == nil then
s = {}
service[name] = s
elseif type(s) == "string" then
error(s)
end
assert(type(s) == "table")
if not s.launch and func then
s.launch = true
return request(name, func, ...)
end
table.insert(s, co)
skynet.wait()
s = service[name]
if type(s) == "string" then
error(s)
end
assert(type(s) == "number")
return s
end
local function read_name(service_name)
if string.byte(service_name) == 64 then -- '@'
return string.sub(service_name , 2)
else
return service_name
end
end
function cmd.LAUNCH(service_name, subname, ...)
local realname = read_name(service_name)
if realname == "snaxd" then
return waitfor(service_name.."."..subname, snax.rawnewservice, subname, ...)
else
return waitfor(service_name, skynet.newservice, realname, subname, ...)
end
end
function cmd.QUERY(service_name, subname)
local realname = read_name(service_name)
if realname == "snaxd" then
return waitfor(service_name.."."..subname)
else
return waitfor(service_name)
end
end
local function list_service()
local result = {}
for k,v in pairs(service) do
if type(v) == "string" then
v = "Error: " .. v
elseif type(v) == "table" then
v = "Querying"
else
v = skynet.address(v)
end
result[k] = v
end
return result
end
local function register_global()
function cmd.GLAUNCH(name, ...)
local global_name = "@" .. name
return cmd.LAUNCH(global_name, ...)
end
function cmd.GQUERY(name, ...)
local global_name = "@" .. name
return cmd.QUERY(global_name, ...)
end
local mgr = {}
function cmd.REPORT(m)
mgr[m] = true
end
local function add_list(all, m)
local harbor = "@" .. skynet.harbor(m)
local result = skynet.call(m, "lua", "LIST")
for k,v in pairs(result) do
all[k .. harbor] = v
end
end
function cmd.LIST()
local result = {}
for k in pairs(mgr) do
pcall(add_list, result, k)
end
local l = list_service()
for k, v in pairs(l) do
result[k] = v
end
return result
end
end
local function register_local()
function cmd.GLAUNCH(name, ...)
local global_name = "@" .. name
return waitfor(global_name, skynet.call, "SERVICE", "lua", "LAUNCH", global_name, ...)
end
function cmd.GQUERY(name, ...)
local global_name = "@" .. name
return waitfor(global_name, skynet.call, "SERVICE", "lua", "QUERY", global_name, ...)
end
function cmd.LIST()
return list_service()
end
skynet.call("SERVICE", "lua", "REPORT", skynet.self())
end
skynet.start(function()
skynet.dispatch("lua", function(session, address, command, ...)
local f = cmd[command]
if f == nil then
skynet.ret(skynet.pack(nil, "Invalid command " .. command))
return
end
local ok, r = pcall(f, ...)
if ok then
skynet.ret(skynet.pack(r))
else
skynet.ret(skynet.pack(nil, r))
end
end)
local handle = skynet.localname ".service"
if handle then
skynet.error(".service is already register by ", skynet.address(handle))
skynet.exit()
else
skynet.register(".service")
end
if skynet.getenv "standalone" then
skynet.register("SERVICE")
register_global()
else
register_local()
end
end)
|
local skynet = require "skynet"
require "skynet.manager" -- import skynet.register
local snax = require "snax"
local cmd = {}
local service = {}
local function request(name, func, ...)
local ok, handle = pcall(func, ...)
local s = service[name]
assert(type(s) == "table")
if ok then
service[name] = handle
else
service[name] = tostring(handle)
end
for _,v in ipairs(s) do
skynet.wakeup(v)
end
if ok then
return handle
else
error(tostring(handle))
end
end
local function waitfor(name , func, ...)
local s = service[name]
if type(s) == "number" then
return s
end
local co = coroutine.running()
if s == nil then
s = {}
service[name] = s
elseif type(s) == "string" then
error(s)
end
assert(type(s) == "table")
if not s.launch and func then
s.launch = true
return request(name, func, ...)
end
table.insert(s, co)
skynet.wait()
s = service[name]
if type(s) == "string" then
error(s)
end
assert(type(s) == "number")
return s
end
local function read_name(service_name)
if string.byte(service_name) == 64 then -- '@'
return string.sub(service_name , 2)
else
return service_name
end
end
function cmd.LAUNCH(service_name, subname, ...)
local realname = read_name(service_name)
if realname == "snaxd" then
return waitfor(service_name.."."..subname, snax.rawnewservice, subname, ...)
else
return waitfor(service_name, skynet.newservice, realname, subname, ...)
end
end
function cmd.QUERY(service_name, subname)
local realname = read_name(service_name)
if realname == "snaxd" then
return waitfor(service_name.."."..subname)
else
return waitfor(service_name)
end
end
local function list_service()
local result = {}
for k,v in pairs(service) do
if type(v) == "string" then
v = "Error: " .. v
elseif type(v) == "table" then
v = "Querying"
else
v = skynet.address(v)
end
result[k] = v
end
return result
end
local function register_global()
function cmd.GLAUNCH(name, ...)
local global_name = "@" .. name
return cmd.LAUNCH(global_name, ...)
end
function cmd.GQUERY(name, ...)
local global_name = "@" .. name
return cmd.QUERY(global_name, ...)
end
local mgr = {}
function cmd.REPORT(m)
mgr[m] = true
end
local function add_list(all, m)
local harbor = "@" .. skynet.harbor(m)
local result = skynet.call(m, "lua", "LIST")
for k,v in pairs(result) do
all[k .. harbor] = v
end
end
function cmd.LIST()
local result = {}
for k in pairs(mgr) do
pcall(add_list, result, k)
end
local l = list_service()
for k, v in pairs(l) do
result[k] = v
end
return result
end
end
local function register_local()
local function waitfor_remote(cmd, name, ...)
local global_name = "@" .. name
local local_name
if name == "snaxd" then
local_name = global_name .. "." .. (...)
else
local_name = global_name
end
return waitfor(local_name, skynet.call, "SERVICE", "lua", cmd, global_name, ...)
end
function cmd.GLAUNCH(...)
return waitfor_remote("LAUNCH", ...)
end
function cmd.GQUERY(...)
return waitfor_remote("QUERY", ...)
end
function cmd.LIST()
return list_service()
end
skynet.call("SERVICE", "lua", "REPORT", skynet.self())
end
skynet.start(function()
skynet.dispatch("lua", function(session, address, command, ...)
local f = cmd[command]
if f == nil then
skynet.ret(skynet.pack(nil, "Invalid command " .. command))
return
end
local ok, r = pcall(f, ...)
if ok then
skynet.ret(skynet.pack(r))
else
skynet.ret(skynet.pack(nil, r))
end
end)
local handle = skynet.localname ".service"
if handle then
skynet.error(".service is already register by ", skynet.address(handle))
skynet.exit()
else
skynet.register(".service")
end
if skynet.getenv "standalone" then
skynet.register("SERVICE")
register_global()
else
register_local()
end
end)
|
fix #487
|
fix #487
|
Lua
|
mit
|
hongling0/skynet,sundream/skynet,icetoggle/skynet,QuiQiJingFeng/skynet,rainfiel/skynet,Ding8222/skynet,xjdrew/skynet,zhangshiqian1214/skynet,asanosoyokaze/skynet,zhangshiqian1214/skynet,lawnight/skynet,xcjmine/skynet,czlc/skynet,kyle-wang/skynet,cdd990/skynet,xcjmine/skynet,cloudwu/skynet,great90/skynet,bttscut/skynet,sanikoyes/skynet,letmefly/skynet,xinjuncoding/skynet,JiessieDawn/skynet,QuiQiJingFeng/skynet,chuenlungwang/skynet,Ding8222/skynet,hongling0/skynet,cmingjian/skynet,great90/skynet,bigrpg/skynet,Ding8222/skynet,nightcj/mmo,letmefly/skynet,icetoggle/skynet,icetoggle/skynet,firedtoad/skynet,zhangshiqian1214/skynet,ag6ag/skynet,nightcj/mmo,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,zhouxiaoxiaoxujian/skynet,xinjuncoding/skynet,cloudwu/skynet,cdd990/skynet,iskygame/skynet,firedtoad/skynet,nightcj/mmo,rainfiel/skynet,sundream/skynet,cmingjian/skynet,rainfiel/skynet,puXiaoyi/skynet,fztcjjl/skynet,letmefly/skynet,liuxuezhan/skynet,liuxuezhan/skynet,sanikoyes/skynet,kyle-wang/skynet,fztcjjl/skynet,sanikoyes/skynet,korialuo/skynet,wangyi0226/skynet,JiessieDawn/skynet,pigparadise/skynet,czlc/skynet,bigrpg/skynet,codingabc/skynet,jxlczjp77/skynet,lawnight/skynet,asanosoyokaze/skynet,ag6ag/skynet,ag6ag/skynet,pigparadise/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,liuxuezhan/skynet,czlc/skynet,cloudwu/skynet,xinjuncoding/skynet,liuxuezhan/skynet,fztcjjl/skynet,cmingjian/skynet,codingabc/skynet,wangyi0226/skynet,bigrpg/skynet,JiessieDawn/skynet,great90/skynet,chuenlungwang/skynet,chuenlungwang/skynet,cdd990/skynet,asanosoyokaze/skynet,ypengju/skynet_comment,puXiaoyi/skynet,wangyi0226/skynet,ypengju/skynet_comment,jxlczjp77/skynet,zhangshiqian1214/skynet,lawnight/skynet,puXiaoyi/skynet,firedtoad/skynet,korialuo/skynet,zhouxiaoxiaoxujian/skynet,iskygame/skynet,sundream/skynet,xjdrew/skynet,ypengju/skynet_comment,bttscut/skynet,pigparadise/skynet,korialuo/skynet,hongling0/skynet,iskygame/skynet,codingabc/skynet,lawnight/skynet,kyle-wang/skynet,xcjmine/skynet,QuiQiJingFeng/skynet,xjdrew/skynet,letmefly/skynet,bttscut/skynet
|
c47401502fd5800f6344a64276533a7a58800416
|
lua/entities/gmod_wire_expression2/core/timer.lua
|
lua/entities/gmod_wire_expression2/core/timer.lua
|
/******************************************************************************\
Timer support
\******************************************************************************/
local timerid = 0
local runner
local function Execute(self, name)
runner = name
self.data['timer'].timers[name] = nil
if(self.entity and self.entity.Execute) then
self.entity:Execute()
end
if !self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
end
runner = nil
end
local function AddTimer(self, name, delay)
if delay < 10 then delay = 10 end
if runner == name then
timer.Adjust("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 2, function()
Execute(self, name)
end)
timer.Start("e2_" .. self.data['timer'].timerid .. "_" .. name)
elseif !self.data['timer'].timers[name] then
timer.Create("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 2, function()
Execute(self, name)
end)
end
self.data['timer'].timers[name] = true
end
local function RemoveTimer(self, name)
if self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
self.data['timer'].timers[name] = nil
end
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data['timer'] = {}
self.data['timer'].timerid = timerid
self.data['timer'].timers = {}
timerid = timerid + 1
end)
registerCallback("destruct", function(self)
for name,_ in pairs(self.data['timer'].timers) do
RemoveTimer(self, name)
end
end)
/******************************************************************************/
__e2setcost(5) -- approximation
e2function void interval(rv1)
AddTimer(self, "interval", rv1)
end
e2function void timer(string rv1, rv2)
AddTimer(self, rv1, rv2)
end
e2function void stoptimer(string rv1)
RemoveTimer(self, rv1)
end
e2function number clk()
if runner == "interval"
then return 1 else return 0 end
end
e2function number clk(string rv1)
if runner == rv1
then return 1 else return 0 end
end
e2function string clkName()
return runner or ""
end
e2function array getTimers()
local ret = {}
local i = 0
for name,_ in pairs( self.data.timer.timers ) do
i = i + 1
ret[i] = name
end
self.prf = self.prf + i * 5
return ret
end
e2function void stopAllTimers()
for name,_ in pairs(self.data.timer.timers) do
self.prf = self.prf + 5
RemoveTimer(self,name)
end
end
/******************************************************************************/
e2function number curtime()
return CurTime()
end
e2function number realtime()
return RealTime()
end
e2function number systime()
return SysTime()
end
-----------------------------------------------------------------------------------
local function luaDateToE2Table( time, utc )
local ret = {n={},ntypes={},s={},stypes={},size=0}
local time = os.date((utc and "!" or "") .. "*t",time)
if not time then return ret end -- this happens if you give it a negative time
for k,v in pairs( time ) do
if k == "isdst" then
ret.s.isdst = (v and 1 or 0)
ret.stypes.isdst = "n"
else
ret.s[k] = v
ret.stypes[k] = "n"
end
ret.size = ret.size + 1
end
return ret
end
-- Returns the server's current time formatted neatly in a table
e2function table date()
return luaDateToE2Table()
end
-- Returns the specified time formatted neatly in a table
e2function table date( time )
return luaDateToE2Table(time)
end
-- Returns the server's current time formatted neatly in a table using UTC
e2function table dateUTC()
return luaDateToE2Table(nil,true)
end
-- Returns the specified time formatted neatly in a table using UTC
e2function table dateUTC( time )
return luaDateToE2Table(time,true)
end
-- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it
-- It's essentially the same as the date function above
e2function number time(string component)
local ostime = os.date("!*t")
local ret = ostime[component]
return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst
end
-----------------------------------------------------------------------------------
-- Returns the time in seconds
e2function number time()
return os.time()
end
-- Attempts to construct the time from the data in the given table (same as lua's os.time)
-- The table structure must be the same as in the above date functions
-- If any values are missing or of the wrong type, that value is ignored (it will be nil)
local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true}
e2function number time(table data)
local args = {}
for k,v in pairs( data.s ) do
if data.stypes[k] ~= "n" or not validkeys[k] then continue end
if k == "isdst" then
args.isdst = (v == 1)
else
args[k] = v
end
end
return os.time( args )
end
|
/******************************************************************************\
Timer support
\******************************************************************************/
local timerid = 0
local function Execute(self, name)
self.data.timer.runner = name
self.data['timer'].timers[name] = nil
if(self.entity and self.entity.Execute) then
self.entity:Execute()
end
if !self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
end
self.data.timer.runner = nil
end
local function AddTimer(self, name, delay)
if delay < 10 then delay = 10 end
if self.data.timer.runner == name then
timer.Adjust("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 2, function()
Execute(self, name)
end)
timer.Start("e2_" .. self.data['timer'].timerid .. "_" .. name)
elseif !self.data['timer'].timers[name] then
timer.Create("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 2, function()
Execute(self, name)
end)
end
self.data['timer'].timers[name] = true
end
local function RemoveTimer(self, name)
if self.data['timer'].timers[name] then
timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
self.data['timer'].timers[name] = nil
end
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data['timer'] = {}
self.data['timer'].timerid = timerid
self.data['timer'].timers = {}
timerid = timerid + 1
end)
registerCallback("destruct", function(self)
for name,_ in pairs(self.data['timer'].timers) do
RemoveTimer(self, name)
end
end)
/******************************************************************************/
__e2setcost(5) -- approximation
e2function void interval(rv1)
AddTimer(self, "interval", rv1)
end
e2function void timer(string rv1, rv2)
AddTimer(self, rv1, rv2)
end
e2function void stoptimer(string rv1)
RemoveTimer(self, rv1)
end
e2function number clk()
if self.data.timer.runner == "interval"
then return 1 else return 0 end
end
e2function number clk(string rv1)
if self.data.timer.runner == rv1
then return 1 else return 0 end
end
e2function string clkName()
return self.data.timer.runner or ""
end
e2function array getTimers()
local ret = {}
local i = 0
for name,_ in pairs( self.data.timer.timers ) do
i = i + 1
ret[i] = name
end
self.prf = self.prf + i * 5
return ret
end
e2function void stopAllTimers()
for name,_ in pairs(self.data.timer.timers) do
self.prf = self.prf + 5
RemoveTimer(self,name)
end
end
/******************************************************************************/
e2function number curtime()
return CurTime()
end
e2function number realtime()
return RealTime()
end
e2function number systime()
return SysTime()
end
-----------------------------------------------------------------------------------
local function luaDateToE2Table( time, utc )
local ret = {n={},ntypes={},s={},stypes={},size=0}
local time = os.date((utc and "!" or "") .. "*t",time)
if not time then return ret end -- this happens if you give it a negative time
for k,v in pairs( time ) do
if k == "isdst" then
ret.s.isdst = (v and 1 or 0)
ret.stypes.isdst = "n"
else
ret.s[k] = v
ret.stypes[k] = "n"
end
ret.size = ret.size + 1
end
return ret
end
-- Returns the server's current time formatted neatly in a table
e2function table date()
return luaDateToE2Table()
end
-- Returns the specified time formatted neatly in a table
e2function table date( time )
return luaDateToE2Table(time)
end
-- Returns the server's current time formatted neatly in a table using UTC
e2function table dateUTC()
return luaDateToE2Table(nil,true)
end
-- Returns the specified time formatted neatly in a table using UTC
e2function table dateUTC( time )
return luaDateToE2Table(time,true)
end
-- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it
-- It's essentially the same as the date function above
e2function number time(string component)
local ostime = os.date("!*t")
local ret = ostime[component]
return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst
end
-----------------------------------------------------------------------------------
-- Returns the time in seconds
e2function number time()
return os.time()
end
-- Attempts to construct the time from the data in the given table (same as lua's os.time)
-- The table structure must be the same as in the above date functions
-- If any values are missing or of the wrong type, that value is ignored (it will be nil)
local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true}
e2function number time(table data)
local args = {}
for k,v in pairs( data.s ) do
if data.stypes[k] ~= "n" or not validkeys[k] then continue end
if k == "isdst" then
args.isdst = (v == 1)
else
args[k] = v
end
end
return os.time( args )
end
|
Fixed timer execution caused by other e2 not working
|
Fixed timer execution caused by other e2 not working
If one e2 was using a timer and caused an execution of a different e2,
then the second e2 would be unable to use a timer of the same name.
Thanks to Steve on Discord for finding this issue.
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,dvdvideo1234/wire,garrysmodlua/wire,Grocel/wire,wiremod/wire,sammyt291/wire,bigdogmat/wire,thegrb93/wire
|
048f45263025004f166411437533464093b6a79e
|
otouto/plugins/twitter.lua
|
otouto/plugins/twitter.lua
|
local twitter = {}
function twitter:init(config)
if not cred_data.tw_consumer_key then
print('Missing config value: tw_consumer_key.')
print('twitter.lua will not be enabled.')
return
elseif not cred_data.tw_consumer_secret then
print('Missing config value: tw_consumer_secret.')
print('twitter.lua will not be enabled.')
return
elseif not cred_data.tw_access_token then
print('Missing config value: tw_access_token.')
print('twitter.lua will not be enabled.')
return
elseif not cred_data.tw_access_token_secret then
print('Missing config value: tw_access_token_secret.')
print('twitter.lua will not be enabled.')
return
end
twitter.triggers = {
'twitter.com/[^/]+/statuse?s?/([0-9]+)',
'twitter.com/statuse?s?/([0-9]+)'
}
twitter.doc = [[*Twitter-Link*: Postet Tweet]]
end
local consumer_key = cred_data.tw_consumer_key
local consumer_secret = cred_data.tw_consumer_secret
local access_token = cred_data.tw_access_token
local access_token_secret = cred_data.tw_access_token_secret
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function twitter:action(msg, config, matches)
if not matches[2] then
id = matches[1]
else
id = matches[2]
end
local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json"
local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url)
local response = json.decode(response_body)
local full_name = response.user.name
local user_name = response.user.screen_name
if response.user.verified then
verified = ' ✅'
else
verified = ''
end
local header = '<b>Tweet von '..full_name..'</b> (<a href="https://twitter.com/'..user_name..'">@' ..user_name..'</a>'..verified..'):'
local text = response.text
-- favorites & retweets
if response.retweet_count == 0 then
retweets = ""
else
retweets = response.retweet_count..'x retweeted'
end
if response.favorite_count == 0 then
favorites = ""
else
favorites = response.favorite_count..'x favorisiert'
end
if retweets == "" and favorites ~= "" then
footer = '<i>'..favorites..'</i>'
elseif retweets ~= "" and favorites == "" then
footer = '<i>'..retweets..'</i>'
elseif retweets ~= "" and favorites ~= "" then
footer = '<i>'..retweets..' - '..favorites..'</i>'
else
footer = ""
end
-- replace short URLs
if response.entities.urls then
for k, v in pairs(response.entities.urls) do
local short = v.url
local long = v.expanded_url
local long = long:gsub('%%', '%%%%')
text = text:gsub(short, long)
end
end
-- remove images
local images = {}
local videos = {}
if response.entities.media and response.extended_entities.media then
for k, v in pairs(response.extended_entities.media) do
local url = v.url
local pic = v.media_url_https
if v.video_info then
if not v.video_info.variants[3] then
local vid = v.video_info.variants[1].url
table.insert(videos, vid)
else
local vid = v.video_info.variants[3].url
table.insert(videos, vid)
end
end
text = text:gsub(url, "")
table.insert(images, pic)
end
end
-- quoted tweet
if response.quoted_status then
local quoted_text = response.quoted_status.text
local quoted_name = response.quoted_status.user.name
local quoted_screen_name = response.quoted_status.user.screen_name
if response.quoted_status.user.verified then
quoted_verified = ' ✅'
else
quoted_verified = ''
end
quote = '<b>Als Antwort auf '..quoted_name..'</b> (<a href="https://twitter.com/'..quoted_screen_name..'">@' ..quoted_screen_name..'</a>'..quoted_verified..'):\n'..quoted_text
text = text..'\n\n'..quote..'\n'
end
-- send the parts
local text = unescape(text)
utilities.send_reply(self, msg, header .. "\n" .. text.."\n"..footer, 'HTML')
for k, v in pairs(images) do
local file = download_to_file(v)
utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id)
end
for k, v in pairs(videos) do
local file = download_to_file(v)
utilities.send_video(self, msg.chat.id, file, nil, msg.message_id)
end
end
return twitter
|
local twitter = {}
function twitter:init(config)
if not cred_data.tw_consumer_key then
print('Missing config value: tw_consumer_key.')
print('twitter.lua will not be enabled.')
return
elseif not cred_data.tw_consumer_secret then
print('Missing config value: tw_consumer_secret.')
print('twitter.lua will not be enabled.')
return
elseif not cred_data.tw_access_token then
print('Missing config value: tw_access_token.')
print('twitter.lua will not be enabled.')
return
elseif not cred_data.tw_access_token_secret then
print('Missing config value: tw_access_token_secret.')
print('twitter.lua will not be enabled.')
return
end
twitter.triggers = {
'twitter.com/[^/]+/statuse?s?/([0-9]+)',
'twitter.com/statuse?s?/([0-9]+)'
}
twitter.doc = [[*Twitter-Link*: Postet Tweet]]
end
local consumer_key = cred_data.tw_consumer_key
local consumer_secret = cred_data.tw_consumer_secret
local access_token = cred_data.tw_access_token
local access_token_secret = cred_data.tw_access_token_secret
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function twitter:action(msg, config, matches)
if not matches[2] then
id = matches[1]
else
id = matches[2]
end
local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json"
local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url)
local response = json.decode(response_body)
local full_name = response.user.name
local user_name = response.user.screen_name
if response.user.verified then
verified = ' ✅'
else
verified = ''
end
local header = '<b>Tweet von '..full_name..'</b> (<a href="https://twitter.com/'..user_name..'">@' ..user_name..'</a>'..verified..'):'
local text = response.text
-- favorites & retweets
if response.retweet_count == 0 then
retweets = ""
else
retweets = response.retweet_count..'x retweeted'
end
if response.favorite_count == 0 then
favorites = ""
else
favorites = response.favorite_count..'x favorisiert'
end
if retweets == "" and favorites ~= "" then
footer = '<i>'..favorites..'</i>'
elseif retweets ~= "" and favorites == "" then
footer = '<i>'..retweets..'</i>'
elseif retweets ~= "" and favorites ~= "" then
footer = '<i>'..retweets..' - '..favorites..'</i>'
else
footer = ""
end
-- replace short URLs
if response.entities.urls then
for k, v in pairs(response.entities.urls) do
local short = v.url
local long = v.expanded_url
local long = long:gsub('%%', '%%%%')
text = text:gsub(short, long)
end
end
-- remove images
local images = {}
local videos = {}
if response.entities.media and response.extended_entities.media then
for k, v in pairs(response.extended_entities.media) do
local url = v.url
local pic = v.media_url_https
if v.video_info then
if not v.video_info.variants[3] then
local vid = v.video_info.variants[1].url
table.insert(videos, vid)
else
local vid = v.video_info.variants[3].url
table.insert(videos, vid)
end
end
text = text:gsub(url, "")
table.insert(images, pic)
end
end
-- quoted tweet
if response.quoted_status then
local quoted_text = response.quoted_status.text
local quoted_name = response.quoted_status.user.name
local quoted_screen_name = response.quoted_status.user.screen_name
if response.quoted_status.user.verified then
quoted_verified = ' ✅'
else
quoted_verified = ''
end
quote = '<b>Als Antwort auf '..quoted_name..'</b> (<a href="https://twitter.com/'..quoted_screen_name..'">@' ..quoted_screen_name..'</a>'..quoted_verified..'):\n'..quoted_text
text = text..'\n\n'..quote..'\n'
end
-- send the parts
utilities.send_reply(self, msg, header .. "\n" .. text.."\n"..footer, 'HTML')
if videos[1] then images = {} end
for k, v in pairs(images) do
local file = download_to_file(v)
utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id)
end
for k, v in pairs(videos) do
local file = download_to_file(v)
utilities.send_video(self, msg.chat.id, file, nil, msg.message_id)
end
end
return twitter
|
Twitter: Fix, entferne unescape() und sende keine Bilder, wenn Video eingebunden ist
|
Twitter: Fix, entferne unescape() und sende keine Bilder, wenn Video eingebunden ist
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
951f43ffe615c52dbd00b8cd61bfcffce91d225b
|
tundra.lua
|
tundra.lua
|
require "tundra.native"
local native = require('tundra.native')
local macosx = {
Env = {
CCOPTS = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything",
"-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
},
CXXOPTS = {
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
},
},
Frameworks = { "Cocoa" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
"/DPRODBG_WIN",
"/FS", "/MT", "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
},
CXXOPTS = {
"/DPRODBG_WIN",
"/FS", "/MT", "/I.", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
},
},
}
Build {
Passes = {
GenerateSources = { Name="Generate sources", BuildOrder = 1 },
},
Units = "units.lua",
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
|
require "tundra.native"
local native = require('tundra.native')
local macosx = {
Env = {
CCOPTS = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything",
"-Wno-c++98-compat-pedantic",
"-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
},
CXXOPTS = {
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-c++98-compat-pedantic",
"-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
},
},
Frameworks = { "Cocoa" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
"/DPRODBG_WIN",
"/FS", "/MT", "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
},
CXXOPTS = {
"/DPRODBG_WIN",
"/FS", "/MT", "/I.", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
},
},
}
Build {
Passes = {
GenerateSources = { Name="Generate sources", BuildOrder = 1 },
},
Units = "units.lua",
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
|
Fixed log_* warnings with -Weverything
|
Fixed log_* warnings with -Weverything
|
Lua
|
mit
|
emoon/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,kondrak/ProDBG,v3n/ProDBG,emoon/ProDBG,emoon/ProDBG,v3n/ProDBG,emoon/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,kondrak/ProDBG,v3n/ProDBG,ashemedai/ProDBG,emoon/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,v3n/ProDBG,RobertoMalatesta/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,emoon/ProDBG,kondrak/ProDBG
|
76ab48df3b23669142dc925680cdb00a33192f87
|
lualib/skynet/remotedebug.lua
|
lualib/skynet/remotedebug.lua
|
local skynet = require "skynet"
local debugchannel = require "debugchannel"
local socket = require "socket"
local injectrun = require "skynet.injectcode"
local table = table
local debug = debug
local coroutine = coroutine
local sethook = debugchannel.sethook
local M = {}
local HOOK_FUNC = "raw_dispatch_message"
local raw_dispatcher
local print = _G.print
local skynet_suspend
local prompt
local newline
local function change_prompt(s)
newline = true
prompt = s
end
local function replace_upvalue(func, uvname, value)
local i = 1
while true do
local name, uv = debug.getupvalue(func, i)
if name == nil then
break
end
if name == uvname then
if value then
debug.setupvalue(func, i, value)
end
return uv
end
i = i + 1
end
end
local function remove_hook(dispatcher)
assert(raw_dispatcher, "Not in debug mode")
replace_upvalue(dispatcher, HOOK_FUNC, raw_dispatcher)
raw_dispatcher = nil
print = _G.print
skynet.error "Leave debug mode"
end
local function gen_print(fd)
-- redirect print to socket fd
return function(...)
local tmp = table.pack(...)
for i=1,tmp.n do
tmp[i] = tostring(tmp[i])
end
table.insert(tmp, "\n")
socket.write(fd, table.concat(tmp, "\t"))
end
end
local function run_exp(ok, ...)
if ok then
print(...)
end
return ok
end
local function run_cmd(cmd, env, co, level)
if not run_exp(injectrun("return "..cmd, co, level, env)) then
print(select(2, injectrun(cmd,co, level,env)))
end
end
local ctx_skynet = debug.getinfo(skynet.start,"S").short_src -- skip when enter this source file
local ctx_term = debug.getinfo(run_cmd, "S").short_src -- term when get here
local ctx_active = {}
local linehook
local function skip_hook(mode)
local co = coroutine.running()
local ctx = ctx_active[co]
if mode == "return" then
ctx.level = ctx.level - 1
if ctx.level == 0 then
ctx.needupdate = true
sethook(linehook, "crl")
end
else
ctx.level = ctx.level + 1
end
end
function linehook(mode, line)
local co = coroutine.running()
local ctx = ctx_active[co]
if mode ~= "line" then
ctx.needupdate = true
if mode ~= "return" then
if ctx.next_mode or debug.getinfo(2,"S").short_src == ctx_skynet then
ctx.level = 1
sethook(skip_hook, "cr")
end
end
else
if ctx.needupdate then
ctx.needupdate = false
ctx.filename = debug.getinfo(2, "S").short_src
if ctx.filename == ctx_term then
ctx_active[co] = nil
sethook()
change_prompt(string.format(":%08x>", skynet.self()))
return
end
end
-- Lua 5.3 report currentline seems wrong
change_prompt(string.format("%s(%d)>",ctx.filename, line-1))
return true -- yield
end
end
local function add_watch_hook()
local co = coroutine.running()
local ctx = {}
ctx_active[co] = ctx
local level = 3
sethook(function()
level = level - 1
if level == 0 then
ctx.needupdate = true
sethook(linehook, "crl")
end
end, "r")
end
local function watch_proto(protoname, cond)
local proto = assert(replace_upvalue(skynet.register_protocol, "proto"), "Can't find proto table")
local p = proto[protoname]
local dispatch = p.dispatch_origin or p.dispatch
if p == nil or dispatch == nil then
return "No " .. protoname
end
p.dispatch_origin = dispatch
p.dispatch = function(...)
if not cond or cond(...) then
p.dispatch = dispatch -- restore origin dispatch function
add_watch_hook()
end
dispatch(...)
end
end
local function remove_watch()
for co in pairs(ctx_active) do
sethook(co)
end
ctx_active = {}
end
local dbgcmd = {}
function dbgcmd.s(co)
local ctx = ctx_active[co]
ctx.next_mode = false
skynet_suspend(co, coroutine.resume(co))
end
function dbgcmd.n(co)
local ctx = ctx_active[co]
ctx.next_mode = true
skynet_suspend(co, coroutine.resume(co))
end
function dbgcmd.c(co)
sethook(co)
ctx_active[co] = nil
change_prompt(string.format(":%08x>", skynet.self()))
skynet_suspend(co, coroutine.resume(co))
end
local function hook_dispatch(dispatcher, resp, fd, channel)
change_prompt(string.format(":%08x>", skynet.self()))
print = gen_print(fd)
local env = {
print = print,
watch = watch_proto
}
local watch_env = {
print = print
}
local function watch_cmd(cmd)
local co = next(ctx_active)
watch_env._CO = co
if dbgcmd[cmd] then
dbgcmd[cmd](co)
else
run_cmd(cmd, watch_env, co, 0)
end
end
local function debug_hook()
while true do
if newline then
socket.write(fd, prompt)
newline = false
end
local cmd = channel:read()
if cmd then
if cmd == "cont" then
-- leave debug mode
break
end
if cmd ~= "" then
if next(ctx_active) then
watch_cmd(cmd)
else
run_cmd(cmd, env, coroutine.running(),2)
end
end
newline = true
else
-- no input
return
end
end
-- exit debug mode
remove_watch()
remove_hook(dispatcher)
resp(true)
end
local func
local function hook(...)
debug_hook()
return func(...)
end
func = replace_upvalue(dispatcher, HOOK_FUNC, hook)
if func then
local function idle()
skynet.timeout(10,idle) -- idle every 0.1s
end
skynet.timeout(0, idle)
end
return func
end
function M.start(import, fd, handle)
local dispatcher = import.dispatch
skynet_suspend = import.suspend
assert(raw_dispatcher == nil, "Already in debug mode")
skynet.error "Enter debug mode"
local channel = debugchannel.connect(handle)
raw_dispatcher = hook_dispatch(dispatcher, skynet.response(), fd, channel)
end
return M
|
local skynet = require "skynet"
local debugchannel = require "debugchannel"
local socket = require "socket"
local injectrun = require "skynet.injectcode"
local table = table
local debug = debug
local coroutine = coroutine
local sethook = debugchannel.sethook
local M = {}
local HOOK_FUNC = "raw_dispatch_message"
local raw_dispatcher
local print = _G.print
local skynet_suspend
local prompt
local newline
local function change_prompt(s)
newline = true
prompt = s
end
local function replace_upvalue(func, uvname, value)
local i = 1
while true do
local name, uv = debug.getupvalue(func, i)
if name == nil then
break
end
if name == uvname then
if value then
debug.setupvalue(func, i, value)
end
return uv
end
i = i + 1
end
end
local function remove_hook(dispatcher)
assert(raw_dispatcher, "Not in debug mode")
replace_upvalue(dispatcher, HOOK_FUNC, raw_dispatcher)
raw_dispatcher = nil
print = _G.print
skynet.error "Leave debug mode"
end
local function gen_print(fd)
-- redirect print to socket fd
return function(...)
local tmp = table.pack(...)
for i=1,tmp.n do
tmp[i] = tostring(tmp[i])
end
table.insert(tmp, "\n")
socket.write(fd, table.concat(tmp, "\t"))
end
end
local function run_exp(ok, ...)
if ok then
print(...)
end
return ok
end
local function run_cmd(cmd, env, co, level)
if not run_exp(injectrun("return "..cmd, co, level, env)) then
print(select(2, injectrun(cmd,co, level,env)))
end
end
local ctx_skynet = debug.getinfo(skynet.start,"S").short_src -- skip when enter this source file
local ctx_term = debug.getinfo(run_cmd, "S").short_src -- term when get here
local ctx_active = {}
local linehook
local function skip_hook(mode)
local co = coroutine.running()
local ctx = ctx_active[co]
if mode == "return" then
ctx.level = ctx.level - 1
if ctx.level == 0 then
ctx.needupdate = true
sethook(linehook, "crl")
end
else
ctx.level = ctx.level + 1
end
end
function linehook(mode, line)
local co = coroutine.running()
local ctx = ctx_active[co]
if mode ~= "line" then
ctx.needupdate = true
if mode ~= "return" then
if ctx.next_mode or debug.getinfo(2,"S").short_src == ctx_skynet then
ctx.level = 1
sethook(skip_hook, "cr")
end
end
else
if ctx.needupdate then
ctx.needupdate = false
ctx.filename = debug.getinfo(2, "S").short_src
if ctx.filename == ctx_term then
ctx_active[co] = nil
sethook()
change_prompt(string.format(":%08x>", skynet.self()))
return
end
end
change_prompt(string.format("%s(%d)>",ctx.filename, line))
return true -- yield
end
end
local function add_watch_hook()
local co = coroutine.running()
local ctx = {}
ctx_active[co] = ctx
local level = 1
sethook(function(mode)
if mode == "return" then
level = level - 1
else
level = level + 1
if level == 0 then
ctx.needupdate = true
sethook(linehook, "crl")
end
end
end, "cr")
end
local function watch_proto(protoname, cond)
local proto = assert(replace_upvalue(skynet.register_protocol, "proto"), "Can't find proto table")
local p = proto[protoname]
local dispatch = p.dispatch_origin or p.dispatch
if p == nil or dispatch == nil then
return "No " .. protoname
end
p.dispatch_origin = dispatch
p.dispatch = function(...)
if not cond or cond(...) then
p.dispatch = dispatch -- restore origin dispatch function
add_watch_hook()
end
dispatch(...)
end
end
local function remove_watch()
for co in pairs(ctx_active) do
sethook(co)
end
ctx_active = {}
end
local dbgcmd = {}
function dbgcmd.s(co)
local ctx = ctx_active[co]
ctx.next_mode = false
skynet_suspend(co, coroutine.resume(co))
end
function dbgcmd.n(co)
local ctx = ctx_active[co]
ctx.next_mode = true
skynet_suspend(co, coroutine.resume(co))
end
function dbgcmd.c(co)
sethook(co)
ctx_active[co] = nil
change_prompt(string.format(":%08x>", skynet.self()))
skynet_suspend(co, coroutine.resume(co))
end
local function hook_dispatch(dispatcher, resp, fd, channel)
change_prompt(string.format(":%08x>", skynet.self()))
print = gen_print(fd)
local env = {
print = print,
watch = watch_proto
}
local watch_env = {
print = print
}
local function watch_cmd(cmd)
local co = next(ctx_active)
watch_env._CO = co
if dbgcmd[cmd] then
dbgcmd[cmd](co)
else
run_cmd(cmd, watch_env, co, 0)
end
end
local function debug_hook()
while true do
if newline then
socket.write(fd, prompt)
newline = false
end
local cmd = channel:read()
if cmd then
if cmd == "cont" then
-- leave debug mode
break
end
if cmd ~= "" then
if next(ctx_active) then
watch_cmd(cmd)
else
run_cmd(cmd, env, coroutine.running(),2)
end
end
newline = true
else
-- no input
return
end
end
-- exit debug mode
remove_watch()
remove_hook(dispatcher)
resp(true)
end
local func
local function hook(...)
debug_hook()
return func(...)
end
func = replace_upvalue(dispatcher, HOOK_FUNC, hook)
if func then
local function idle()
skynet.timeout(10,idle) -- idle every 0.1s
end
skynet.timeout(0, idle)
end
return func
end
function M.start(import, fd, handle)
local dispatcher = import.dispatch
skynet_suspend = import.suspend
assert(raw_dispatcher == nil, "Already in debug mode")
skynet.error "Enter debug mode"
local channel = debugchannel.connect(handle)
raw_dispatcher = hook_dispatch(dispatcher, skynet.response(), fd, channel)
end
return M
|
bugfix: watch hook begin at next call
|
bugfix: watch hook begin at next call
|
Lua
|
mit
|
xjdrew/skynet,lawnight/skynet,jiuaiwo1314/skynet,Ding8222/skynet,longmian/skynet,KAndQ/skynet,enulex/skynet,liuxuezhan/skynet,chuenlungwang/skynet,ilylia/skynet,zhaijialong/skynet,JiessieDawn/skynet,ypengju/skynet_comment,great90/skynet,bingo235/skynet,javachengwc/skynet,ypengju/skynet_comment,czlc/skynet,zzh442856860/skynet,fztcjjl/skynet,harryzeng/skynet,u20024804/skynet,zhouxiaoxiaoxujian/skynet,pichina/skynet,bttscut/skynet,icetoggle/skynet,wangjunwei01/skynet,fhaoquan/skynet,jxlczjp77/skynet,dymx101/skynet,Zirpon/skynet,xjdrew/skynet,togolwb/skynet,chfg007/skynet,microcai/skynet,nightcj/mmo,LuffyPan/skynet,lawnight/skynet,bigrpg/skynet,letmefly/skynet,longmian/skynet,zhangshiqian1214/skynet,cdd990/skynet,LiangMa/skynet,chenjiansnail/skynet,yinjun322/skynet,ruleless/skynet,lc412/skynet,firedtoad/skynet,boyuegame/skynet,pigparadise/skynet,pichina/skynet,zzh442856860/skynet-Note,u20024804/skynet,bttscut/skynet,togolwb/skynet,cmingjian/skynet,JiessieDawn/skynet,microcai/skynet,liuxuezhan/skynet,LiangMa/skynet,wangyi0226/skynet,xinjuncoding/skynet,codingabc/skynet,zhangshiqian1214/skynet,jxlczjp77/skynet,catinred2/skynet,Ding8222/skynet,bigrpg/skynet,zzh442856860/skynet,zhangshiqian1214/skynet,ludi1991/skynet,pigparadise/skynet,zhoukk/skynet,winglsh/skynet,rainfiel/skynet,czlc/skynet,zhaijialong/skynet,xcjmine/skynet,zhouxiaoxiaoxujian/skynet,lc412/skynet,codingabc/skynet,icetoggle/skynet,letmefly/skynet,harryzeng/skynet,gitfancode/skynet,cmingjian/skynet,zzh442856860/skynet-Note,vizewang/skynet,MoZhonghua/skynet,helling34/skynet,firedtoad/skynet,korialuo/skynet,puXiaoyi/skynet,LuffyPan/skynet,QuiQiJingFeng/skynet,felixdae/skynet,cpascal/skynet,puXiaoyi/skynet,u20024804/skynet,wangyi0226/skynet,cdd990/skynet,lynx-seu/skynet,kebo/skynet,MoZhonghua/skynet,cmingjian/skynet,KittyCookie/skynet,harryzeng/skynet,bttscut/skynet,ruleless/skynet,bingo235/skynet,LuffyPan/skynet,jxlczjp77/skynet,wangjunwei01/skynet,samael65535/skynet,zzh442856860/skynet-Note,ludi1991/skynet,sundream/skynet,ilylia/skynet,bingo235/skynet,wangjunwei01/skynet,xinjuncoding/skynet,chuenlungwang/skynet,MRunFoss/skynet,ag6ag/skynet,czlc/skynet,leezhongshan/skynet,cloudwu/skynet,zzh442856860/skynet-Note,cuit-zhaxin/skynet,chfg007/skynet,sanikoyes/skynet,codingabc/skynet,QuiQiJingFeng/skynet,felixdae/skynet,felixdae/skynet,sanikoyes/skynet,ludi1991/skynet,winglsh/skynet,vizewang/skynet,asanosoyokaze/skynet,plsytj/skynet,Markal128/skynet,lynx-seu/skynet,ypengju/skynet_comment,liuxuezhan/skynet,gitfancode/skynet,chfg007/skynet,iskygame/skynet,Markal128/skynet,yinjun322/skynet,puXiaoyi/skynet,asanosoyokaze/skynet,sundream/skynet,wangyi0226/skynet,zhaijialong/skynet,fhaoquan/skynet,leezhongshan/skynet,sundream/skynet,MetSystem/skynet,microcai/skynet,javachengwc/skynet,zhoukk/skynet,samael65535/skynet,ilylia/skynet,lawnight/skynet,matinJ/skynet,MoZhonghua/skynet,winglsh/skynet,xcjmine/skynet,yunGit/skynet,letmefly/skynet,kyle-wang/skynet,nightcj/mmo,sdgdsffdsfff/skynet,KAndQ/skynet,ludi1991/skynet,jiuaiwo1314/skynet,lawnight/skynet,rainfiel/skynet,lynx-seu/skynet,great90/skynet,sdgdsffdsfff/skynet,chenjiansnail/skynet,yunGit/skynet,ag6ag/skynet,MRunFoss/skynet,gitfancode/skynet,chuenlungwang/skynet,plsytj/skynet,MRunFoss/skynet,hongling0/skynet,longmian/skynet,Markal128/skynet,leezhongshan/skynet,yunGit/skynet,yinjun322/skynet,Zirpon/skynet,kyle-wang/skynet,xcjmine/skynet,fhaoquan/skynet,pichina/skynet,xjdrew/skynet,cuit-zhaxin/skynet,kyle-wang/skynet,cdd990/skynet,catinred2/skynet,helling34/skynet,sdgdsffdsfff/skynet,vizewang/skynet,Zirpon/skynet,zhouxiaoxiaoxujian/skynet,cuit-zhaxin/skynet,bigrpg/skynet,kebo/skynet,kebo/skynet,pigparadise/skynet,your-gatsby/skynet,MetSystem/skynet,your-gatsby/skynet,iskygame/skynet,javachengwc/skynet,cloudwu/skynet,ruleless/skynet,asanosoyokaze/skynet,zzh442856860/skynet,KAndQ/skynet,fztcjjl/skynet,zhangshiqian1214/skynet,letmefly/skynet,hongling0/skynet,dymx101/skynet,cpascal/skynet,great90/skynet,your-gatsby/skynet,rainfiel/skynet,helling34/skynet,hongling0/skynet,zhangshiqian1214/skynet,samael65535/skynet,zhangshiqian1214/skynet,jiuaiwo1314/skynet,matinJ/skynet,nightcj/mmo,KittyCookie/skynet,xinjuncoding/skynet,firedtoad/skynet,iskygame/skynet,sanikoyes/skynet,enulex/skynet,fztcjjl/skynet,Ding8222/skynet,togolwb/skynet,cpascal/skynet,icetoggle/skynet,matinJ/skynet,liuxuezhan/skynet,enulex/skynet,korialuo/skynet,JiessieDawn/skynet,MetSystem/skynet,plsytj/skynet,boyuegame/skynet,cloudwu/skynet,zhoukk/skynet,boyuegame/skynet,dymx101/skynet,KittyCookie/skynet,ag6ag/skynet,catinred2/skynet,QuiQiJingFeng/skynet,LiangMa/skynet,lc412/skynet,chenjiansnail/skynet,korialuo/skynet
|
d093198ddcd2f0f8e511dd03e848de0378b81bfd
|
xmake/core/base/dump.lua
|
xmake/core/base/dump.lua
|
local colors = require("base/colors")
local table = require("base/table")
local _dump = {}
function _dump._string(str, as_key)
local quote = (not as_key) or str:match("%s")
if quote then
io.write(colors.translate("${cyan}\""))
end
io.write(colors.translate("${reset}${cyan bright}", false))
io.write(str)
io.write(colors.translate("${reset}", false))
if quote then
io.write(colors.translate("${cyan}\""))
end
end
function _dump._keyword(keyword)
io.write(colors.translate("${blue}" .. tostring(keyword)))
end
function _dump._number(num)
io.write(colors.translate("${green}" .. num))
end
function _dump._function(func, as_key)
if as_key then
return _dump._default(func)
end
local funcinfo = debug.getinfo(func)
local srcinfo = funcinfo.short_src
if funcinfo.linedefined >= 0 then
srcinfo = srcinfo .. ":" .. funcinfo.linedefined
end
io.write(colors.translate("${red}function ${bright}" .. (funcinfo.name or "") .. "${reset}${dim}" .. srcinfo))
end
function _dump._default(value)
io.write(colors.translate("${dim}<", false) .. tostring(value) .. colors.translate(">${reset}", false))
end
function _dump._scalar(value, as_key)
if type(value) == "nil" then
_dump._keyword("nil")
elseif type(value) == "boolean" then
_dump._keyword(value)
elseif type(value) == "number" then
_dump._number(value)
elseif type(value) == "string" then
_dump._string(value, as_key)
elseif type(value) == "function" then
_dump._function(value, as_key)
else
_dump._default(value)
end
end
function _dump._table(value, first_indent, remain_indent)
io.write(first_indent .. colors.translate("${dim}{"))
local inner_indent = remain_indent .. " "
local is_arr = table.is_array(value)
local first_value = true
for k, v in pairs(value) do
if first_value then
io.write("\n")
first_value = false
else
io.write(",\n")
end
io.write(inner_indent)
if not is_arr then
_dump._scalar(k, true)
io.write(colors.translate("${dim} = "))
end
if type(v) == "table" then
_dump._table(v, "", inner_indent)
else
_dump._scalar(v)
end
end
if first_value then
io.write(colors.translate(" ${dim}}"))
else
io.write("\n" .. remain_indent .. colors.translate("${dim}}"))
end
end
function _dump.main(value, indent)
indent = indent or ""
if type(value) == "table" then
_dump._table(value, indent, indent:gsub(".", " "))
else
io.write(indent)
_dump._scalar(value)
end
end
return _dump.main
|
local colors = require("base/colors")
local table = require("base/table")
local _dump = {}
function _dump._string(str, as_key)
local quote = (not as_key) or (not str:match("^[a-zA-Z_][a-zA-Z0-9_]*$"))
if quote then
io.write(colors.translate("${cyan}\""))
end
io.write(colors.translate("${reset}${cyan bright}", false))
io.write(str)
io.write(colors.translate("${reset}", false))
if quote then
io.write(colors.translate("${cyan}\""))
end
end
function _dump._keyword(keyword)
io.write(colors.translate("${blue}" .. tostring(keyword)))
end
function _dump._number(num)
io.write(colors.translate("${green}" .. num))
end
function _dump._function(func, as_key)
if as_key then
return _dump._default(func)
end
local funcinfo = debug.getinfo(func)
local srcinfo = funcinfo.short_src
if funcinfo.linedefined >= 0 then
srcinfo = srcinfo .. ":" .. funcinfo.linedefined
end
io.write(colors.translate("${red}function ${bright}" .. (funcinfo.name or "") .. "${reset}${dim}" .. srcinfo))
end
function _dump._default(value)
io.write(colors.translate("${dim}<", false) .. tostring(value) .. colors.translate(">${reset}", false))
end
function _dump._scalar(value, as_key)
if type(value) == "nil" then
_dump._keyword("nil")
elseif type(value) == "boolean" then
_dump._keyword(value)
elseif type(value) == "number" then
_dump._number(value)
elseif type(value) == "string" then
_dump._string(value, as_key)
elseif type(value) == "function" then
_dump._function(value, as_key)
else
_dump._default(value)
end
end
function _dump._table(value, first_indent, remain_indent)
io.write(first_indent .. colors.translate("${dim}{"))
local inner_indent = remain_indent .. " "
local is_arr = table.is_array(value)
local first_value = true
for k, v in pairs(value) do
if first_value then
io.write("\n")
first_value = false
else
io.write(",\n")
end
io.write(inner_indent)
if not is_arr then
_dump._scalar(k, true)
io.write(colors.translate("${dim} = "))
end
if type(v) == "table" then
_dump._table(v, "", inner_indent)
else
_dump._scalar(v)
end
end
if first_value then
io.write(colors.translate(" ${dim}}"))
else
io.write("\n" .. remain_indent .. colors.translate("${dim}}"))
end
end
function _dump.main(value, indent)
indent = indent or ""
if type(value) == "table" then
_dump._table(value, indent, indent:gsub(".", " "))
else
io.write(indent)
_dump._scalar(value)
end
end
return _dump.main
|
fix string qoute rule
|
fix string qoute rule
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
daf87aa14712f4813f268b86049c0e65ef2a8aaf
|
lib/system/plan.lua
|
lib/system/plan.lua
|
-- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*-
-- vim: ts=4 sw=4 ft=lua noet
---------------------------------------------------------------------
-- @author Daniel Barney <[email protected]>
-- @copyright 2014, Pagoda Box, Inc.
-- @doc
--
-- @end
-- Created : 4 Nov 2014 by Daniel Barney <[email protected]>
---------------------------------------------------------------------
local Emitter = require('core').Emitter
local JSON = require('json')
local spawn = require('childprocess').spawn
local timer = require('timer')
local logger = require('../logger')
local Plan = Emitter:extend()
function Plan:initialize(system,id,type)
self.system = system
self.id = id
self.plan = {}
self.mature = false
local me = self
process:on('SIGINT',function() me:shutdown() end)
process:on('SIGQUIT',function() me:shutdown() end)
process:on('SIGTERM',function() me:shutdown() end)
end
function Plan:set_new(is_dead)
local add = {}
local idx = 0
local count = #is_dead
local alive_count = count
local id = self.id
for _idx,is_dead in pairs(is_dead) do
if is_dead then
if _idx < self.id then
id = id - 1
end
alive_count = alive_count - 1
end
end
logger:debug("check what is alive",alive_count,self.system.data)
for i=1,#self.system.data do
logger:debug("mod",(i % count) + 1,is_dead[(i % count) + 1],is_dead,self.id)
if (i % count) + 1 == self.id then
logger:debug("its me!",self.system.data[i])
add[#add + 1] = self.system.data[i]
elseif is_dead[(i % count) + 1] then
logger:debug("not alive",self.system.data[i],idx,alive_count,self.id,id)
-- if the other node is down, and we are responsible for it
-- add it in
if (idx % alive_count) + 1 == id then
logger:debug("failing for",self.system.data[i])
add[#add + 1] = self.system.data[i]
end
idx = idx + 1
end
end
self.next_plan = add
self.last_group = #is_dead
end
function Plan:activate(Timeout)
if self.plan_activation_timer then
logger:debug("clearing timer")
timer.clearTimer(self.plan_activation_timer)
end
if self.queue then
self.queue = self.next_plan
self.next_plan = nil
else
logger:debug("setting plan",self.next_plan)
local me = self
self.plan_activation_timer = timer.setTimeout(Timeout,function(new_plan)
me:compute(new_plan)
end,self.next_plan)
end
end
function Plan:compute(new_plan)
-- we order the array to make the comparison easier
table.sort(new_plan)
local add = {}
local remove = {}
local index = 1
local lidx = 1
logger:debug("start",idx,new_plan)
for idx=1, #new_plan do
--- value 1,3,4
--- self.plan 1,2,3
logger:debug("compare",self.plan[index],new_plan[idx])
if (new_plan[idx] and not self.plan[index]) or (self.plan[index] > new_plan[idx]) then
logger:debug("adding",new_plan[idx])
add[#add +1] = new_plan[idx]
elseif (self.plan[idx] and not new_plan[index]) or (self.plan[index] < new_plan[idx]) then
logger:debug("removing",new_plan[idx])
remove[#remove +1] = self.plan[index]
index = index + 1
idx = idx - 1
else
logger:debug("skipping",new_plan[idx])
idx = idx + 1
index = index + 1
end
lidx = idx
end
lidx = lidx + 1
-- everything else gets removed
for index=index,#self.plan do
logger:debug("batch removing",self.plan[index])
remove[#remove +1] = self.plan[index]
end
-- everything else gets added
for idx=lidx,#new_plan do
logger:debug("batch adding",new_plan[idx])
add[#add +1] = new_plan[idx]
end
-- this is not really working yet, on a restart I need to remove
-- any data points that I am responsibe for
if not self.mature then
logger:info("not mature yet",#self.system.data,self.last_group)
for i=1,#self.system.data do
if not ((i % self.last_group) + 1 == self.id) then
remove[#remove +1] = self.system.data[i]
end
end
end
-- if there were changes
if (#add > 0) or (#remove > 0) then
self.queue = {add = add,remove = remove}
self:run()
else
logger:info("no change in the plan",self.plan)
end
end
function Plan:shutdown()
self:_run('down',self.plan,function()
process.exit(1)
end)
end
function Plan:run()
local newest_plan = {}
for _idx,current in pairs(self.plan) do
local skip = false
for _idx,value in pairs(self.queue.remove) do
if value == current then
skip = true
break
end
end
if not skip then
newest_plan[#newest_plan + 1] = current
end
end
for _idx,value in pairs(self.queue.add) do
newest_plan[#newest_plan + 1] = value
end
self.plan = newest_plan
local queue = self.queue
self.queue = true
self:_run("alive",queue.add,function()
self:_run("down",queue.remove,function()
self.mature = true
-- if there is another thing queued up to run,
-- lets run it
if self.queue == true then
-- if not, lets end
self.queue = nil
logger:info("new plan",self.plan)
else
logger:info("running next set of jobs",self.queue)
self:compute(self.queue)
end
end)
end)
end
function Plan:_run(state,data,cb)
local sys = self.system
local count = #data
for idx,value in pairs(data) do
local child = spawn(sys[state],{value,JSON.stringify(sys.config)})
child.stdout:on('data', function(chunk)
logger:debug("got",chunk)
end)
child:on('exit', function(code,other)
count = count - 1
if not (code == 0 ) then
logger:error("script failed",sys[state],{value,JSON.stringify(sys.config)})
else
logger:info("script worked",sys[state],{value,JSON.stringify(sys.config)})
end
if count == 0 and cb then
cb()
end
end)
end
if count == 0 then
process.nextTick(cb)
end
end
return Plan
|
-- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*-
-- vim: ts=4 sw=4 ft=lua noet
---------------------------------------------------------------------
-- @author Daniel Barney <[email protected]>
-- @copyright 2014, Pagoda Box, Inc.
-- @doc
--
-- @end
-- Created : 4 Nov 2014 by Daniel Barney <[email protected]>
---------------------------------------------------------------------
local Emitter = require('core').Emitter
local JSON = require('json')
local spawn = require('childprocess').spawn
local timer = require('timer')
local logger = require('../logger')
local Plan = Emitter:extend()
function Plan:initialize(system,id,type)
self.system = system
self.id = id
self.plan = {}
self.mature = false
local me = self
process:on('SIGINT',function() me:shutdown() end)
process:on('SIGQUIT',function() me:shutdown() end)
process:on('SIGTERM',function() me:shutdown() end)
end
function Plan:set_new(is_dead)
local add = {}
local idx = 0
local count = #is_dead
local alive_count = count
local id = self.id
for _idx,is_dead in pairs(is_dead) do
if is_dead then
if _idx < self.id then
id = id - 1
end
alive_count = alive_count - 1
end
end
logger:debug("check what is alive",alive_count,self.system.data)
for i=1,#self.system.data do
logger:debug("mod",(i % count) + 1,is_dead[(i % count) + 1],is_dead,self.id)
if (i % count) + 1 == self.id then
logger:debug("its me!",self.system.data[i])
add[#add + 1] = self.system.data[i]
elseif is_dead[(i % count) + 1] then
logger:debug("not alive",self.system.data[i],idx,alive_count,self.id,id)
-- if the other node is down, and we are responsible for it
-- add it in
if (idx % alive_count) + 1 == id then
logger:debug("failing for",self.system.data[i])
add[#add + 1] = self.system.data[i]
end
idx = idx + 1
end
end
self.next_plan = add
self.last_group = #is_dead
end
function Plan:activate(Timeout)
if self.plan_activation_timer then
logger:debug("clearing timer")
timer.clearTimer(self.plan_activation_timer)
end
if self.queue then
self.queue = self.next_plan
self.next_plan = nil
else
logger:debug("setting plan",self.next_plan)
local me = self
self.plan_activation_timer = timer.setTimeout(Timeout,function(new_plan)
me:compute(new_plan)
end,self.next_plan)
end
end
function Plan:compute(new_plan)
-- we order the array to make the comparison easier
table.sort(new_plan)
local add = {}
local remove = {}
local index = 1
local lidx = 1
logger:debug("start",idx,new_plan)
for idx=1, #new_plan do
--- value 1,3,4
--- self.plan 1,2,3
logger:debug("compare",self.plan[index],new_plan[idx])
if (new_plan[idx] and not self.plan[index]) or (self.plan[index] > new_plan[idx]) then
logger:debug("adding",new_plan[idx])
add[#add +1] = new_plan[idx]
elseif (self.plan[idx] and not new_plan[index]) or (self.plan[index] < new_plan[idx]) then
logger:debug("removing",new_plan[idx])
remove[#remove +1] = self.plan[index]
index = index + 1
idx = idx - 1
else
logger:debug("skipping",new_plan[idx])
idx = idx + 1
index = index + 1
end
lidx = idx
end
lidx = lidx + 1
-- everything else gets removed
for index=index,#self.plan do
logger:debug("batch removing",self.plan[index])
remove[#remove +1] = self.plan[index]
end
-- everything else gets added
for idx=lidx,#new_plan do
logger:debug("batch adding",new_plan[idx])
add[#add +1] = new_plan[idx]
end
-- this is not really working yet, on a restart I need to remove
-- any data points that I am responsibe for
if not self.mature then
logger:info("not mature yet",#self.system.data,self.last_group)
for i=1,#self.system.data do
if not ((i % self.last_group) + 1 == self.id) then
remove[#remove +1] = self.system.data[i]
end
end
end
-- if there were changes
if (#add > 0) or (#remove > 0) then
self.queue = {add = add,remove = remove}
self:run()
else
logger:info("no change in the plan",self.plan)
end
end
function Plan:shutdown()
self:_run('down',self.plan,function()
process.exit(1)
end)
end
function Plan:run()
local newest_plan = {}
for _idx,current in pairs(self.plan) do
local skip = false
for _idx,value in pairs(self.queue.remove) do
if value == current then
skip = true
break
end
end
if not skip then
newest_plan[#newest_plan + 1] = current
end
end
for _idx,value in pairs(self.queue.add) do
newest_plan[#newest_plan + 1] = value
end
self.plan = newest_plan
local queue = self.queue
self.queue = true
self:_run("alive",queue.add,function()
self:_run("down",queue.remove,function()
self.mature = true
-- if there is another thing queued up to run,
-- lets run it
if self.queue == true then
-- if not, lets end
self.queue = nil
logger:info("new plan",self.plan)
else
logger:info("running next set of jobs",self.queue)
local queue = self.queue
self.queue = nil
self:compute(queue)
end
end)
end)
end
function Plan:_run(state,data,cb)
local sys = self.system
local count = #data
for idx,value in pairs(data) do
local child = spawn(sys[state],{value,JSON.stringify(sys.config)})
child.stdout:on('data', function(chunk)
logger:debug("got",chunk)
end)
child:on('exit', function(code,other)
count = count - 1
if not (code == 0 ) then
logger:error("script failed",sys[state],{value,JSON.stringify(sys.config)})
else
logger:info("script worked",sys[state],{value,JSON.stringify(sys.config)})
end
if count == 0 and cb then
cb()
end
end)
end
if count == 0 then
process.nextTick(cb)
end
end
return Plan
|
fixed queued plans causing flip to stop updating
|
fixed queued plans causing flip to stop updating
|
Lua
|
mit
|
fliping/flip,nanopack/flip
|
3f37ae3af9fe8822dd70b9737cf300924943df6f
|
lua/entities/gmod_wire_dhdd.lua
|
lua/entities/gmod_wire_dhdd.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Dupeable Hard Drive"
ENT.Author = "Divran"
ENT.WireDebugName = "Dupeable HDD"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Outputs = WireLib.CreateOutputs( self, { "Memory [ARRAY]", "Size" } )
self.Inputs = WireLib.CreateInputs( self, { "Data [ARRAY]", "Clear", "AllowWrite" } )
self.Memory = {}
self.ROM = false
self.AllowWrite = true
self:SetOverlayText("DHDD")
end
-- Read cell
function ENT:ReadCell( Address )
-- 256 KiB limit
if Address < 0 or Address >= 262144 then return 0 end
local data = self.Memory[Address or 0] or 0
return isnumber(data) and data or 0
end
-- Write cell
function ENT:WriteCell( Address, value )
-- 256 KiB limit
if Address < 0 or Address >= 262144 then return false end
if self.AllowWrite then
self.Memory[Address] = value ~= 0 and value or nil
end
self:ShowOutputs()
return true
end
function ENT:ShowOutputs()
WireLib.TriggerOutput( self, "Memory", self.Memory )
local n = #self.Memory
WireLib.TriggerOutput( self, "Size", n )
if not self.ROM then
self:SetOverlayText("DHDD\nSize: " .. n .." bytes" )
else
self:SetOverlayText("ROM\nSize: " .. n .." bytes" )
end
end
function ENT:TriggerInput( name, value )
if (name == "Data") then
if not value then return end -- if the value is invalid, abort
if not IsValid(self.Inputs.Data.Src) then return end -- if the input is not wired to anything, abort
if not self.AllowWrite then return end -- if we don't allow writing, abort
self.Memory = value
self:ShowOutputs()
elseif (name == "Clear") then
self.Memory = {}
self:ShowOutputs()
elseif (name == "AllowWrite") then
self.AllowWrite = value >= 1
end
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo( self ) or {}
info.DHDD = {}
info.ROM = self.ROM
local n = 0
info.DHDD.Memory = {}
for k,v in pairs( self.Memory ) do -- Only save the first 512^2 values
n = n + 1
if (n > 512*512) then break end
info.DHDD.Memory[k] = v
end
info.DHDD.AllowWrite = self.AllowWrite
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
if (info.DHDD) then
ent.Memory = (info.DHDD.Memory or {})
if info.DHDD.AllowWrite ~= nil then
ent.AllowWrite = info.DHDD.AllowWrite
end
self:ShowOutputs()
end
self.ROM = info.ROM or false
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
end
duplicator.RegisterEntityClass( "gmod_wire_dhdd", WireLib.MakeWireEnt, "Data" )
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Dupeable Hard Drive"
ENT.Author = "Divran"
ENT.WireDebugName = "Dupeable HDD"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Outputs = WireLib.CreateOutputs( self, { "Memory [ARRAY]", "Size" } )
self.Inputs = WireLib.CreateInputs( self, { "Data [ARRAY]", "Clear", "AllowWrite" } )
self.Memory = {}
self.Size = 0
self.ROM = false
self.AllowWrite = true
self:SetOverlayText("DHDD")
end
-- Read cell
function ENT:ReadCell( Address )
-- 256 KiB limit
if Address < 0 or Address >= 262144 then return 0 end
local data = self.Memory[Address or 0] or 0
return isnumber(data) and data or 0
end
-- Write cell
function ENT:WriteCell( Address, value )
-- 256 KiB limit
if Address < 0 or Address >= 262144 then return false end
if self.AllowWrite then
self.Memory[Address] = value ~= 0 and value or nil
self.Size = math.max(self.Size, Address + 1)
end
self:ShowOutputs()
return true
end
function ENT:ShowOutputs()
WireLib.TriggerOutput( self, "Memory", self.Memory )
WireLib.TriggerOutput( self, "Size", self.Size )
if not self.ROM then
self:SetOverlayText("DHDD\nSize: " .. self.Size .." bytes" )
else
self:SetOverlayText("ROM\nSize: " .. self.Size .." bytes" )
end
end
function ENT:TriggerInput( name, value )
if (name == "Data") then
if not value then return end -- if the value is invalid, abort
if not IsValid(self.Inputs.Data.Src) then return end -- if the input is not wired to anything, abort
if not self.AllowWrite then return end -- if we don't allow writing, abort
self.Memory = value
-- HiSpeed interfaces are 0-based, but Lua arrays are typically 1-based.
-- This gives the right 0-based size if the input is a 0-based or 1-based array:
-- {} ⇒ 0
-- { 0 = 0 } ⇒ 1
-- { 1 = 1 }, { 0 = 0, 1 = 1 } ⇒ 2
local size = #value
if size ~= 0 or value[0] ~= nil then
size = size + 1
end
self.Size = size
self:ShowOutputs()
elseif (name == "Clear") then
self.Memory = {}
self.Size = 0
self:ShowOutputs()
elseif (name == "AllowWrite") then
self.AllowWrite = value >= 1
end
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo( self ) or {}
info.DHDD = {}
info.ROM = self.ROM
local n = 0
info.DHDD.Memory = {}
for k,v in pairs( self.Memory ) do -- Only save the first 512^2 values
n = n + 1
if (n > 512*512) then break end
info.DHDD.Memory[k] = v
end
info.DHDD.AllowWrite = self.AllowWrite
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
if (info.DHDD) then
ent.Memory = (info.DHDD.Memory or {})
if info.DHDD.AllowWrite ~= nil then
ent.AllowWrite = info.DHDD.AllowWrite
end
self:ShowOutputs()
end
self.ROM = info.ROM or false
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
end
duplicator.RegisterEntityClass( "gmod_wire_dhdd", WireLib.MakeWireEnt, "Data" )
|
Make DHDD's Size output deterministic
|
Make DHDD's Size output deterministic
Currently, the DHDD size is computed with `#self.Memory`, and the
memory starts being entirely `nil` (and writing 0 to a memory cell
internally writes `nil` as a memory optimization). Given that the `#`
operator is nondeterministic when a table isn't a sequence, this makes
it essentially useless. Additionally, the DHDD memory is 0-indexed, but
Lua sequences are 1-indexed, which meant that writing to cell 0 wouldn't
change the size.
This changes the size output to a 'high water mark', by tracking the
largest address written to. The size now matches what's expected with
0-based indexing: if you write to cell 9, for example, then the size is
10.
Fixes #1581.
|
Lua
|
apache-2.0
|
sammyt291/wire,dvdvideo1234/wire,NezzKryptic/Wire,Grocel/wire,garrysmodlua/wire,wiremod/wire
|
83e8397552b541d5e9c60450093e3dbe3366ed4e
|
src/cosy.lua
|
src/cosy.lua
|
local Tag = require "cosy.tag"
local Data = require "cosy.data"
local Protocol = require "cosy.protocol"
local ignore = require "cosy.util.ignore"
local NAME = Tag.NAME
local Cosy = {}
local meta = Data.new {
[NAME] = "meta"
}
local store = Data.new {
[NAME] = "cosy"
}
-- Set global:
local global = _ENV or _G
global.cosy = setmetatable ({}, Cosy)
-- Load interface:
local Platform
if global.js then
Platform = require "cosy.platform.js"
Platform:log "Using JavaScript"
else
-- Platform = require "cosy.interface.c"
end
function Cosy:__index (url)
ignore (self)
if type (url) ~= "string" then
return nil
end
-- FIXME: validate url
-- If url does not use SSL, force it:
if url:find "http://" == 1 then
url = url:gsub ("^http://", "https://")
end
-- Remove trailing slash:
if url [#url] == "/" then
url = url:sub (1, #url-1)
end
--
local resource = rawget (store, url)
if resource then
return resource
end
local model = store [url]
--
for k, server in pairs (meta.servers) do
if url:sub (1, #k) == k then
meta.models [model] = server {}
break
end
end
local meta = meta.models [model]
meta.model = model
meta.resource = url
meta.editor.url = url .. "/editor"
meta.protocol = Protocol.new (meta)
meta.platform = Platform.new (meta)
meta.patch = {
action = "add-patch",
token = meta.editor.token,
}
meta.patches = {}
meta.patches.ids = {}
meta.disconnect = function ()
Data.clear (model)
Data.clear (meta)
end
store [url] = model
return model
end
function Cosy:__newindex ()
ignore (self)
assert (false)
end
Data.on_write.from_user = function (target, value, reverse)
if target / 1 ~= store then
return
end
local model = target / 2
local meta = meta.models [model]
local protocol = meta.protocol ()
-- TODO: generate patch
meta.patches [#(meta.patches) + 1] = meta.patch * {
code = [[ ]] % { },
id = # (meta.patches.ids) + 1,
status = "applied",
target = target,
value = value,
reverse = reverse,
}
meta.patches.ids [#(meta.patches.ids) + 1] = true
protocol:on_change ()
end
return {
Cosy = Cosy,
cosy = global.cosy,
meta = meta,
}
|
local Tag = require "cosy.tag"
local Data = require "cosy.data"
local Protocol = require "cosy.protocol"
local ignore = require "cosy.util.ignore"
local NAME = Tag.NAME
local Cosy = {}
local meta = Data.new {
[NAME] = "meta"
}
local store = Data.new {
[NAME] = "cosy"
}
-- Set global:
local global = _ENV or _G
global.cosy = setmetatable ({}, Cosy)
global.meta = meta
-- Load interface:
local Platform
if global.js then
Platform = require "cosy.platform.js"
Platform:log "Using JavaScript"
else
Platform = require "cosy.platform.dummy"
Platform:log "Using dummy"
end
function Cosy:__index (url)
ignore (self)
if type (url) ~= "string" then
return nil
end
-- FIXME: validate url
-- If url does not use SSL, force it:
if url:find "http://" == 1 then
url = url:gsub ("^http://", "https://")
end
-- Remove trailing slash:
if url [#url] == "/" then
url = url:sub (1, #url-1)
end
--
local model = rawget (cosy, url)
if model ~= nil then
return model
end
model = store [url]
--
for k, server in pairs (meta.servers) do
if url:sub (1, #k) == k then
meta.models [model] = server {}
break
end
end
local meta = meta.models [model]
meta.model = model
meta.resource = url
meta.editor.url = url .. "/editor"
meta.protocol = Protocol.new (meta)
meta.platform = Platform.new (meta)
meta.patch = {
action = "add-patch",
token = meta.editor.token,
}
meta.patches = {}
meta.patches.ids = {}
meta.disconnect = function ()
Data.clear (model)
Data.clear (meta)
end
rawset (cosy, url, model)
return model
end
function Cosy:__newindex ()
ignore (self)
assert (false)
end
Data.on_write.from_user = function (target, value, reverse)
if target / 1 ~= store then
return
end
local model = target / 2
local meta = meta.models [model]
local protocol = meta.protocol ()
-- TODO: generate patch
meta.patches [#(meta.patches) + 1] = meta.patch * {
code = [[ ]] % { },
id = # (meta.patches.ids) + 1,
status = "applied",
target = target,
value = value,
reverse = reverse,
}
meta.patches.ids [#(meta.patches.ids) + 1] = true
protocol:on_change ()
end
return {
Cosy = Cosy,
cosy = global.cosy,
meta = meta,
}
|
Fix bug that caused stack overflow.
|
Fix bug that caused stack overflow.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
c8706c38e21faf6d53fd6ad9cc7a11af019bf5ec
|
test-tls.lua
|
test-tls.lua
|
local openssl = require('openssl')
local uv = require('uv')
local bit = require('bit')
local pathjoin = require('luvi').path.join
-- Sync readfile using uv apis
local function readfile(path)
local fd, stat, chunk, err
fd = assert(uv.fs_open(path, "r", 420)) -- 420 = 0644)
stat, err = uv.fs_fstat(fd)
if stat then
chunk, err = uv.fs_read(fd, stat.size, 0)
end
uv.fs_close(fd)
if chunk then return chunk end
error(err)
end
-- Resolve an address and connect
local function tcpConnect(host, port, callback)
local onAddress, onConnect, address
function onAddress(err, res)
assert(not err, err)
assert(#res > 0)
address = res[1]
local client = uv.new_tcp()
uv.tcp_nodelay(client, true)
uv.tcp_connect(client, address.addr, address.port, onConnect)
end
function onConnect(client, err)
callback(err, client, address)
end
uv.getaddrinfo(host, port, {
socktype= "STREAM",
family = "INET"
}, onAddress)
end
local function noop() end
local function prep(callback)
if callback then return callback, noop end
local thread, main = coroutine.running()
if not thread or main then error("Callback required in main thread") end
local waiting, data
local function next(err, ...)
assert(not err, err)
if waiting then
coroutine.resume(thread, ...)
else
data = {...}
end
end
local function wait()
if data then return unpack(data) end
waiting = true
return coroutine.suspend()
end
return next, wait
end
local function makeChannel(watermark)
local length = 0
local queue = {}
local channel = {}
local onDrain, onRead
local err
watermark = watermark or 2
local function check()
if err then
if onRead then
local fn = onRead
onRead = nil
fn(err)
end
if onDrain then
local fn = onDrain
onDrain = nil
fn(err)
end
else
if onRead and length > 0 then
local fn = onRead
onRead = nil
local data = queue[length]
queue[length] = nil
length = length - 1
fn(nil, data)
end
if onDrain and length < watermark then
local fn = onDrain
onDrain = nil
fn()
end
end
end
function channel.put(item)
if err then error(err) end
queue[length + 1] = item
length = length + 1
check()
return length < watermark
end
function channel.drain(callback)
local next, wait = prep(callback)
if onDrain then error("Only one drain at a time please") end
if type(callback) ~= "function" then
error("callback must be a function")
end
onDrain = next
check()
return wait()
end
function channel.take(callback)
local next, wait = prep(callback)
if onRead then error("Only one read at a time please") end
if type(callback) ~= "function" then
error("callback must be a function")
end
onRead = next
check()
return wait()
end
function channel.fail(e)
err = e
check()
end
return channel
end
-- <- input <- <- input <-
-- TCP tcpChannel <-> BIOs tlsChannel
-- -> output -> -> output ->
-- Wrap any uv_stream_t subclass (uv_tcp_t, uv_pipe_t, or uv_tty_t) and
-- expose it as a culvert channel with callback and coroutine support.
-- call channel.put/channel.drain to write to the tcp socket
-- call channel.take to read from the tcp socket
local function streamToChannel(stream)
local input = makeChannel(2)
local output = makeChannel(2)
local paused = true
local onRead, onDrain, onInput, onWrite
function onRead(_, err, chunk)
if err then return output.fail(err) end
if output.put(chunk) or paused then return end
paused = true
uv.read_stop(stream)
output.drain(onDrain)
end
function onDrain(err)
if err then return output.fail(err) end
if not paused then return end
paused = false
uv.read_start(stream, onRead)
end
function onInput(err, chunk)
if err then return output.fail(err) end
-- TODO: find better way to do backpressure than writing
-- one at a time.
uv.write(stream, chunk, onWrite)
end
function onWrite(_, err)
if err then return output.fail(err) end
input.take(onInput)
end
input.take(onInput)
uv.read_start(stream, onRead)
paused = false
return {
put = input.put,
drain = input.drain,
take = output.take,
fail = input.fail,
}
end
-- Given a duplex channel, do TLS handchake with it and return a new
-- channel for R/W of the clear text.
local function secureChannel(channel)
local input = makeChannel(2)
local output = makeChannel(2)
local initialized = false
local ctx = openssl.ssl.ctx_new("TLSv1_2")
-- TODO: use root ca cert to verify server
local xcert = openssl.x509.read(readfile(pathjoin(module.dir, "ca.cer")))
p(xcert:parse())
ctx:set_verify({"none"})
-- TODO: Make options configurable in secureChannel call
ctx:options(bit.bor(
openssl.ssl.no_sslv2,
openssl.ssl.no_sslv3,
openssl.ssl.no_compression))
local bin, bout = openssl.bio.mem(8192), openssl.bio.mem(8192)
local ssl = ctx:ssl(bin, bout, false)
local process, onPlainText, onCipherText
function onPlainText(err, data)
p{plainText=data}
if err then return output.fail(err) end
ssl:write(data)
input.take(onPlainText)
process()
end
function onCipherText(err, data)
p{cipherText=data}
if err then return output.fail(err) end
bin:write(data)
channel.take(onCipherText)
process()
end
function process()
if not initialized then
local success, message = ssl:handshake()
p {
success = success,
message = message,
}
if success then
initialized = true
input.take(onPlainText)
end
else
if bin:pending() > 0 then
local data = ssl:read()
if data then
p{writePlain=data}
output.put(data)
end
end
end
if bout:pending() > 0 then
local data = bout:read()
p{writeCipher=data}
channel.put(data)
end
end
-- Kick off the process
process()
channel.take(onCipherText)
return {
put = input.put,
drain = input.drain,
take = output.take,
fail = input.fail,
}
end
print("Connecting to https://luvit.io/")
tcpConnect("luvit.io", "https", function (err, stream, address)
assert(not err, err)
print("TCP Connected.")
p {stream=stream,address=address}
print("Establishing secure socket")
local channel = secureChannel(streamToChannel(stream))
p {channel=channel}
channel.put("GET / HTTP/1.1\r\n" ..
"User-Agent: luvit\r\n" ..
"Host: luvit.io\r\n" ..
"Accept: *.*\r\n\r\n")
channel.take(function (err, data)
assert(not err, err)
p{onRead=data}
end)
end)
-- Run the event loop with stack traces in case of errors
xpcall(uv.run, debug.traceback)
|
local openssl = require('openssl')
local uv = require('uv')
local bit = require('bit')
local pathjoin = require('luvi').path.join
-- Sync readfile using uv apis
local function readfile(path)
local fd, stat, chunk, err
fd = assert(uv.fs_open(path, "r", 420)) -- 420 = 0644)
stat, err = uv.fs_fstat(fd)
if stat then
chunk, err = uv.fs_read(fd, stat.size, 0)
end
uv.fs_close(fd)
if chunk then return chunk end
error(err)
end
local function noop() end
local function prep(callback)
if callback then return callback, noop end
local thread, main = coroutine.running()
if not thread or main then error("Callback required in main thread") end
local waiting, data
local function next(err, ...)
assert(not err, err)
if waiting then
coroutine.resume(thread, ...)
else
data = {...}
end
end
local function wait()
if data then return unpack(data) end
waiting = true
return coroutine.yield()
end
return next, wait
end
-- Resolve an address and connect
local function tcpConnect(host, port, callback)
local next, wait = prep(callback)
local onAddress, onConnect, address
function onAddress(err, res)
if err then return next(err) end
if #res == 0 then return next("Can't resolve domain " .. host) end
address = res[1]
local client = uv.new_tcp()
uv.tcp_nodelay(client, true)
uv.tcp_connect(client, address.addr, address.port, onConnect)
end
function onConnect(client, err)
next(err, client, address)
end
uv.getaddrinfo(host, port, {
socktype= "STREAM",
family = "INET"
}, onAddress)
return wait()
end
local function makeChannel(watermark)
local length = 0
local queue = {}
local channel = {}
local onDrain, onRead
local err
watermark = watermark or 2
local function check()
if err then
if onRead then
local fn = onRead
onRead = nil
fn(err)
end
if onDrain then
local fn = onDrain
onDrain = nil
fn(err)
end
else
if onRead and length > 0 then
local fn = onRead
onRead = nil
local data = queue[length]
queue[length] = nil
length = length - 1
fn(nil, data)
end
if onDrain and length < watermark then
local fn = onDrain
onDrain = nil
fn()
end
end
end
function channel.put(item)
if err then error(err) end
queue[length + 1] = item
length = length + 1
check()
return length < watermark
end
function channel.drain(callback)
local next, wait = prep(callback)
if onDrain then error("Only one drain at a time please") end
if type(callback) ~= "function" then
error("callback must be a function")
end
onDrain = next
check()
return wait()
end
function channel.take(callback)
local next, wait = prep(callback)
if onRead then error("Only one read at a time please") end
if type(next) ~= "function" then
error("callback must be a function")
end
onRead = next
check()
return wait()
end
function channel.fail(e)
err = e
check()
end
return channel
end
-- <- input <- <- input <-
-- TCP tcpChannel <-> BIOs tlsChannel
-- -> output -> -> output ->
-- Wrap any uv_stream_t subclass (uv_tcp_t, uv_pipe_t, or uv_tty_t) and
-- expose it as a culvert channel with callback and coroutine support.
-- call channel.put/channel.drain to write to the tcp socket
-- call channel.take to read from the tcp socket
local function streamToChannel(stream)
local input = makeChannel(2)
local output = makeChannel(2)
local paused = true
local onRead, onDrain, onInput, onWrite
function onRead(_, err, chunk)
if err then return output.fail(err) end
if output.put(chunk) or paused then return end
paused = true
uv.read_stop(stream)
output.drain(onDrain)
end
function onDrain(err)
if err then return output.fail(err) end
if not paused then return end
paused = false
uv.read_start(stream, onRead)
end
function onInput(err, chunk)
if err then return output.fail(err) end
-- TODO: find better way to do backpressure than writing
-- one at a time.
uv.write(stream, chunk, onWrite)
end
function onWrite(_, err)
if err then return output.fail(err) end
input.take(onInput)
end
input.take(onInput)
uv.read_start(stream, onRead)
paused = false
return {
put = input.put,
drain = input.drain,
take = output.take,
fail = input.fail,
}
end
-- Given a duplex channel, do TLS handchake with it and return a new
-- channel for R/W of the clear text.
local function secureChannel(channel)
local input = makeChannel(2)
local output = makeChannel(2)
local initialized = false
local ctx = openssl.ssl.ctx_new("TLSv1_2")
ctx:set_verify({"none"})
-- TODO: Make options configurable in secureChannel call
ctx:options(bit.bor(
openssl.ssl.no_sslv2,
openssl.ssl.no_sslv3,
openssl.ssl.no_compression))
local bin, bout = openssl.bio.mem(8192), openssl.bio.mem(8192)
local ssl = ctx:ssl(bin, bout, false)
local process, onPlainText, onCipherText
function onPlainText(err, data)
if err then return output.fail(err) end
ssl:write(data)
input.take(onPlainText)
process()
end
function onCipherText(err, data)
if err then return output.fail(err) end
bin:write(data)
channel.take(onCipherText)
process()
end
function process()
if not initialized then
local success, message = ssl:handshake()
if success then
initialized = true
input.take(onPlainText)
end
else
if bin:pending() > 0 then
local data = ssl:read()
if data then
output.put(data)
end
end
end
if bout:pending() > 0 then
local data = bout:read()
channel.put(data)
end
end
-- Kick off the process
process()
channel.take(onCipherText)
return {
put = input.put,
drain = input.drain,
take = output.take,
fail = input.fail,
}
end
-- TODO: use root ca cert to verify server
local xcert = openssl.x509.read(readfile(pathjoin(module.dir, "ca.cer")))
p(xcert:parse())
coroutine.wrap(function ()
print("Connecting to https://luvit.io/")
local stream, address = tcpConnect("luvit.io", "https")
print("TCP Connected.")
p {stream=stream,address=address}
print("Establishing secure socket")
local channel = secureChannel(streamToChannel(stream))
p {channel=channel}
channel.put("GET / HTTP/1.1\r\n" ..
"User-Agent: luvit\r\n" ..
"Host: luvit.io\r\n" ..
"Accept: *.*\r\n\r\n")
print("Reading data")
local data
repeat
data = channel.take()
p(data)
until not data
end)()
-- Run the event loop with stack traces in case of errors
xpcall(uv.run, debug.traceback)
|
Fix mostly for coroutine style
|
Fix mostly for coroutine style
|
Lua
|
apache-2.0
|
kaustavha/luvit,DBarney/luvit,bsn069/luvit,rjeli/luvit,DBarney/luvit,luvit/luvit,DBarney/luvit,luvit/luvit,kaustavha/luvit,kaustavha/luvit,rjeli/luvit,rjeli/luvit,bsn069/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,zhaozg/luvit,zhaozg/luvit,bsn069/luvit
|
147d3bb548eeba306d3d26983b5b2b5e6b5206f1
|
kong/plugins/prometheus/enterprise/exporter.lua
|
kong/plugins/prometheus/enterprise/exporter.lua
|
local kong = kong
local sub = string.sub
local split = require('kong.tools.utils').split
local metrics = {}
local function init(prometheus)
metrics.license_errors = prometheus:counter("enterprise_license_errors",
"Errors when collecting license info")
metrics.license_signature = prometheus:gauge("enterprise_license_signature",
"Last 32 bytes of the license signature in number")
metrics.license_expiration = prometheus:gauge("enterprise_license_expiration",
"Unix epoch time when the license expires, " ..
"the timestamp is substracted by 24 hours "..
"to avoid difference in timezone")
metrics.license_features = prometheus:gauge("enterprise_license_features",
"License features features",
{ "feature" })
end
local function license_date_to_unix(yyyy_mm_dd)
local date_t = split(yyyy_mm_dd, "-")
local ok, res = pcall(os.time, {
year = tonumber(date_t[1]),
month = tonumber(date_t[2]),
day = tonumber(date_t[3])
})
if ok then
return res
end
return nil, res
end
local function metric_data()
if not metrics then
kong.log.err("prometheus: plugin is not initialized, please make sure ",
" 'prometheus_metrics' shared dict is present in nginx template")
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
if not kong.license or not kong.license.license then
metrics.license_errors:inc()
kong.log.err("cannot read kong.license when collecting license info")
return
end
local lic = kong.license.license
if tonumber(lic.version) ~= 1 then
metrics.license_errors:inc()
kong.log.err("enterprise license version (" .. (lic.version or "nil") .. ") unsupported")
return
end
local sig = lic.signature
if not sig then
metrics.license_errors:inc()
kong.log.err("cannot read license signature when collecting license info")
return
end
-- last 32 bytes as an int32
metrics.license_signature:set(tonumber("0x" .. sub(sig, #sig-33, #sig)))
local expiration = lic.payload and lic.payload.license_expiration_date
if not expiration then
metrics.license_errors:inc()
kong.log.err("cannot read license expiration when collecting license info")
return
end
local tm, err = license_date_to_unix(expiration)
if not tm then
metrics.license_errors:inc()
kong.log.err("cannot parse license expiration when collecting license info ", err)
return
end
-- substract it by 24h so everyone one earth is happy monitoring it
metrics.license_expiration:set(tm - 86400)
metrics.license_features:set(kong.licensing:can("ee_plugins") and 1 or 0,
{ "ee_plugins" })
metrics.license_features:set(kong.licensing:can("write_admin_api") and 1 or 0,
{ "write_admin_api" })
end
return {
init = init,
metric_data = metric_data,
}
|
local kong = kong
local sub = string.sub
local split = require('kong.tools.utils').split
local metrics = {}
local function init(prometheus)
metrics.license_errors = prometheus:counter("enterprise_license_errors",
"Errors when collecting license info")
metrics.license_signature = prometheus:gauge("enterprise_license_signature",
"Last 32 bytes of the license signature in number")
metrics.license_expiration = prometheus:gauge("enterprise_license_expiration",
"Unix epoch time when the license expires, " ..
"the timestamp is substracted by 24 hours "..
"to avoid difference in timezone")
metrics.license_features = prometheus:gauge("enterprise_license_features",
"License features features",
{ "feature" })
prometheus.dict:set("enterprise_license_errors", 0)
end
local function license_date_to_unix(yyyy_mm_dd)
local date_t = split(yyyy_mm_dd, "-")
local ok, res = pcall(os.time, {
year = tonumber(date_t[1]),
month = tonumber(date_t[2]),
day = tonumber(date_t[3])
})
if ok then
return res
end
return nil, res
end
local function metric_data()
if not metrics then
kong.log.err("prometheus: plugin is not initialized, please make sure ",
" 'prometheus_metrics' shared dict is present in nginx template")
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
if not kong.license or not kong.license.license then
metrics.license_errors:inc()
kong.log.err("cannot read kong.license when collecting license info")
return
end
local lic = kong.license.license
if tonumber(lic.version) ~= 1 then
metrics.license_errors:inc()
kong.log.err("enterprise license version (" .. (lic.version or "nil") .. ") unsupported")
return
end
local sig = lic.signature
if not sig then
metrics.license_errors:inc()
kong.log.err("cannot read license signature when collecting license info")
return
end
-- last 32 bytes as an int32
metrics.license_signature:set(tonumber("0x" .. sub(sig, #sig-33, #sig)))
local expiration = lic.payload and lic.payload.license_expiration_date
if not expiration then
metrics.license_errors:inc()
kong.log.err("cannot read license expiration when collecting license info")
return
end
local tm, err = license_date_to_unix(expiration)
if not tm then
metrics.license_errors:inc()
kong.log.err("cannot parse license expiration when collecting license info ", err)
return
end
-- substract it by 24h so everyone one earth is happy monitoring it
metrics.license_expiration:set(tm - 86400)
metrics.license_features:set(kong.licensing:can("ee_plugins") and 1 or 0,
{ "ee_plugins" })
metrics.license_features:set(kong.licensing:can("write_admin_api") and 1 or 0,
{ "write_admin_api" })
end
return {
init = init,
metric_data = metric_data,
}
|
fix(prometheus) properly initialize counter (#144)
|
fix(prometheus) properly initialize counter (#144)
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
d74a316d58fc2d4894cc4d3725b9deb11a1b628a
|
modules/announce.lua
|
modules/announce.lua
|
local mod = EPGP:NewModule("announce")
local AC = LibStub("AceComm-3.0")
local Debug = LibStub("LibDebug-1.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local SendChatMessage = _G.SendChatMessage
if ChatThrottleLib then
SendChatMessage = function(...)
ChatThrottleLib:SendChatMessage("NORMAL", "EPGP", ...)
end
end
function mod:AnnounceTo(medium, fmt, ...)
if not medium then return end
local channel = GetChannelName(self.db.profile.channel or 0)
-- Override raid and party if we are not grouped
if (medium == "RAID" or medium == "GUILD") and not UnitInRaid("player") then
medium = "GUILD"
end
local msg = string.format(fmt, ...)
local str = "EPGP:"
for _,s in pairs({strsplit(" ", msg)}) do
if #str + #s >= 250 then
SendChatMessage(str, medium, nil, channel)
str = "EPGP:"
end
str = str .. " " .. s
end
SendChatMessage(str, medium, nil, channel)
end
function mod:Announce(fmt, ...)
local medium = self.db.profile.medium
return mod:AnnounceTo(medium, fmt, ...)
end
function mod:EPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, name)
end
function mod:GPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d GP (%s) to %s"], amount, reason, name)
end
function mod:BankedItem(event_name, name, reason, amount, mass)
mod:Announce(L["%s to %s"], reason, name)
end
local function MakeCommaSeparated(t)
local first = true
local awarded = ""
for name in pairs(t) do
if first then
awarded = name
first = false
else
awarded = awarded..", "..name
end
end
return awarded
end
function mod:MassEPAward(event_name, names, reason, amount,
extras_names, extras_reason, extras_amount)
local normal = MakeCommaSeparated(names)
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, normal)
if extras_names then
local extras = MakeCommaSeparated(extras_names)
mod:Announce(L["%+d EP (%s) to %s"], extras_amount, extras_reason, extras)
end
end
function mod:Decay(event_name, decay_p)
mod:Announce(L["Decay of EP/GP by %d%%"], decay_p)
end
function mod:StartRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:ResumeRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Resume recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:StopRecurringAward(event_name)
mod:Announce(L["Stop recurring award"])
end
function mod:EPGPReset(event_name)
mod:Announce(L["EP/GP are reset"])
end
function mod:GPReset(event_name)
mod:Announce(L["GP (not EP) is reset"])
end
function mod:GPRescale(event_name)
mod:Announce(L["GP is rescaled for the new tier"])
end
function mod:LootEpics(event_name, loot)
for _, itemLink in ipairs(loot) do
local _, _, itemRarity = GetItemInfo(itemLink)
local cost = GP:GetValue(loot)
if itemRarity >= ITEM_QUALITY_EPIC and cost ~= nil then
mod:Announce(itemLink)
AC:SendCommMessage("EPGPCORPSELOOT", tostring(itemLink), "RAID", nil, "ALERT")
end
end
end
function mod:CoinLootGood(event_name, sender, rewardLink, numCoins)
local _, _, diffculty = GetInstanceInfo()
if not UnitInRaid("player") or diffculty == 7 then return end
mod:Announce(format(L["Bonus roll for %s (%s left): got %s"], sender, numCoins, rewardLink))
EPGP:LogBonusLootRoll(sender, numCoins, rewardLink)
end
function mod:CoinLootBad(event_name, sender, numCoins)
local _, _, diffculty = GetInstanceInfo()
if not UnitInRaid("player") or diffculty == 7 then return end
mod:Announce(format(L["Bonus roll for %s (%s left): got gold"], sender, numCoins))
EPGP:LogBonusLootRoll(sender, numCoins, nil)
end
mod.dbDefaults = {
profile = {
enabled = true,
medium = "GUILD",
events = {
['*'] = true,
},
}
}
function mod:OnInitialize()
self.db = EPGP.db:RegisterNamespace("announce", mod.dbDefaults)
end
mod.optionsName = L["Announce"]
mod.optionsDesc = L["Announcement of EPGP actions"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Announces EPGP actions to the specified medium."],
},
medium = {
order = 10,
type = "select",
name = L["Announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = CHAT_MSG_GUILD,
["OFFICER"] = CHAT_MSG_OFFICER,
["RAID"] = CHAT_MSG_RAID,
["PARTY"] = CHAT_MSG_PARTY,
["CHANNEL"] = CUSTOM,
},
},
channel = {
order = 11,
type = "input",
name = L["Custom announce channel name"],
desc = L["Sets the custom announce channel name used to announce EPGP actions."],
disabled = function(i) return mod.db.profile.medium ~= "CHANNEL" end,
},
events = {
order = 12,
type = "multiselect",
name = L["Announce when:"],
values = {
EPAward = L["A member is awarded EP"],
MassEPAward = L["Guild or Raid are awarded EP"],
GPAward = L["A member is credited GP"],
BankedItem = L["An item was disenchanted or deposited into the guild bank"],
Decay = L["EPGP decay"],
StartRecurringAward = L["Recurring awards start"],
StopRecurringAward = L["Recurring awards stop"],
ResumeRecurringAward = L["Recurring awards resume"],
EPGPReset = L["EPGP reset"],
GPReset = L["GP (not ep) reset"],
GPRescale = L["GP rescale for new tier"],
LootEpics = L["Announce epic loot from corpses"],
CoinLootGood = L["Announce when someone in your raid wins something good with bonus roll"],
CoinLootBad = L["Announce when someone in your raid derps a bonus roll"],
},
width = "full",
get = "GetEvent",
set = "SetEvent",
},
}
function mod:GetEvent(i, e)
return self.db.profile.events[e]
end
function mod:SetEvent(i, e, v)
if v then
Debug("Enabling announce of: %s", e)
EPGP.RegisterCallback(self, e)
else
Debug("Disabling announce of: %s", e)
EPGP.UnregisterCallback(self, e)
end
self.db.profile.events[e] = v
end
function mod:OnEnable()
for e, _ in pairs(mod.optionsArgs.events.values) do
if self.db.profile.events[e] then
Debug("Enabling announce of: %s (startup)", e)
EPGP.RegisterCallback(self, e)
end
end
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
local mod = EPGP:NewModule("announce")
local AC = LibStub("AceComm-3.0")
local Debug = LibStub("LibDebug-1.0")
local GP = LibStub("LibGearPoints-1.2")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local SendChatMessage = _G.SendChatMessage
if ChatThrottleLib then
SendChatMessage = function(...)
ChatThrottleLib:SendChatMessage("NORMAL", "EPGP", ...)
end
end
function mod:AnnounceTo(medium, fmt, ...)
if not medium then return end
local channel = GetChannelName(self.db.profile.channel or 0)
-- Override raid and party if we are not grouped
if (medium == "RAID" or medium == "GUILD") and not UnitInRaid("player") then
medium = "GUILD"
end
local msg = string.format(fmt, ...)
local str = "EPGP:"
for _,s in pairs({strsplit(" ", msg)}) do
if #str + #s >= 250 then
SendChatMessage(str, medium, nil, channel)
str = "EPGP:"
end
str = str .. " " .. s
end
SendChatMessage(str, medium, nil, channel)
end
function mod:Announce(fmt, ...)
local medium = self.db.profile.medium
return mod:AnnounceTo(medium, fmt, ...)
end
function mod:EPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, name)
end
function mod:GPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d GP (%s) to %s"], amount, reason, name)
end
function mod:BankedItem(event_name, name, reason, amount, mass)
mod:Announce(L["%s to %s"], reason, name)
end
local function MakeCommaSeparated(t)
local first = true
local awarded = ""
for name in pairs(t) do
if first then
awarded = name
first = false
else
awarded = awarded..", "..name
end
end
return awarded
end
function mod:MassEPAward(event_name, names, reason, amount,
extras_names, extras_reason, extras_amount)
local normal = MakeCommaSeparated(names)
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, normal)
if extras_names then
local extras = MakeCommaSeparated(extras_names)
mod:Announce(L["%+d EP (%s) to %s"], extras_amount, extras_reason, extras)
end
end
function mod:Decay(event_name, decay_p)
mod:Announce(L["Decay of EP/GP by %d%%"], decay_p)
end
function mod:StartRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:ResumeRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Resume recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:StopRecurringAward(event_name)
mod:Announce(L["Stop recurring award"])
end
function mod:EPGPReset(event_name)
mod:Announce(L["EP/GP are reset"])
end
function mod:GPReset(event_name)
mod:Announce(L["GP (not EP) is reset"])
end
function mod:GPRescale(event_name)
mod:Announce(L["GP is rescaled for the new tier"])
end
function mod:LootEpics(event_name, loot)
for _, itemLink in ipairs(loot) do
local _, _, itemRarity = GetItemInfo(itemLink)
local cost = GP:GetValue(loot)
if itemRarity >= ITEM_QUALITY_EPIC and cost ~= nil then
mod:Announce(itemLink)
AC:SendCommMessage("EPGPCORPSELOOT", tostring(itemLink), "RAID", nil, "ALERT")
end
end
end
function mod:CoinLootGood(event_name, sender, rewardLink, numCoins)
local _, _, diffculty = GetInstanceInfo()
if not UnitInRaid("player") or diffculty == 7 then return end
mod:Announce(format(L["Bonus roll for %s (%s left): got %s"], sender, numCoins, rewardLink))
EPGP:LogBonusLootRoll(sender, numCoins, rewardLink)
end
function mod:CoinLootBad(event_name, sender, numCoins)
local _, _, diffculty = GetInstanceInfo()
if not UnitInRaid("player") or diffculty == 7 then return end
mod:Announce(format(L["Bonus roll for %s (%s left): got gold"], sender, numCoins))
EPGP:LogBonusLootRoll(sender, numCoins, nil)
end
mod.dbDefaults = {
profile = {
enabled = true,
medium = "GUILD",
events = {
['*'] = true,
},
}
}
function mod:OnInitialize()
self.db = EPGP.db:RegisterNamespace("announce", mod.dbDefaults)
end
mod.optionsName = L["Announce"]
mod.optionsDesc = L["Announcement of EPGP actions"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Announces EPGP actions to the specified medium."],
},
medium = {
order = 10,
type = "select",
name = L["Announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = CHAT_MSG_GUILD,
["OFFICER"] = CHAT_MSG_OFFICER,
["RAID"] = CHAT_MSG_RAID,
["PARTY"] = CHAT_MSG_PARTY,
["CHANNEL"] = CUSTOM,
},
},
channel = {
order = 11,
type = "input",
name = L["Custom announce channel name"],
desc = L["Sets the custom announce channel name used to announce EPGP actions."],
disabled = function(i) return mod.db.profile.medium ~= "CHANNEL" end,
},
events = {
order = 12,
type = "multiselect",
name = L["Announce when:"],
values = {
EPAward = L["A member is awarded EP"],
MassEPAward = L["Guild or Raid are awarded EP"],
GPAward = L["A member is credited GP"],
BankedItem = L["An item was disenchanted or deposited into the guild bank"],
Decay = L["EPGP decay"],
StartRecurringAward = L["Recurring awards start"],
StopRecurringAward = L["Recurring awards stop"],
ResumeRecurringAward = L["Recurring awards resume"],
EPGPReset = L["EPGP reset"],
GPReset = L["GP (not ep) reset"],
GPRescale = L["GP rescale for new tier"],
LootEpics = L["Announce epic loot from corpses"],
CoinLootGood = L["Announce when someone in your raid wins something good with bonus roll"],
CoinLootBad = L["Announce when someone in your raid derps a bonus roll"],
},
width = "full",
get = "GetEvent",
set = "SetEvent",
},
}
function mod:GetEvent(i, e)
return self.db.profile.events[e]
end
function mod:SetEvent(i, e, v)
if v then
Debug("Enabling announce of: %s", e)
EPGP.RegisterCallback(self, e)
else
Debug("Disabling announce of: %s", e)
EPGP.UnregisterCallback(self, e)
end
self.db.profile.events[e] = v
end
function mod:OnEnable()
for e, _ in pairs(mod.optionsArgs.events.values) do
if self.db.profile.events[e] then
Debug("Enabling announce of: %s (startup)", e)
EPGP.RegisterCallback(self, e)
end
end
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
bugfix
|
bugfix
|
Lua
|
bsd-3-clause
|
sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,protomech/epgp-dkp-reloaded,sheldon/epgp,hayword/tfatf_epgp,hayword/tfatf_epgp,ceason/epgp-tfatf
|
11b5f6c6c9a7a45a6e4e4cf081ff40e9d278511d
|
modules/exchange.lua
|
modules/exchange.lua
|
local cc = {
["AED"] = "United Arab Emirates Dirham (AED)",
["ANG"] = "Netherlands Antillean Gulden (ANG)",
["ARS"] = "Argentine Peso (ARS)",
["AUD"] = "Australian Dollar (AUD)",
["BGN"] = "Bulgarian Lev (BGN)",
["BHD"] = "Bahraini Dinar (BHD)",
["BND"] = "Brunei Dollar (BND)",
["BOB"] = "Bolivian Boliviano (BOB)",
["BRL"] = "Brazilian Real (BRL)",
["BWP"] = "Botswana Pula (BWP)",
["CAD"] = "Canadian Dollar (CAD)",
["CHF"] = "Swiss Franc (CHF)",
["CLP"] = "Chilean Peso (CLP)",
["CNY"] = "Chinese Yuan (renminbi) (CNY)",
["COP"] = "Colombian Peso (COP)",
["CSD"] = "Serbian Dinar (CSD)",
["CZK"] = "Czech Koruna (CZK)",
["DKK"] = "Danish Krone (DKK)",
["EEK"] = "Estonian Kroon (EEK)",
["EGP"] = "Egyptian Pound (EGP)",
["EUR"] = "Euro (EUR)",
["FJD"] = "Fijian Dollar (FJD)",
["GBP"] = "British Pound (GBP)",
["HKD"] = "Hong Kong Dollar (HKD)",
["HNL"] = "Honduran Lempira (HNL)",
["HRK"] = "Croatian Kuna (HRK)",
["HUF"] = "Hungarian Forint (HUF)",
["IDR"] = "Indonesian Rupiah (IDR)",
["ILS"] = "New Israeli Sheqel (ILS)",
["INR"] = "Indian Rupee (INR)",
["ISK"] = "Icelandic Króna (ISK)",
["JPY"] = "Japanese Yen (JPY)",
["KRW"] = "South Korean Won (KRW)",
["KWD"] = "Kuwaiti Dinar (KWD)",
["KZT"] = "Kazakhstani Tenge (KZT)",
["LKR"] = "Sri Lankan Rupee (LKR)",
["LTL"] = "Lithuanian Litas (LTL)",
["MAD"] = "Moroccan Dirham (MAD)",
["MUR"] = "Mauritian Rupee (MUR)",
["MXN"] = "Mexican Peso (MXN)",
["MYR"] = "Malaysian Ringgit (MYR)",
["NOK"] = "Norwegian Krone (NOK)",
["NPR"] = "Nepalese Rupee (NPR)",
["NZD"] = "New Zealand Dollar (NZD)",
["OMR"] = "Omani Rial (OMR)",
["PEN"] = "Peruvian Nuevo Sol (PEN)",
["PHP"] = "Philippine Peso (PHP)",
["PKR"] = "Pakistani Rupee (PKR)",
["PLN"] = "Polish Złoty (PLN)",
["QAR"] = "Qatari Riyal (QAR)",
["RON"] = "New Romanian Leu (RON)",
["RUB"] = "Russian Ruble (RUB)",
["SAR"] = "Saudi Riyal (SAR)",
["SEK"] = "Swedish Krona (SEK)",
["SGD"] = "Singapore Dollar (SGD)",
["SIT"] = "Slovenian Tolar (SIT)",
["SKK"] = "Slovak Koruna (SKK)",
["THB"] = "Thai Baht (THB)",
["TRY"] = "New Turkish Lira (TRY)",
["TTD"] = "Trinidad and Tobago Dollar (TTD)",
["TWD"] = "New Taiwan Dollar (TWD)",
["UAH"] = "Ukrainian Hryvnia (UAH)",
["USD"] = "United States Dollar (USD)",
["VEB"] = "Venezuelan Bolívar (VEB)",
["ZAR"] = "South African Rand (ZAR)",
}
local add = function(...)
local t = 0
for i=1, select('#', ...) do
t = t + select(i, ...)
end
return t
end
-- make environment
local _X = setmetatable({
math = math,
print = function(val) if(val and tonumber(val)) then return tonumber(val) end end
}, {__index = math})
-- run code under environment
local function run(untrusted_code)
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then return nil, message end
setfenv(untrusted_function, _X)
return pcall(untrusted_function)
end
local exchange = function(self, src, dest, val, from, to)
from = from:gsub(' [tT]?[oO]?[iI]?[nN]?', '')
local output
if(cc[from:upper()] and cc[to:upper()] and from:upper() ~= to:upper()) then
local success, val, err = run('return [['..val..']]')
if(not err) then
if(type(val) == 'string') then
val = add(string.byte(val, 1, #val))
end
if(tonumber(val) and val > 0 and val ~= math.huge and val ~= (0/0)) then
local url = ('http://finance.google.com/finance/converter?a=%s&from=%s&to=%s'):format(val, from, to)
local content, status = utils.http(url)
if(status == 200) then
local data = content:match'<div id=currency_converter_result>(.-)</span>'
data = utils.decodeHTML(data:gsub('<.->', '')):gsub(' ', ' ')
if(data) then
output = data
end
else
output = 'Unable to contact server. Returned status code: '..tostring(status)
end
else
output = 'assertion failed - invalid number data.'
end
else
output = 'assertion failed - '..err
end
else
output = 'Invalid currency.'
end
if dest == self.config.nick then
-- Send the response in a PM
local srcnick = self:srctonick(src)
self:privmsg(srcnick, "%s: %s", srcnick, output)
else
-- Send it to the channel
self:privmsg(dest, "%s: %s", self:srctonick(src), output)
end
end
return {
["^:(%S+) PRIVMSG (%S+) :!xe (.-) (.-) (%a%a%a)"] = exchange,
["^:(%S+) PRIVMSG (%S+) :!cur (.-) (.-) (%a%a%a)"] = exchange,
}
|
local cc = {
["AED"] = "United Arab Emirates Dirham (AED)",
["ANG"] = "Netherlands Antillean Gulden (ANG)",
["ARS"] = "Argentine Peso (ARS)",
["AUD"] = "Australian Dollar (AUD)",
["BGN"] = "Bulgarian Lev (BGN)",
["BHD"] = "Bahraini Dinar (BHD)",
["BND"] = "Brunei Dollar (BND)",
["BOB"] = "Bolivian Boliviano (BOB)",
["BRL"] = "Brazilian Real (BRL)",
["BWP"] = "Botswana Pula (BWP)",
["CAD"] = "Canadian Dollar (CAD)",
["CHF"] = "Swiss Franc (CHF)",
["CLP"] = "Chilean Peso (CLP)",
["CNY"] = "Chinese Yuan (renminbi) (CNY)",
["COP"] = "Colombian Peso (COP)",
["CSD"] = "Serbian Dinar (CSD)",
["CZK"] = "Czech Koruna (CZK)",
["DKK"] = "Danish Krone (DKK)",
["EEK"] = "Estonian Kroon (EEK)",
["EGP"] = "Egyptian Pound (EGP)",
["EUR"] = "Euro (EUR)",
["FJD"] = "Fijian Dollar (FJD)",
["GBP"] = "British Pound (GBP)",
["HKD"] = "Hong Kong Dollar (HKD)",
["HNL"] = "Honduran Lempira (HNL)",
["HRK"] = "Croatian Kuna (HRK)",
["HUF"] = "Hungarian Forint (HUF)",
["IDR"] = "Indonesian Rupiah (IDR)",
["ILS"] = "New Israeli Sheqel (ILS)",
["INR"] = "Indian Rupee (INR)",
["ISK"] = "Icelandic Króna (ISK)",
["JPY"] = "Japanese Yen (JPY)",
["KRW"] = "South Korean Won (KRW)",
["KWD"] = "Kuwaiti Dinar (KWD)",
["KZT"] = "Kazakhstani Tenge (KZT)",
["LKR"] = "Sri Lankan Rupee (LKR)",
["LTL"] = "Lithuanian Litas (LTL)",
["MAD"] = "Moroccan Dirham (MAD)",
["MUR"] = "Mauritian Rupee (MUR)",
["MXN"] = "Mexican Peso (MXN)",
["MYR"] = "Malaysian Ringgit (MYR)",
["NOK"] = "Norwegian Krone (NOK)",
["NPR"] = "Nepalese Rupee (NPR)",
["NZD"] = "New Zealand Dollar (NZD)",
["OMR"] = "Omani Rial (OMR)",
["PEN"] = "Peruvian Nuevo Sol (PEN)",
["PHP"] = "Philippine Peso (PHP)",
["PKR"] = "Pakistani Rupee (PKR)",
["PLN"] = "Polish Złoty (PLN)",
["QAR"] = "Qatari Riyal (QAR)",
["RON"] = "New Romanian Leu (RON)",
["RUB"] = "Russian Ruble (RUB)",
["SAR"] = "Saudi Riyal (SAR)",
["SEK"] = "Swedish Krona (SEK)",
["SGD"] = "Singapore Dollar (SGD)",
["SIT"] = "Slovenian Tolar (SIT)",
["SKK"] = "Slovak Koruna (SKK)",
["THB"] = "Thai Baht (THB)",
["TRY"] = "New Turkish Lira (TRY)",
["TTD"] = "Trinidad and Tobago Dollar (TTD)",
["TWD"] = "New Taiwan Dollar (TWD)",
["UAH"] = "Ukrainian Hryvnia (UAH)",
["USD"] = "United States Dollar (USD)",
["VEB"] = "Venezuelan Bolívar (VEB)",
["ZAR"] = "South African Rand (ZAR)",
}
local add = function(...)
local t = 0
for i=1, select('#', ...) do
t = t + select(i, ...)
end
return t
end
-- make environment
local _X = setmetatable({
math = math,
print = function(val) if(val and tonumber(val)) then return tonumber(val) end end
}, {__index = math})
-- run code under environment
local function run(untrusted_code)
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then return nil, message end
setfenv(untrusted_function, _X)
return pcall(untrusted_function)
end
local exchange = function(self, src, dest, val, from, to)
from = from:gsub(' [tT]?[oO]?[iI]?[nN]?', '')
local output
if(cc[from:upper()] and cc[to:upper()] and from:upper() ~= to:upper()) then
local success, val, err = run('return [['..val..']]')
if(not err) then
if(type(val) == 'string' and not tonumber(val)) then
val = add(string.byte(val, 1, #val))
else
val = tonumber(val)
end
if(tonumber(val) and val > 0 and val ~= math.huge and val ~= (0/0)) then
local url = ('http://finance.google.com/finance/converter?a=%s&from=%s&to=%s'):format(val, from, to)
local content, status = utils.http(url)
if(status == 200) then
local data = content:match'<div id=currency_converter_result>(.-)</span>'
data = utils.decodeHTML(data:gsub('<.->', '')):gsub(' ', ' ')
if(data) then
output = data
end
else
output = 'Unable to contact server. Returned status code: '..tostring(status)
end
else
output = 'assertion failed - invalid number data.'
end
else
output = 'assertion failed - '..err
end
else
output = 'Invalid currency.'
end
if dest == self.config.nick then
-- Send the response in a PM
local srcnick = self:srctonick(src)
self:privmsg(srcnick, "%s: %s", srcnick, output)
else
-- Send it to the channel
self:privmsg(dest, "%s: %s", self:srctonick(src), output)
end
end
return {
["^:(%S+) PRIVMSG (%S+) :!xe (.-) (.-) (%a%a%a)"] = exchange,
["^:(%S+) PRIVMSG (%S+) :!cur (.-) (.-) (%a%a%a)"] = exchange,
}
|
Fix string input.
|
Fix string input.
|
Lua
|
mit
|
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
|
9345d2498a5455114e84360ba684b1bca768893b
|
hammerspoon/init.lua
|
hammerspoon/init.lua
|
-- Reload config on write.
function reloadConfig(files)
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
doReload = true
end
end
if doReload then
hs.reload()
end
end
hs.pathwatcher.new(os.getenv("HOME") .. "/.homesick/repos/hammerspoon-castle/home/.hammerspoon/", reloadConfig):start()
hs.alert.show("Config loaded")
-- Music Hotkeys
hs.hotkey.bind({"ctrl"}, "f7", function ()
if hs.appfinder.appFromName("iTunes") then
hs.itunes.previous()
if hs.itunes.getCurrentTrack() then
hs.itunes.displayCurrentTrack()
end
elseif hs.appfinder.appFromName("Spotify") then
hs.spotify.previous()
if hs.spotify.getCurrentTrack() then
hs.spotify.displayCurrentTrack()
end
end
end)
paused = false
hs.hotkey.bind({"ctrl"}, "f8", function ()
if hs.appfinder.appFromName("iTunes") then
if not paused then
paused = true
hs.itunes.pause()
else
paused = false
hs.itunes.play()
hs.itunes.displayCurrentTrack()
end
elseif hs.appfinder.appFromName("Spotify") then
if not paused then
paused = true
hs.spotify.pause()
else
paused = false
hs.spotify.play()
hs.spotify.displayCurrentTrack()
end
end
end)
hs.hotkey.bind({"ctrl"}, "f9", function ()
if hs.appfinder.appFromName("iTunes") then
hs.itunes.next()
if hs.itunes.getCurrentTrack() then
hs.itunes.displayCurrentTrack()
end
elseif hs.appfinder.appFromName("Spotify") then
hs.spotify.next()
if hs.spotify.getCurrentTrack() then
hs.spotify.displayCurrentTrack()
end
end
end)
hs.hotkey.bind({"ctrl"}, "f10", function ()
if hs.audiodevice.current().muted then
hs.audiodevice.defaultOutputDevice():setMuted(false)
else
hs.audiodevice.defaultOutputDevice():setMuted(true)
end
end)
hs.hotkey.bind({"ctrl"}, "f11", function ()
if hs.audiodevice.current().volume > 0 then
newVolume = math.floor(hs.audiodevice.current().volume - 5)
if newVolume < 0 then
newVolume = 0
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
hs.hotkey.bind({"ctrl"}, "f12", function ()
if hs.audiodevice.current().volume < 100 then
newVolume = math.ceil(hs.audiodevice.current().volume + 5)
if newVolume > 100 then
newVolume = 100
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
-- Window Hotkeys
function fullsizeWindow()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h
win:setFrame(f)
end
hs.hotkey.bind({"ctrl", "alt"}, "m", fullsizeWindow)
hs.hotkey.bind({"ctrl", "alt"}, "Up", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Down", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y + (max.h / 2)
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Left", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Right", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "j", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():next())
end)
hs.hotkey.bind({"ctrl", "alt"}, "k", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():previous())
end)
|
-- Reload config on write.
function reloadConfig(files)
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
doReload = true
end
end
if doReload then
hs.reload()
end
end
hs.pathwatcher.new(os.getenv("HOME") .. "/.dotfiles/hammerspoon/", reloadConfig):start()
hs.alert.show("Config loaded")
-- Music Hotkeys
hs.hotkey.bind({"ctrl"}, "f7", function ()
if hs.appfinder.appFromName("iTunes") then
hs.itunes.previous()
if hs.itunes.getCurrentTrack() then
hs.itunes.displayCurrentTrack()
end
elseif hs.appfinder.appFromName("Spotify") then
hs.spotify.previous()
if hs.spotify.getCurrentTrack() then
hs.spotify.displayCurrentTrack()
end
end
end)
paused = false
hs.hotkey.bind({"ctrl"}, "f8", function ()
if hs.appfinder.appFromName("iTunes") then
if not paused then
paused = true
hs.itunes.pause()
else
paused = false
hs.itunes.play()
hs.itunes.displayCurrentTrack()
end
elseif hs.appfinder.appFromName("Spotify") then
if not paused then
paused = true
hs.spotify.pause()
else
paused = false
hs.spotify.play()
hs.spotify.displayCurrentTrack()
end
end
end)
hs.hotkey.bind({"ctrl"}, "f9", function ()
if hs.appfinder.appFromName("iTunes") then
hs.itunes.next()
if hs.itunes.getCurrentTrack() then
hs.itunes.displayCurrentTrack()
end
elseif hs.appfinder.appFromName("Spotify") then
hs.spotify.next()
if hs.spotify.getCurrentTrack() then
hs.spotify.displayCurrentTrack()
end
end
end)
hs.hotkey.bind({"ctrl"}, "f10", function ()
if hs.audiodevice.current().muted then
hs.audiodevice.defaultOutputDevice():setMuted(false)
else
hs.audiodevice.defaultOutputDevice():setMuted(true)
end
end)
hs.hotkey.bind({"ctrl"}, "f11", function ()
if hs.audiodevice.current().volume > 0 then
newVolume = math.floor(hs.audiodevice.current().volume - 5)
if newVolume < 0 then
newVolume = 0
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
hs.hotkey.bind({"ctrl"}, "f12", function ()
if hs.audiodevice.current().volume < 100 then
newVolume = math.ceil(hs.audiodevice.current().volume + 5)
if newVolume > 100 then
newVolume = 100
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
-- Window Hotkeys
function fullsizeWindow()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h
win:setFrame(f)
end
hs.hotkey.bind({"ctrl", "alt"}, "m", fullsizeWindow)
hs.hotkey.bind({"ctrl", "alt"}, "Up", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Down", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y + (max.h / 2)
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Left", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Right", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "j", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():next())
end)
hs.hotkey.bind({"ctrl", "alt"}, "k", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():previous())
end)
|
Fix path in hammerspoon config.
|
Fix path in hammerspoon config.
|
Lua
|
mit
|
squaresurf/dotfiles,squaresurf/dotfiles,squaresurf/dotfiles
|
746a9c666171804b8bf1b3881d1bbe6db5543c13
|
roles/neovim/config/lua/irubataru/lsp/servers/sumneko_lua.lua
|
roles/neovim/config/lua/irubataru/lsp/servers/sumneko_lua.lua
|
local path = vim.split(package.path, ";")
table.insert(path, "lua/?.lua")
table.insert(path, "lua/?/init.lua")
local function setup_libraries()
local library = {}
local function add(lib)
for _, p in pairs(vim.fn.expand(lib, false, true)) do
p = vim.loop.fs_realpath(p)
library[p] = true
end
end
local homedir = vim.env.HOME
local workdir = vim.fn.getcwd()
local function dev_vim()
return workdir:find("^" .. homedir .. "/.config/nvim") ~= nil or workdir:find("^" .. homedir .. "/.dotfiles") ~= nil
end
local function dev_awesome()
return workdir:find("^" .. homedir .. "/.config/awesome") ~= nil or workdir:find("^" .. homedir .. "/config/awesome") ~= nil
end
if dev_vim() then
-- add runtime
add("$VIMRUNTIME")
-- add your config
add("~/.config/nvim")
-- add plugins
-- if you're not using packer, then you might need to change the paths below
add("~/.local/share/nvim/site/pack/packer/opt/*")
add("~/.local/share/nvim/site/pack/packer/start/*")
elseif dev_awesome() then
add("$PWD")
add("/usr/share/awesome/lib")
else
add("$PWD")
end
return library
end
local M = {}
M.config = {
on_attach_post = function(client, _)
client.config.settings.Lua.workspace.library = setup_libraries()
end,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
-- Setup your lua path
path = path,
},
completion = { callSnippet = "Both" },
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {
-- neovim
"vim",
-- awesome
"awesome",
"client",
"root",
"screen",
},
},
workspace = {
-- Make the server aware of Neovim runtime files
library =setup_libraries(),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = { enable = false },
},
},
filetypes = { "lua", "lua.luapad", "luapad" },
}
return M
|
local path = vim.split(package.path, ";")
table.insert(path, "lua/?.lua")
table.insert(path, "lua/?/init.lua")
local function setup_libraries()
local library = {}
local function add(lib)
for _, p in pairs(vim.fn.expand(lib, false, true)) do
p = vim.loop.fs_realpath(p)
library[p] = true
end
end
local homedir = vim.env.HOME
local filedir = vim.fn.expand("%:p")
local function dev_vim()
return filedir:find("^" .. homedir .. "/.config/nvim") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/neovim/config") ~= nil
end
local function dev_awesome()
return filedir:find("^" .. homedir .. "/.config/awesome") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/awesome/config") ~= nil
end
local function dev_awesome_custom()
return filedir:find("^" .. homedir .. "/config/awesome") ~= nil
end
if dev_vim() then
-- add runtime
add("$VIMRUNTIME")
-- add your config
add("~/.config/nvim")
-- add plugins
-- if you're not using packer, then you might need to change the paths below
add("~/.local/share/nvim/site/pack/packer/opt/*")
add("~/.local/share/nvim/site/pack/packer/start/*")
elseif dev_awesome() then
add(homedir .. "/.dotfiles/roles/awesome/config")
add(homedir .. "/.dotfiles/roles/awesome/config/*")
add("/usr/share/awesome/lib")
add("/usr/share/awesome/lib/*")
elseif dev_awesome_custom() then
add("$PWD")
add("/usr/share/awesome/lib")
add("/usr/share/awesome/lib/*")
else
add("$PWD")
end
for k, _ in pairs(library) do
print(k)
end
return library
end
local M = {}
M.config = {
on_attach_post = function(client, _)
client.config.settings.Lua.workspace.library = setup_libraries()
end,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
-- Setup your lua path
path = path,
},
completion = { callSnippet = "Both" },
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {
-- neovim
"vim",
-- awesome
"awesome",
"client",
"root",
"screen",
},
},
workspace = {
-- Make the server aware of Neovim runtime files
library = setup_libraries(),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = { enable = false },
},
},
filetypes = { "lua", "lua.luapad", "luapad" },
}
return M
|
fix(nvim): another attempt at sumneko lsp discovery
|
fix(nvim): another attempt at sumneko lsp discovery
|
Lua
|
mit
|
Irubataru/dotfiles,Irubataru/dotfiles,Irubataru/dotfiles
|
4d28d90ddd63f23a2fe653821879703b2a9a3305
|
endnotes.lua
|
endnotes.lua
|
SILE.require("packages/footnotes")
SILE.scratch.endnotes = {}
SILE.registerCommand("endnote", function(options, content)
SILE.call("footnotemark")
--local material = SILE.Commands["rebox"]({}, function()
local material = SILE.Commands["vbox"]({}, function()
SILE.Commands["footnote:font"]({}, function()
SILE.call("footnote:atstart")
SILE.call("footnote:counter")
--SILE.process(content)
--SU.debug("viachristus", content)
SILE.typesetter:typeset("this is a test")
end)
end)
--SU.debug("viachristus", material.height)
SILE.scratch.endnotes[#SILE.scratch.endnotes+1] = material
SILE.scratch.counters.footnote.value = SILE.scratch.counters.footnote.value + 1
end)
SILE.registerCommand("endnotes", function(options, content)
for i=1, #SILE.scratch.endnotes do
SILE.typesetter:pushVbox(SILE.scratch.endnotes[i])
end
SILE.scratch.endnotes = {}
end)
local class = SILE.documentState.documentClass
local originalfinish = class.finish
class.finish = function()
if #SILE.scratch.endnotes >= 1 then
SILE.call("endnotes")
end
return originalfinish(class)
end
|
SILE.require("packages/footnotes")
SILE.scratch.endnotes = {}
SILE.registerCommand("endnote", function(options, content)
SILE.call("footnotemark")
local material = content
local counter = SILE.formatCounter(SILE.scratch.counters.footnote)
SILE.scratch.endnotes[#SILE.scratch.endnotes+1] = function()
return counter, material
end
SILE.scratch.counters.footnote.value = SILE.scratch.counters.footnote.value + 1
end)
SILE.registerCommand("endnote:counter", function(options, content)
SILE.call("noindent")
SILE.typesetter:typeset(options.value..".")
SILE.call("qquad")
end)
SILE.registerCommand("endnotes", function(options, content)
for i=1, #SILE.scratch.endnotes do
local counter, material = SILE.scratch.endnotes[i]()
SILE.Commands["footnote:font"]({}, function()
SILE.call("footnote:atstart")
SILE.call("endnote:counter", { value=counter })
SILE.process(material)
end)
SILE.typesetter:leaveHmode()
end
SILE.scratch.endnotes = {}
SILE.scratch.counters.footnote.value = 1
end)
local class = SILE.documentState.documentClass
local originalfinish = class.finish
class.finish = function()
if #SILE.scratch.endnotes >= 1 then
SILE.call("endnotes")
end
return originalfinish(class)
end
|
Fix endnotes class to actually work
|
Fix endnotes class to actually work
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
a4d060e324037972979a8f8f72a78cae6aa631d0
|
lua-binding/CCB/Loader.lua
|
lua-binding/CCB/Loader.lua
|
local CCBLoader = {}
local function fillCallbacks(proxy, owner, names, nodes, events)
if not owner then return end
--Callbacks
for i = 1, #names do
local callbackName = names[i]
local callbackNode = tolua.cast(nodes[i],"cc.Node")
proxy:setCallback(callbackNode, function(sender, event)
if owner and owner[callbackName] and "function" == type(owner[callbackName]) then
owner[callbackName](owner, sender, event)
else
print("Warning: Cannot find lua function:" .. ":" .. callbackName .. " for selector")
end
end, events[i])
end
end
local function fillMembers(owner, names, nodes)
if not owner then return end
--Variables
for i = 1, #names do
local outletName = names[i]
local outletNode = tolua.cast(nodes[i],"cc.Node")
owner[outletName] = outletNode
-- print("fillMembers:", outletName, outletNode)
end
end
local function extend(node, name, isRoot)
local codePath = (CCBLoader.codeRootPath and CCBLoader.codeRootPath ~= "") and CCBLoader.codeRootPath .. "." .. name or name
local luaObj = require(codePath)
for k,v in pairs(luaObj) do
node[k] = v
end
if not isRoot then
node:ctor()
end
end
local function fillNode(proxy, ccbReader, owner, isRoot)
local rootName = ccbReader:getDocumentControllerName()
local animationManager = ccbReader:getActionManager()
local node = animationManager:getRootNode()
-- print("fillNode:", rootName, node)
--owner set in readCCBFromFile is proxy
if nil ~= owner then
--Callbacks
local ownerCallbackNames = ccbReader:getOwnerCallbackNames()
local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes()
local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents()
fillCallbacks(proxy, owner, ownerCallbackNames, ownerCallbackNodes, ownerCallbackControlEvents)
--Variables
local ownerOutletNames = ccbReader:getOwnerOutletNames()
local ownerOutletNodes = ccbReader:getOwnerOutletNodes()
fillMembers(owner, ownerOutletNames, ownerOutletNodes)
end
--document root
if "" ~= rootName then
extend(node, rootName, isRoot)
node.animationManager = animationManager
--Callbacks
local documentCallbackNames = animationManager:getDocumentCallbackNames()
local documentCallbackNodes = animationManager:getDocumentCallbackNodes()
local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents()
fillCallbacks(proxy, node, documentCallbackNames, documentCallbackNodes, documentCallbackControlEvents)
--Variables
local documentOutletNames = animationManager:getDocumentOutletNames()
local documentOutletNodes = animationManager:getDocumentOutletNodes()
fillMembers(node, documentOutletNames, documentOutletNodes)
--[[
if (typeof(controller.onDidLoadFromCCB) == "function")
controller.onDidLoadFromCCB();
]]--
--Setup timeline callbacks
local keyframeCallbacks = animationManager:getKeyframeCallbacks()
for i = 1 , #keyframeCallbacks do
local callbackCombine = keyframeCallbacks[i]
local beignIndex,endIndex = string.find(callbackCombine,":")
local callbackType = tonumber(string.sub(callbackCombine,1,beignIndex - 1))
local callbackName = string.sub(callbackCombine,endIndex + 1, -1)
--Document callback
if 1 == callbackType then
local callfunc = cc.CallFunc:create(function(sender, event)
if node and node[callbackName] and type(node[callbackName]) == "function" then
node[callbackName](node, sender, event)
else
print("Warning: Cannot find lua function:" .. callbackName .. " for animation selector")
end
end)
animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine);
elseif 2 == callbackType and nil ~= owner then --Owner callback
local callfunc = cc.CallFunc:create(owner[callbackName])--need check
animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine)
end
end
--start animation
local autoPlaySeqId = animationManager:getAutoPlaySequenceId()
if -1 ~= autoPlaySeqId then
animationManager:runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0)
end
end
--subReaders
local subReaders = ccbReader:getSubReaders()
-- print("subReaders:", subReaders and #subReaders or 0, subReaders)
-- table.dump(subReaders)
if subReaders then
for i=1, #subReaders do
local reader = subReaders[i]
fillNode(proxy, reader, owner, false)
end
end
end
local function doLoad(fileName, proxy, owner)
if nil == proxy then
return nil
end
local strFilePath = (CCBLoader.ccbiRootPath and CCBLoader.ccbiRootPath ~= "") and CCBLoader.ccbiRootPath .. fileName or fileName
local ccbReader = proxy:createCCBReader()
local node = ccbReader:load(strFilePath)
fillNode(proxy, ccbReader, owner, true)
return node
end
------------------------------------------------------------
function CCBLoader:setRootPath(codeRoot, ccbiRoot)
if ccbiRoot and string.sub(ccbiRoot, -1) ~= "/" then
ccbiRoot = ccbiRoot .. "/"
end
self.codeRootPath = codeRoot or self.codeRootPath
self.ccbiRootPath = ccbiRoot or self.ccbiRootPath
end
function CCBLoader:load(fileName, owner)
local proxy = cc.CCBProxy:create()
return doLoad(fileName, proxy, owner)
end
return CCBLoader
|
local CCBLoader = {}
local function fillCallbacks(proxy, owner, names, nodes, events)
if not owner then return end
--Callbacks
for i = 1, #names do
local callbackName = names[i]
local callbackNode = tolua.cast(nodes[i],"cc.Node")
proxy:setCallback(callbackNode, function(sender, event)
if owner and owner[callbackName] and "function" == type(owner[callbackName]) then
owner[callbackName](owner, sender, event)
else
print("Warning: Cannot find lua function:" .. ":" .. callbackName .. " for selector")
end
end, events[i])
end
end
local function fillMembers(owner, names, nodes)
if not owner then return end
--Variables
for i = 1, #names do
local outletName = names[i]
local outletNode = tolua.cast(nodes[i],"cc.Node")
owner[outletName] = outletNode
-- print("fillMembers:", outletName, outletNode)
end
end
local function extend(node, name)
local codePath = (CCBLoader.codeRootPath and CCBLoader.codeRootPath ~= "") and CCBLoader.codeRootPath .. "." .. name or name
local luaObj = require(codePath)
for k,v in pairs(luaObj) do
node[k] = v
end
end
local function fillNode(proxy, ccbReader, owner, isRoot)
local rootName = ccbReader:getDocumentControllerName()
local animationManager = ccbReader:getActionManager()
local node = animationManager:getRootNode()
-- print("fillNode:", rootName, node)
--owner set in readCCBFromFile is proxy
if nil ~= owner then
--Callbacks
local ownerCallbackNames = ccbReader:getOwnerCallbackNames()
local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes()
local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents()
fillCallbacks(proxy, owner, ownerCallbackNames, ownerCallbackNodes, ownerCallbackControlEvents)
--Variables
local ownerOutletNames = ccbReader:getOwnerOutletNames()
local ownerOutletNodes = ccbReader:getOwnerOutletNodes()
fillMembers(owner, ownerOutletNames, ownerOutletNodes)
end
--document root
if "" ~= rootName then
extend(node, rootName)
node.animationManager = animationManager
--Callbacks
local documentCallbackNames = animationManager:getDocumentCallbackNames()
local documentCallbackNodes = animationManager:getDocumentCallbackNodes()
local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents()
fillCallbacks(proxy, node, documentCallbackNames, documentCallbackNodes, documentCallbackControlEvents)
--Variables
local documentOutletNames = animationManager:getDocumentOutletNames()
local documentOutletNodes = animationManager:getDocumentOutletNodes()
fillMembers(node, documentOutletNames, documentOutletNodes)
--[[
if (typeof(controller.onDidLoadFromCCB) == "function")
controller.onDidLoadFromCCB();
]]--
--Setup timeline callbacks
local keyframeCallbacks = animationManager:getKeyframeCallbacks()
for i = 1 , #keyframeCallbacks do
local callbackCombine = keyframeCallbacks[i]
local beignIndex,endIndex = string.find(callbackCombine,":")
local callbackType = tonumber(string.sub(callbackCombine,1,beignIndex - 1))
local callbackName = string.sub(callbackCombine,endIndex + 1, -1)
--Document callback
if 1 == callbackType then
local callfunc = cc.CallFunc:create(function(sender, event)
if node and node[callbackName] and type(node[callbackName]) == "function" then
node[callbackName](node, sender, event)
else
print("Warning: Cannot find lua function:" .. callbackName .. " for animation selector")
end
end)
animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine);
elseif 2 == callbackType and nil ~= owner then --Owner callback
local callfunc = cc.CallFunc:create(owner[callbackName])--need check
animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine)
end
end
--start animation
local autoPlaySeqId = animationManager:getAutoPlaySequenceId()
if -1 ~= autoPlaySeqId then
animationManager:runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0)
end
end
--subReaders
local subReaders = ccbReader:getSubReaders()
-- print("subReaders:", subReaders and #subReaders or 0, subReaders)
-- table.dump(subReaders)
if subReaders then
for i=1, #subReaders do
local reader = subReaders[i]
fillNode(proxy, reader, owner, false)
end
end
if not isRoot and node and type(node.ctor) == "function" then
node:ctor()
end
end
local function doLoad(fileName, proxy, owner)
if nil == proxy then
return nil
end
local strFilePath = (CCBLoader.ccbiRootPath and CCBLoader.ccbiRootPath ~= "") and CCBLoader.ccbiRootPath .. fileName or fileName
local ccbReader = proxy:createCCBReader()
local node = ccbReader:load(strFilePath)
fillNode(proxy, ccbReader, owner, true)
return node
end
------------------------------------------------------------
function CCBLoader:setRootPath(codeRoot, ccbiRoot)
if ccbiRoot and string.sub(ccbiRoot, -1) ~= "/" then
ccbiRoot = ccbiRoot .. "/"
end
self.codeRootPath = codeRoot or self.codeRootPath
self.ccbiRootPath = ccbiRoot or self.ccbiRootPath
end
function CCBLoader:load(fileName, owner)
local proxy = cc.CCBProxy:create()
return doLoad(fileName, proxy, owner)
end
return CCBLoader
|
solve sub node ctor not called bug
|
solve sub node ctor not called bug
|
Lua
|
mit
|
Jennal/CocosBuilder,Jennal/CocosBuilder,Jennal/CocosBuilder,Jennal/CocosBuilder,Jennal/CocosBuilder
|
df0a06c8f7e9038df627e99b3d6c3ea6e17cd5d9
|
MMOCoreORB/bin/scripts/loot/items/janta_hides.lua
|
MMOCoreORB/bin/scripts/loot/items/janta_hides.lua
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
janta_hides = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/component/armor/armor_segment_enhancement_janta.iff",
craftingValues = {
{"armor_special_type",0,0,0},
{"armor_effectiveness",3,8,10},
{"armor_integrity",0,0,0,0},
{"acideffectiveness",0,0,0,0},
{"heateffectiveness",0,0,0,0},
{"energyeffectiveness",0,0,0,0},
{"kineticeffectiveness",0,0,0,0},
{"coldeffectiveness",0,0,0,0},
{"blasteffectiveness",0,0,0,0},
{"electricaleffectiveness",0,0,0,0},
{"stuneffectiveness",0,0,0,0},
{"armor_health_encumbrance",0,0,0,0},
{"armor_action_encumbrance",0,0,0,0},
{"armor_mind_encumbrance",0,0,0,0},
{"hitpoints",0,0,0,0},
{"useCount",1,7,0},
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("janta_hides", janta_hides)
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
janta_hides = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/component/armor/armor_segment_enhancement_janta.iff",
craftingValues = {
{"armor_special_type",0,0,0},
{"armor_effectiveness",3,8,10},
{"hitpoints",0,0,0,0},
{"useCount",1,7,0},
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("janta_hides", janta_hides)
|
(Unstable) [Fixed] Janta Hides
|
(Unstable) [Fixed] Janta Hides
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5122 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
ab18fa731bf81f02426eb3c1304d4e6cae81d3e3
|
resources/prosody-plugins/mod_muc_allowners.lua
|
resources/prosody-plugins/mod_muc_allowners.lua
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
end
load_config();
local function is_admin(jid)
return um_is_admin(jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain][email protected]
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil or not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local st = require "util.stanza";
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local get_room_from_jid = util.get_room_from_jid;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local disable_revoke_owners;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
disable_revoke_owners = module:get_option_boolean("allowners_disable_revoke_owners", false);
end
load_config();
local function is_admin(_jid)
return um_is_admin(_jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain][email protected]
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s',
room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s',
subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil
or not stanza.attr
or not stanza.attr.to
or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
-- filters any attempt to revoke owner rights on non moderated rooms
function filter_admin_set_query(event)
local origin, stanza = event.origin, event.stanza;
local room_jid = jid_bare(stanza.attr.to);
local room = get_room_from_jid(room_jid);
local item = stanza.tags[1].tags[1];
local _aff = item.attr.affiliation;
-- if it is a moderated room we skip it
if is_moderated(room.jid) then
return nil;
end
-- any revoking is disabled
if _aff ~= 'owner' then
origin.send(st.error_reply(stanza, "auth", "forbidden"));
return true;
end
end
if not disable_revoke_owners then
-- default prosody priority for handling these is -2
module:hook("iq-set/bare/http://jabber.org/protocol/muc#admin:query", filter_admin_set_query, 5);
module:hook("iq-set/host/http://jabber.org/protocol/muc#admin:query", filter_admin_set_query, 5);
end
|
Adds new option to allowners module (#10207)
|
Adds new option to allowners module (#10207)
* feat: Adds option to disable owner revoke in allowners module.
* squash: Fixes few lua check warnings.
|
Lua
|
apache-2.0
|
gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet
|
07e0ee74e05d4cb9b8d08820496d1027a9460502
|
OS/DiskOS/Programs/run.lua
|
OS/DiskOS/Programs/run.lua
|
--This file loads a lk12 disk and executes it
--First we will start by obtaining the disk data
--We will run the current code in the editor
local term = require("C://terminal")
local eapi = require("C://Editors")
local mapobj = require("C://Libraries/map")
local sprid = 3 --"spritesheet"
local codeid = 2 --"luacode"
local tileid = 4 --"tilemap"
local swidth, sheight = screenSize()
--Load the spritesheet
local SpriteMap, FlagsData
local sheetImage = image(eapi.leditors[sprid]:exportImage())
local FlagsData = eapi.leditors[sprid]:getFlags()
local sheetW, sheetH = sheetImage:width()/8, sheetImage:height()/8
SpriteMap = SpriteSheet(sheetImage,sheetW,sheetH)
--Load the tilemap
local mapData = eapi.leditors[tileid]:export()
local mapW, mapH = swidth*0.75, sheight
local TileMap = mapobj(mapW,mapH,SpriteMap)
TileMap:import(mapData)
--Load the code
local luacode = eapi.leditors[codeid]:export()
luacode = luacode .. "\n__".."_autoEventLoop()" --Because trible _ are not allowed in LIKO-12
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(8) print("Compile ERR: "..err )
return
end
--Upload the data to the ram
local SpriteSheetAddr = binToNum(memget(0x0054, 4))
local MapDataAddr = binToNum(memget(0x0058, 4))
local LuaCodeAddr = binToNum(memget(0x0068, 4))
local SpriteFlagsAddr = SpriteSheetAddr + 12*1024
memset(SpriteSheetAddr, imgToBin(sheetImage))
memset(SpriteFlagsAddr, FlagsData)
memset(MapDataAddr, mapToBin(TileMap))
memset(LuaCodeAddr, codeToBin(luacode:sub(1,20*1024)))
--Create the sandboxed global variables
local glob = _Freshglobals()
glob._G = glob --Magic ;)
local co
glob.getfenv = function(f)
if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end
local ok, env = pcall(getfenv,f)
if not ok then return error(env) end
if env == _G then env = {} end --Protection
return env
end
glob.setfenv = function(f,env)
if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end
if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end
local oldenv = getfenv(f)
if oldenv == _G then return end --Trying to make a crash ! evil.
local ok, err = pcall(setfenv,f,env)
if not ok then return error(err) end
end
glob.loadstring = function(data)
local chunk, err = loadstring(data)
if not chunk then return nil, err end
setfenv(chunk,glob)
return chunk
end
glob.coroutine.running = function()
local curco = coroutine.running()
if co and curco == co then return end
return curco
end
--Add peripherals api
local blocklist = { HDD = true, WEB = true, Floppy = true }
local perglob = {GPU = true, CPU = true, Keyboard = true, RAM = true} --The perihperals to make global not in a table.
local _,directapi = coroutine.yield("BIOS:DirectAPI"); directapi = directapi or {}
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[k] = nil end
for peripheral,funcs in pairs(perlist) do
local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end
for _,func in ipairs(funcs) do
if func:sub(1,1) ~= "_" then
if directapi[peripheral] and directapi[peripheral][func] then
holder[func] = directapi[peripheral][func]
else
local command = peripheral..":"..func
holder[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
local function autoEventLoop()
if glob._init and type(glob._init) == "function" then
glob._init()
end
if type(glob._eventLoop) == "boolean" and not glob._eventLoop then return end --Skip the auto eventLoop.
if glob._update or glob._draw or glob._eventLoop then
eventLoop()
end
end
setfenv(autoEventLoop,glob)
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
glob.TileMap = TileMap
glob.MapObj = mapobj
local UsedDoFile = false --So it can be only used for once
glob.dofile = function(path)
if UsedDoFile then return error("dofile() can be only used for once !") end
UsedDoFile = true
local chunk, err = fs.load(path)
if not chunk then return error(err) end
setfenv(chunk,glob)
local ok, err = pcall(chunk)
if not ok then return error(err) end
end
glob["__".."_".."autoEventLoop"] = autoEventLoop --Because trible _ are not allowed in LIKO-12
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
local function extractArgs(args,factor)
local nargs = {}
for k,v in ipairs(args) do
if k > factor then table.insert(nargs,v) end
end
return nargs
end
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
if os.clock() > eventclock + 3.5 then
color(8) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":") or 0
err = err:sub(pos+1,-1); color(8) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
--This file loads a lk12 disk and executes it
--First we will start by obtaining the disk data
--We will run the current code in the editor
local term = require("C://terminal")
local eapi = require("C://Editors")
local mapobj = require("C://Libraries/map")
local sprid = 3 --"spritesheet"
local codeid = 2 --"luacode"
local tileid = 4 --"tilemap"
local swidth, sheight = screenSize()
--Load the spritesheet
local SpriteMap, FlagsData
local sheetImage = image(eapi.leditors[sprid]:exportImage())
local FlagsData = eapi.leditors[sprid]:getFlags()
local sheetW, sheetH = sheetImage:width()/8, sheetImage:height()/8
SpriteMap = SpriteSheet(sheetImage,sheetW,sheetH)
--Load the tilemap
local mapData = eapi.leditors[tileid]:export()
local mapW, mapH = swidth*0.75, sheight
local TileMap = mapobj(mapW,mapH,SpriteMap)
TileMap:import(mapData)
--Load the code
local luacode = eapi.leditors[codeid]:export()
luacode = luacode .. "\n__".."_autoEventLoop()" --Because trible _ are not allowed in LIKO-12
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(8) print("Compile ERR: "..err )
return
end
--Upload the data to the ram
local SpriteSheetAddr = binToNum(memget(0x0054, 4))
local MapDataAddr = binToNum(memget(0x0058, 4))
local LuaCodeAddr = binToNum(memget(0x0068, 4))
local SpriteFlagsAddr = SpriteSheetAddr + 12*1024
memset(SpriteSheetAddr, imgToBin(sheetImage))
memset(SpriteFlagsAddr, FlagsData)
memset(MapDataAddr, mapToBin(TileMap))
memset(LuaCodeAddr, codeToBin(luacode:sub(1,20*1024)))
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
local co
glob.getfenv = function(f)
if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end
local ok, env = pcall(getfenv,f)
if not ok then return error(env) end
if env == _G then env = {} end --Protection
return env
end
glob.setfenv = function(f,env)
if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end
if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end
local oldenv = getfenv(f)
if oldenv == _G then return end --Trying to make a crash ! evil.
local ok, err = pcall(setfenv,f,env)
if not ok then return error(err) end
end
glob.loadstring = function(data)
local chunk, err = loadstring(data)
if not chunk then return nil, err end
setfenv(chunk,glob)
return chunk
end
glob.coroutine.running = function()
local curco = coroutine.running()
if co and curco == co then return end
return curco
end
--Add peripherals api
local blocklist = { HDD = true, WEB = true, Floppy = true }
local perglob = {GPU = true, CPU = true, Keyboard = true, RAM = true} --The perihperals to make global not in a table.
local _,directapi = coroutine.yield("BIOS:DirectAPI"); directapi = directapi or {}
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[k] = nil end
for peripheral,funcs in pairs(perlist) do
local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end
for _,func in ipairs(funcs) do
if func:sub(1,1) ~= "_" then
if directapi[peripheral] and directapi[peripheral][func] then
holder[func] = directapi[peripheral][func]
else
local command = peripheral..":"..func
holder[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
local function autoEventLoop()
if glob._init and type(glob._init) == "function" then
glob._init()
end
if type(glob._eventLoop) == "boolean" and not glob._eventLoop then return end --Skip the auto eventLoop.
if glob._update or glob._draw or glob._eventLoop then
eventLoop()
end
end
setfenv(autoEventLoop,glob)
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
glob.TileMap = TileMap
glob.MapObj = mapobj
local UsedDoFile = false --So it can be only used for once
glob.dofile = function(path)
if UsedDoFile then return error("dofile() can be only used for once !") end
UsedDoFile = true
local chunk, err = fs.load(path)
if not chunk then return error(err) end
setfenv(chunk,glob)
local ok, err = pcall(chunk)
if not ok then return error(err) end
end
glob["__".."_".."autoEventLoop"] = autoEventLoop --Because trible _ are not allowed in LIKO-12
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
--Run the thing !
local function extractArgs(args,factor)
local nargs = {}
for k,v in ipairs(args) do
if k > factor then table.insert(nargs,v) end
end
return nargs
end
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
if os.clock() > eventclock + 3.5 then
color(8) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":") or 0
err = err:sub(pos+1,-1); color(8) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
end
end
clearEStack()
print("")
|
Bugfixes
|
Bugfixes
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
972dbec0220c04b5b1a1249c5b4e2d4d05e4531a
|
sslobby/gamemode/init.lua
|
sslobby/gamemode/init.lua
|
AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("cl_scoreboard.lua")
AddCSLuaFile("modules/sh_link.lua")
AddCSLuaFile("modules/cl_link.lua")
AddCSLuaFile("modules/sh_chairs.lua")
AddCSLuaFile("modules/cl_chairs.lua")
AddCSLuaFile("modules/cl_worldpicker.lua")
AddCSLuaFile("modules/sh_minigame.lua")
AddCSLuaFile("modules/cl_minigame.lua")
AddCSLuaFile("modules/cl_worldpanel.lua")
AddCSLuaFile("modules/sh_leaderboard.lua")
AddCSLuaFile("modules/cl_leaderboard.lua")
AddCSLuaFile("modules/sh_sound.lua")
include("shared.lua")
include("player_class/player_lobby.lua")
include("player_extended.lua")
include("modules/sv_socket.lua")
include("modules/sh_link.lua")
include("modules/sv_link.lua")
include("modules/sh_chairs.lua")
include("modules/sv_chairs.lua")
include("modules/sv_worldpicker.lua")
include("modules/sh_minigame.lua")
include("modules/sv_minigame.lua")
include("modules/sh_leaderboard.lua")
include("modules/sv_leaderboard.lua")
include("modules/sv_elevator.lua")
include("modules/sh_sound.lua")
--------------------------------------------------
--
--------------------------------------------------
function GM:InitPostEntity()
self.spawnPoints = {lounge = {}}
local spawns = ents.FindByClass("info_player_spawn")
for k, entity in pairs(spawns) do
if (entity.lounge) then
table.insert(self.spawnPoints.lounge, entity)
else
if (!entity.minigames) then
table.insert(self.spawnPoints, entity)
end
end
end
local slotMachines = ents.FindByClass("prop_physics_multiplayer")
for k, entity in pairs(slotMachines) do
if (IsValid(entity)) then
local model = string.lower(entity:GetModel())
if (model == "models/sam/slotmachine.mdl") then
local position, angles = entity:GetPos(), entity:GetAngles()
local slotMachine = ents.Create("slot_machine")
slotMachine:SetPos(position)
slotMachine:SetAngles(angles)
slotMachine:Spawn()
entity:Remove()
end
end
end
timer.Simple(5,function()
socket.SetupHost("192.168.1.152", 40000)
timer.Simple(2,function()
socket.AddServer("192.168.1.152", 40001)
end)
end)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerInitialSpawn(player)
self.BaseClass:PlayerInitialSpawn(player)
player:SetTeam(TEAM_READY)
player:SetCollideWithTeammates(true)
player:SetModel("models/player/group01/male_01.mdl")
timer.Simple(0.4,function()
for i = LEADERBOARD_DAILY, LEADERBOARD_ALLTIME_10 do
SS.Lobby.LeaderBoard.Network(i, player)
end
SS.Lobby.Minigame:UpdateScreen(player)
end)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerSpawn(player)
self.BaseClass:PlayerSpawn(player)
player:SetJumpPower(205)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerLoadout(player)
player:StripWeapons()
player:RemoveAllAmmo()
SS.Lobby.Minigame:CallWithPlayer("PlayerLoadout", player)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable )
local Pos = spawnpointent:GetPos()
-- Note that we're searching the default hull size here for a player in the way of our spawning.
-- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job
-- (HL2DM kills everything within a 128 unit radius)
local Ents = ents.FindInBox( Pos + Vector( -14, -14, 0 ), Pos + Vector( 14, 14, 64 ) )
if ( pl:Team() == TEAM_SPECTATOR ) then return true end
local Blockers = 0
for k, v in pairs( Ents ) do
if ( IsValid( v ) && v:GetClass() == "player" && v:Alive() ) then
Blockers = Blockers + 1
if ( bMakeSuitable ) then
v:Kill()
end
end
end
if ( bMakeSuitable ) then return true end
if ( Blockers > 0 ) then return false end
return true
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerSelectSpawn(player, minigame)
local spawnPoint = self.spawnPoints.lounge
if (player:Team() > TEAM_READY) then
if (minigame) then
spawnPoint = minigame:GetSpawnPoints(player)
else
spawnPoint = self.spawnPoints
end
end
for i = 1, #spawnPoint do
local entity = spawnPoint[i]
local suitAble = self:IsSpawnpointSuitable(player, entity, false)
if (suitAble) then
return entity
end
end
-- IS THIS SHIT SPAWNING THE PLAYER AT THE QUEUE AGAIN????
spawnPoint = table.Random(spawnPoint)
return spawnPoint
end
--------------------------------------------------
--
--------------------------------------------------
function GM:KeyPress(player, key)
if (key == IN_USE) then
local trace = player:EyeTrace(84)
if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then
local canSlap = player:CanSlap(trace.Entity)
if (canSlap) then
player:Slap(trace.Entity)
end
end
end
SS.Lobby.Minigame:CallWithPlayer("KeyPress", player, key)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:DoPlayerDeath(victim, inflictor, dmginfo)
SS.Lobby.Minigame:CallWithPlayer("DoPlayerDeath", victim, inflictor, dmginfo)
return self.BaseClass:DoPlayerDeath(victim, inflictor, dmginfo)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:CanPlayerSuicide(player)
local bool = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSuicide", player)
if (bool != nil) then
return bool
end
return true
end
--------------------------------------------------
--
--------------------------------------------------
function GM:EntityKeyValue(entity, key, value)
if (IsValid(entity)) then
local class = entity:GetClass()
if (class == "func_door" and key == "hammerid") then
entity.id = tonumber(value)
end
end
end
--------------------------------------------------
--
--------------------------------------------------
function GM:AllowPlayerPickup( ply, object )
return false
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerCanPickupItem( player, entity )
return false
end
-- dev
concommand.Add("poo",function()
RunConsoleCommand("bot")
timer.Simple(0,function()
for k, bot in pairs(player.GetBots()) do
bot:SetTeam(math.random(TEAM_RED,TEAM_ORANGE))
bot:SetPos(Vector(-607.938110, -447.018799, 16.031250))
bot:Freeze(true)
end
end)
end)
|
AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("cl_scoreboard.lua")
AddCSLuaFile("modules/sh_link.lua")
AddCSLuaFile("modules/cl_link.lua")
AddCSLuaFile("modules/sh_chairs.lua")
AddCSLuaFile("modules/cl_chairs.lua")
AddCSLuaFile("modules/cl_worldpicker.lua")
AddCSLuaFile("modules/sh_minigame.lua")
AddCSLuaFile("modules/cl_minigame.lua")
AddCSLuaFile("modules/cl_worldpanel.lua")
AddCSLuaFile("modules/sh_leaderboard.lua")
AddCSLuaFile("modules/cl_leaderboard.lua")
AddCSLuaFile("modules/sh_sound.lua")
include("shared.lua")
include("player_class/player_lobby.lua")
include("player_extended.lua")
include("modules/sv_socket.lua")
include("modules/sh_link.lua")
include("modules/sv_link.lua")
include("modules/sh_chairs.lua")
include("modules/sv_chairs.lua")
include("modules/sv_worldpicker.lua")
include("modules/sh_minigame.lua")
include("modules/sv_minigame.lua")
include("modules/sh_leaderboard.lua")
include("modules/sv_leaderboard.lua")
include("modules/sv_elevator.lua")
include("modules/sh_sound.lua")
--------------------------------------------------
--
--------------------------------------------------
function GM:InitPostEntity()
self.spawnPoints = {lounge = {}}
local spawns = ents.FindByClass("info_player_spawn")
for k, entity in pairs(spawns) do
if (entity.lounge) then
table.insert(self.spawnPoints.lounge, entity)
else
if (!entity.minigames) then
table.insert(self.spawnPoints, entity)
end
end
end
local slotMachines = ents.FindByClass("prop_physics_multiplayer")
for k, entity in pairs(slotMachines) do
if (IsValid(entity)) then
local model = string.lower(entity:GetModel())
if (model == "models/sam/slotmachine.mdl") then
local position, angles = entity:GetPos(), entity:GetAngles()
local slotMachine = ents.Create("slot_machine")
slotMachine:SetPos(position)
slotMachine:SetAngles(angles)
slotMachine:Spawn()
entity:Remove()
end
end
end
timer.Simple(5,function()
socket.SetupHost("192.168.1.152", 40000)
timer.Simple(2,function()
socket.AddServer("192.168.1.152", 40001)
end)
end)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerInitialSpawn(player)
self.BaseClass:PlayerInitialSpawn(player)
player:SetTeam(TEAM_READY)
player:SetCollideWithTeammates(true)
player:SetModel("models/player/group01/male_01.mdl")
timer.Simple(0.4,function()
for i = LEADERBOARD_DAILY, LEADERBOARD_ALLTIME_10 do
SS.Lobby.LeaderBoard.Network(i, player)
end
SS.Lobby.Minigame:UpdateScreen(player)
end)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerSpawn(player)
self.BaseClass:PlayerSpawn(player)
player:SetJumpPower(205)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerLoadout(player)
player:StripWeapons()
player:RemoveAllAmmo()
SS.Lobby.Minigame:CallWithPlayer("PlayerLoadout", player)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable )
local Pos = spawnpointent:GetPos()
-- Note that we're searching the default hull size here for a player in the way of our spawning.
-- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job
-- (HL2DM kills everything within a 128 unit radius)
local Ents = ents.FindInBox( Pos + Vector( -14, -14, 0 ), Pos + Vector( 14, 14, 64 ) )
if ( pl:Team() == TEAM_SPECTATOR ) then return true end
local Blockers = 0
for k, v in pairs( Ents ) do
if ( IsValid( v ) && v:GetClass() == "player" && v:Alive() ) then
Blockers = Blockers + 1
if ( bMakeSuitable ) then
v:Kill()
end
end
end
if ( bMakeSuitable ) then return true end
if ( Blockers > 0 ) then return false end
return true
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerSelectSpawn(player, minigame)
local spawnPoint = self.spawnPoints.lounge
if (player:Team() > TEAM_READY) then
if (minigame) then
spawnPoint = minigame:GetSpawnPoints(player)
else
spawnPoint = self.spawnPoints
end
end
for i = 1, #spawnPoint do
local entity = spawnPoint[i]
local suitAble = self:IsSpawnpointSuitable(player, entity, false)
if (suitAble) then
return entity
end
end
-- IS THIS SHIT SPAWNING THE PLAYER AT THE QUEUE AGAIN????
spawnPoint = table.Random(spawnPoint)
return spawnPoint
end
--------------------------------------------------
--
--------------------------------------------------
function GM:KeyPress(player, key)
if (key == IN_USE) then
local trace = player:EyeTrace(84)
if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then
local canSlap = player:CanSlap(trace.Entity)
if (canSlap) then
player:Slap(trace.Entity)
end
end
end
SS.Lobby.Minigame:CallWithPlayer("KeyPress", player, key)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:DoPlayerDeath(victim, inflictor, dmginfo)
SS.Lobby.Minigame:CallWithPlayer("DoPlayerDeath", victim, inflictor, dmginfo)
return self.BaseClass:DoPlayerDeath(victim, inflictor, dmginfo)
end
--------------------------------------------------
--
--------------------------------------------------
function GM:CanPlayerSuicide(player)
local bool = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSuicide", player)
if (bool != nil) then
return bool
end
return true
end
--------------------------------------------------
--
--------------------------------------------------
function GM:EntityKeyValue(entity, key, value)
if (IsValid(entity)) then
local class = entity:GetClass()
if (class == "func_door" and key == "hammerid") then
entity.id = tonumber(value)
end
end
end
--------------------------------------------------
--
--------------------------------------------------
function GM:AllowPlayerPickup( ply, object )
return false
end
--------------------------------------------------
--
--------------------------------------------------
function GM:PlayerCanPickupItem( player, entity )
return false
end
--------------------------------------------------
--
--------------------------------------------------
function GM:AllowPlayerPickup(ply, entity)
if ply:GetRank() == 100 then
return true
else
return false
end
end
-- dev
concommand.Add("poo",function()
RunConsoleCommand("bot")
timer.Simple(0,function()
for k, bot in pairs(player.GetBots()) do
bot:SetTeam(math.random(TEAM_RED,TEAM_ORANGE))
bot:SetPos(Vector(-607.938110, -447.018799, 16.031250))
bot:Freeze(true)
end
end)
end)
|
I'm almost certain this if the final fix!
|
I'm almost certain this if the final fix!
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
db66dcf83df7cbfd1f4ce68f4104fa98ab91afaa
|
src/copas/limit.lua
|
src/copas/limit.lua
|
--------------------------------------------------------------
-- Limits resource usage while executing tasks.
-- Tasks added will be run in parallel, with a maximum of
-- simultaneous tasks to prevent consuming all/too many resources.
-- Every task added will immediately be scheduled (if there is room)
-- using the `wait` method one can wait for completion.
local copas = require("copas")
local pack = table.pack or function(...) return {n=select('#',...),...} end
local unpack = function(t) return (table.unpack or unpack)(t, 1, t.n or #t) end
-- Add a task to the queue, returns the coroutine created
-- identical to `copas.addthread`. Can be called while the
-- set of tasks is executing.
local function add(self, task, ...)
local carg = pack(...)
local coro = copas.addthread(function()
copas.sleep(-1) -- go to sleep until being woken
local suc, err = pcall(task, unpack(carg)) -- start the task
self:removethread(coroutine.running()) -- dismiss ourselves
if not suc then error(err) end -- rethrow error
end)
table.insert(self.queue, coro) -- store in list
self:next()
return coro
end
-- remove a task from the queue. Can be called while the
-- set of tasks is executing. Will NOT stop the task if
-- it is already running.
local function remove(self, coro)
self.queue[coro] = nil
if self.running[coro] then
-- it is in the already running set
self.running[coro] = nil
self.count = self.count - 1
else
-- check the queue and remove if found
for i, item in ipairs(self.queue) do
if coro == item then
table.remove(self.queue, i)
break
end
end
end
self:next()
end
-- schedules the next task (if any) for execution, signals completeness
local function nxt(self)
while self.count < self.maxt do
local coro = self.queue[1]
if not coro then break end -- queue is empty, so nothing to add
-- move it to running and restart the task
table.remove(self.queue, 1)
self.running[coro] = coro
self.count = self.count + 1
copas.wakeup(coro)
end
if self.count == 0 and next(self.waiting) then
-- all tasks done, resume the waiting tasks so they can unblock/return
for coro in pairs(self.waiting) do
copas.wakeup(coro)
end
end
end
-- Waits for the tasks. Yields until all are finished
local function wait(self)
if self.count == 0 then return end -- There's nothing to do...
local coro = coroutine.running()
-- now store this coroutine (so we know which to wakeup) and go to sleep
self.waiting[coro] = true
copas.sleep(-1)
self.waiting[coro] = nil
end
-- creats a new tasksrunner, with maximum maxt simultaneous threads
local function new(maxt)
return {
maxt = maxt or 99999, -- max simultaneous tasks
count = 0, -- count of running tasks
queue = {}, -- tasks waiting (list/array)
running = {}, -- tasks currently running (indexed by coroutine)
waiting = {}, -- coroutines, waiting for all tasks being finished (indexed by coro)
addthread = add,
removethread = remove,
next = nxt,
wait = wait,
}
end
return { new = new }
|
--------------------------------------------------------------
-- Limits resource usage while executing tasks.
-- Tasks added will be run in parallel, with a maximum of
-- simultaneous tasks to prevent consuming all/too many resources.
-- Every task added will immediately be scheduled (if there is room)
-- using the `wait` method one can wait for completion.
local copas = require("copas")
local pack = table.pack or function(...) return {n=select('#',...),...} end
local unpack = function(t) return (table.unpack or unpack)(t, 1, t.n or #t) end
local pcall = pcall
if _VERSION=="Lua 5.1" then -- obsolete: only for Lua 5.1 compatibility
pcall = require("coxpcall").pcall
end
-- Add a task to the queue, returns the coroutine created
-- identical to `copas.addthread`. Can be called while the
-- set of tasks is executing.
local function add(self, task, ...)
local carg = pack(...)
local coro = copas.addthread(function()
copas.sleep(-1) -- go to sleep until being woken
local suc, err = pcall(task, unpack(carg)) -- start the task
self:removethread(coroutine.running()) -- dismiss ourselves
if not suc then error(err) end -- rethrow error
end)
table.insert(self.queue, coro) -- store in list
self:next()
return coro
end
-- remove a task from the queue. Can be called while the
-- set of tasks is executing. Will NOT stop the task if
-- it is already running.
local function remove(self, coro)
self.queue[coro] = nil
if self.running[coro] then
-- it is in the already running set
self.running[coro] = nil
self.count = self.count - 1
else
-- check the queue and remove if found
for i, item in ipairs(self.queue) do
if coro == item then
table.remove(self.queue, i)
break
end
end
end
self:next()
end
-- schedules the next task (if any) for execution, signals completeness
local function nxt(self)
while self.count < self.maxt do
local coro = self.queue[1]
if not coro then break end -- queue is empty, so nothing to add
-- move it to running and restart the task
table.remove(self.queue, 1)
self.running[coro] = coro
self.count = self.count + 1
copas.wakeup(coro)
end
if self.count == 0 and next(self.waiting) then
-- all tasks done, resume the waiting tasks so they can unblock/return
for coro in pairs(self.waiting) do
copas.wakeup(coro)
end
end
end
-- Waits for the tasks. Yields until all are finished
local function wait(self)
if self.count == 0 then return end -- There's nothing to do...
local coro = coroutine.running()
-- now store this coroutine (so we know which to wakeup) and go to sleep
self.waiting[coro] = true
copas.sleep(-1)
self.waiting[coro] = nil
end
-- creats a new tasksrunner, with maximum maxt simultaneous threads
local function new(maxt)
return {
maxt = maxt or 99999, -- max simultaneous tasks
count = 0, -- count of running tasks
queue = {}, -- tasks waiting (list/array)
running = {}, -- tasks currently running (indexed by coroutine)
waiting = {}, -- coroutines, waiting for all tasks being finished (indexed by coro)
addthread = add,
removethread = remove,
next = nxt,
wait = wait,
}
end
return { new = new }
|
fix issue with yielding across c boundary errors in limit.lua. Only applies to Lua 5.1
|
fix issue with yielding across c boundary errors in limit.lua.
Only applies to Lua 5.1
|
Lua
|
mit
|
keplerproject/copas
|
fb76c044f67de90824637aa02aa4a667c0242085
|
api.lua
|
api.lua
|
local api = {}
local http = require("socket.http")
local https = require("ssl.https")
local ltn12 = require("ltn12")
local cjson = require("cjson")
local encode = require("multipart-post").encode
https.TIMEOUT = 5
local utils = require("utils")
---@param method string
---@param parameters table
function api.makeRequest(method, parameters)
local response = {}
empty = true
for k, v in pairs(parameters) do
if type(v) == "number" or type(v) == "boolean" then
parameters[k] = tostring(v)
end
empty = false
end
logger:info("call " .. method .. " with " .. utils.encode(parameters))
local success, code, headers, status
if empty then
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "GET"
}
print(success, code, headers, status)
else
local body, boundary = encode(parameters)
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data; boundary=" .. boundary,
["Content-Length"] = string.len(body),
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response),
}
end
if success then
local status, msg = pcall(cjson.decode, table.concat(response))
if status then
logger:info("response " .. utils.encode(msg))
return msg
else
logger:error("failed to decode: " .. msg)
end
else
logger:error("failed to request: " .. code)
end
end
function api.fetch()
logger:info("fetching latest API ...")
local html = utils.curl("https://core.telegram.org/bots/api"):match("Available methods(.+)$")
html = utils.htmlDecode(html)
local apis = {}
for method, content in html:gsub("<h4>", "<h4><h4>"):gmatch('<h4>[^\n]-</i></a>([a-z]%S-)</h4>(.-)<h4>') do
local t = {
parameters = {},
order = {}
}
setmetatable(t, {
__call = function(...)
local args = {...}
local body = {}
local named = (#args == 1 and type(args[1]) == "table")
for i = 1, #t.order do
body[t.order[i]] = named and args[1][t.order[i]] or args[i]
if (t.parameters[t.order[i]].required and not body[t.order[i]]) then
logger:error("method " .. method .. " missing parameter " .. t.order[i])
return false
end
end
return api.makeRequest(method, body)
end,
__tostring = function()
return table.concat({
"[method] ", method, "\n",
"[description] ", t.description, "\n",
"[parameters] ", table.concat(t.order, ", "),
})
end
})
local description, parameter
if content:find("table") then
description, parameter = content:match('%s*(.-)%s*<table class="table">.-</tr>(.-)</table>')
else
description = content:match("^%s*(.-)%s*$")
parameter = ""
end
t.description = description:gsub("<.->", ""):gsub("\n\n", "\n")
for name, var, req, des in parameter:gmatch('<tr>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*</tr>') do
table.insert(t.order, name)
t.parameters[name] = {
type = var:gsub("<.->", ""),
required = req == "Yes",
description = des:gsub("<.->", "")
}
end
apis[method] = t
end
return apis
end
return api
|
local api = {}
local http = require("socket.http")
local https = require("ssl.https")
local ltn12 = require("ltn12")
local cjson = require("cjson")
local encode = require("multipart-post").encode
https.TIMEOUT = 5
local utils = require("utils")
---@param method string
---@param parameters table
function api.makeRequest(method, parameters)
local response = {}
empty = true
for k, v in pairs(parameters) do
if type(v) == "number" or type(v) == "boolean" then
parameters[k] = tostring(v)
end
empty = false
end
logger:info("call " .. method .. " with " .. utils.encode(parameters))
local success, code, headers, status
if empty then
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "GET",
sink = ltn12.sink.table(response),
}
else
local body, boundary = encode(parameters)
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data; boundary=" .. boundary,
["Content-Length"] = string.len(body),
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response),
}
end
if success then
local status, msg = pcall(cjson.decode, table.concat(response))
if status then
logger:info("response " .. utils.encode(msg))
return msg
else
logger:error("failed to decode: " .. msg)
end
else
logger:error("failed to request: " .. code)
end
end
function api.fetch()
logger:info("fetching latest API ...")
local html = utils.curl("https://core.telegram.org/bots/api"):match("Available methods(.+)$")
html = utils.htmlDecode(html)
local apis = {}
for method, content in html:gsub("<h4>", "<h4><h4>"):gmatch('<h4>[^\n]-</i></a>([a-z]%S-)</h4>(.-)<h4>') do
local t = {
parameters = {},
order = {}
}
setmetatable(t, {
__call = function(...)
local args = {...}
local body = {}
local named = (#args == 1 and type(args[1]) == "table")
for i = 1, #t.order do
body[t.order[i]] = named and args[1][t.order[i]] or args[i]
if (t.parameters[t.order[i]].required and not body[t.order[i]]) then
logger:error("method " .. method .. " missing parameter " .. t.order[i])
return false
end
end
return api.makeRequest(method, body)
end,
__tostring = function()
return table.concat({
"[method] ", method, "\n",
"[description] ", t.description, "\n",
"[parameters] ", table.concat(t.order, ", "),
})
end
})
local description, parameter
if content:find("table") then
description, parameter = content:match('%s*(.-)%s*<table class="table">.-</tr>(.-)</table>')
else
description = content:match("^%s*(.-)%s*$")
parameter = ""
end
t.description = description:gsub("<.->", ""):gsub("\n\n", "\n")
for name, var, req, des in parameter:gmatch('<tr>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*</tr>') do
table.insert(t.order, name)
t.parameters[name] = {
type = var:gsub("<.->", ""),
required = req == "Yes",
description = des:gsub("<.->", "")
}
end
apis[method] = t
end
return apis
end
return api
|
fix(api.lua): missing sink for get
|
fix(api.lua): missing sink for get
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
1e991db95dbd61841e114c66eefc43b1c19f302c
|
stdlib/data/technology.lua
|
stdlib/data/technology.lua
|
--- Technology
-- @classmod Technology
local Technology = {
_class = 'technology'
}
setmetatable(Technology, require('stdlib/data/data'))
local Is = require('stdlib/utils/is')
function Technology:_caller(tech)
return self:get(tech, 'technology')
end
--[[
type = "technology",
name = "military",
icon = "__base__/graphics/technology/military.png",
effects =
{
{
type = "unlock-recipe",
recipe = "submachine-gun"
},
{
type = "unlock-recipe",
recipe = "shotgun"
},
{
type = "unlock-recipe",
recipe = "shotgun-shell"
}
},
unit =
{
count = 10,
ingredients = {{"science-pack-1", 1}},
time = 15
},
order = "e-a-a"
--]]
-- local function create_technology_prototype(name)
-- local new = {
-- type = type,
-- name = name,
-- }
-- data:extend{new}
-- return true
-- end
function Technology:add_effect(effect, unlock_type)
Is.Assert(effect)
--todo fix for non recipe types
local add_unlock =
function(technology, name)
local effects = technology.effects
effects[#effects + 1] = {
type = unlock_type,
recipe = name
}
end
if self:valid('technology') then
local Recipe = require('stdlib/data/recipe')
unlock_type = (not unlock_type and 'unlock-recipe') or unlock_type
local r_name = type(effect) == 'table' and effect.name or effect
if unlock_type == 'unlock-recipe' or not unlock_type then
if Recipe(effect):valid() then
add_unlock(self, r_name)
end
end
elseif self:valid('recipe') then
unlock_type = 'unlock-recipe'
-- Convert to array and return first valid tech
local techs = type(effect) == 'string' and {effect} or effect
for _, name in pairs(techs) do
local tech = Technology(name)
if tech:valid('technology') then
self:set_enabled(false)
add_unlock(tech, self.name)
break
end
end
end
return self
end
function Technology:remove_effect(tech_name, unlock_type, name)
if self:valid('technology') then
return self, name, unlock_type -- TODO finish
elseif self:valid('recipe') then
if tech_name then
local tech = Technology(tech_name)
if tech:valid() then
for index, effect in pairs(tech.effects or {}) do
if effect.type == 'unlock-recipe' and effect.recipe == self.name then
table.remove(tech.effects, index)
end
end
end
else
for _, tech in pairs(data.raw['technology']) do
for index, effect in pairs(tech.effects or {}) do
if effect.type == 'unlock-recipe' and effect.recipe == self.name then
table.remove(tech.effects, index)
end
end
end
end
end
return self
end
function Technology:add_pack(new_pack, count)
if self:valid('technology') then
local Item = require('stdlib/data/item')
if self.table(new_pack) then
count = new_pack[2] or 1
new_pack = new_pack[1]
elseif self.string(new_pack) then
count = count or 1
else
error('new_pack must be a table or string')
end
if Item(new_pack):valid() then
self.unit.ingredients = self.unit.ingredients or {}
local ing = self.unit.ingredients
ing[#ing + 1] = {new_pack, count}
end
end
return self
end
function Technology:remove_pack(pack)
if self:valid('technology') then
local ing = self.unit.ingredients
if ing then
for i = #ing, 1, -1 do
if ing[i][1] == pack then
ing[i] = nil
break
end
end
end
end
return self
end
function Technology:replace_pack(old_pack, new_pack, count)
if self:valid('technology') then
local ing = self.unit.ingredients
if ing then
for i = #ing, 1, -1 do
if ing[i][1] == old_pack then
ing[i][1] = new_pack
ing[i][2] = count or ing[i][2] or 1
break
end
end
end
end
return self
end
function Technology:add_prereq(tech_name)
if self:valid('technology') and Technology(tech_name):valid() then
self.prerequisites = self.prerequisites or {}
local pre = self.prerequisites
for _, existing in pairs(pre) do
if existing == tech_name then
return self
end
end
pre[#pre + 1] = tech_name
end
return self
end
function Technology:remove_prereq(tech_name)
if self:valid('technology') then
local pre = self.prerequisites or {}
for i = #pre, 1, -1 do
if pre[i] == tech_name then
table.remove(pre, i)
end
end
if #pre == 0 then
self.prerequisites = nil
end
end
return self
end
Technology._mt = {
__index = Technology,
__call = Technology._caller,
__tostring = Technology.tostring
}
return Technology
|
--- Technology
-- @classmod Technology
local Technology = {
_class = 'technology'
}
setmetatable(Technology, require('stdlib/data/data'))
local Is = require('stdlib/utils/is')
function Technology:_caller(tech)
return self:get(tech, 'technology')
end
--[[
type = "technology",
name = "military",
icon = "__base__/graphics/technology/military.png",
effects =
{
{
type = "unlock-recipe",
recipe = "submachine-gun"
},
{
type = "unlock-recipe",
recipe = "shotgun"
},
{
type = "unlock-recipe",
recipe = "shotgun-shell"
}
},
unit =
{
count = 10,
ingredients = {{"science-pack-1", 1}},
time = 15
},
order = "e-a-a"
--]]
-- local function create_technology_prototype(name)
-- local new = {
-- type = type,
-- name = name,
-- }
-- data:extend{new}
-- return true
-- end
function Technology:add_effect(effect, unlock_type)
Is.Assert(effect)
--todo fix for non recipe types
local add_unlock =
function(technology, name)
local effects = technology.effects
effects[#effects + 1] = {
type = unlock_type,
recipe = name
}
end
if self:valid('technology') then
local Recipe = require('stdlib/data/recipe')
unlock_type = (not unlock_type and 'unlock-recipe') or unlock_type
local r_name = type(effect) == 'table' and effect.name or effect
if unlock_type == 'unlock-recipe' or not unlock_type then
if Recipe(effect):valid() then
add_unlock(self, r_name)
end
end
elseif self:valid('recipe') then
unlock_type = 'unlock-recipe'
-- Convert to array and return first valid tech
local techs = type(effect) == 'string' and {effect} or effect
for _, name in pairs(techs) do
local tech = Technology(name)
if tech:valid('technology') then
self:set_enabled(false)
add_unlock(tech, self.name)
break
end
end
end
return self
end
function Technology:remove_effect(tech_name, unlock_type, name)
if self:valid('technology') then
return self, name, unlock_type -- TODO finish
elseif self:valid('recipe') then
if tech_name then
local tech = Technology(tech_name)
if tech:valid() then
for index, effect in pairs(tech.effects or {}) do
if effect.type == 'unlock-recipe' and effect.recipe == self.name then
table.remove(tech.effects, index)
end
end
end
else
for _, tech in pairs(data.raw['technology']) do
for index, effect in pairs(tech.effects or {}) do
if effect.type == 'unlock-recipe' and effect.recipe == self.name then
table.remove(tech.effects, index)
end
end
end
end
end
return self
end
function Technology:add_pack(new_pack, count)
if self:valid('technology') then
local Item = require('stdlib/data/item')
if self.table(new_pack) then
count = new_pack[2] or 1
new_pack = new_pack[1]
elseif self.string(new_pack) then
count = count or 1
else
error('new_pack must be a table or string')
end
if Item(new_pack):valid() then
self.unit.ingredients = self.unit.ingredients or {}
local ing = self.unit.ingredients
ing[#ing + 1] = {new_pack, count}
end
end
return self
end
function Technology:remove_pack(pack)
if self:valid('technology') then
local ings = self.unit.ingredients
for i, ing in pairs(ings or {}) do
if ing[1] == pack then
table.remove(ings, i)
break
end
end
end
return self
end
function Technology:replace_pack(old_pack, new_pack, count)
if self:valid('technology') then
local ings = self.unit.ingredients
for i, ing in pairs(ings or {}) do
if ing[1] == old_pack then
ing[1] = new_pack
ing[2] = count or ing[2] or 1
break
end
end
end
return self
end
function Technology:add_prereq(tech_name)
if self:valid('technology') and Technology(tech_name):valid() then
self.prerequisites = self.prerequisites or {}
local pre = self.prerequisites
for _, existing in pairs(pre) do
if existing == tech_name then
return self
end
end
pre[#pre + 1] = tech_name
end
return self
end
function Technology:remove_prereq(tech_name)
if self:valid('technology') then
local pre = self.prerequisites or {}
for i = #pre, 1, -1 do
if pre[i] == tech_name then
table.remove(pre, i)
end
end
if #pre == 0 then
self.prerequisites = nil
end
end
return self
end
Technology._mt = {
__index = Technology,
__call = Technology._caller,
__tostring = Technology.tostring
}
return Technology
|
Fix array holes in Technology
|
Fix array holes in Technology
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
a5129ef291c28fb0dc1414f551ce7a2524a58e52
|
resources/prosody-plugins/mod_muc_allowners.lua
|
resources/prosody-plugins/mod_muc_allowners.lua
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local st = require "util.stanza";
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local get_room_from_jid = util.get_room_from_jid;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local disable_revoke_owners;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
disable_revoke_owners = module:get_option_boolean("allowners_disable_revoke_owners", false);
end
load_config();
local function is_admin(_jid)
return um_is_admin(_jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain][email protected]
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s',
room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s',
subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil
or not stanza.attr
or not stanza.attr.to
or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
-- filters any attempt to revoke owner rights on non moderated rooms
function filter_admin_set_query(event)
local origin, stanza = event.origin, event.stanza;
local room_jid = jid_bare(stanza.attr.to);
local room = get_room_from_jid(room_jid);
local item = stanza.tags[1].tags[1];
local _aff = item.attr.affiliation;
-- if it is a moderated room we skip it
if is_moderated(room.jid) then
return nil;
end
-- any revoking is disabled
if _aff ~= 'owner' then
origin.send(st.error_reply(stanza, "auth", "forbidden"));
return true;
end
end
if not disable_revoke_owners then
-- default prosody priority for handling these is -2
module:hook("iq-set/bare/http://jabber.org/protocol/muc#admin:query", filter_admin_set_query, 5);
module:hook("iq-set/host/http://jabber.org/protocol/muc#admin:query", filter_admin_set_query, 5);
end
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local st = require "util.stanza";
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local get_room_from_jid = util.get_room_from_jid;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local disable_revoke_owners;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
disable_revoke_owners = module:get_option_boolean("allowners_disable_revoke_owners", false);
end
load_config();
local function is_admin(_jid)
return um_is_admin(_jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain][email protected]
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s',
room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s',
subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil
or not stanza.attr
or not stanza.attr.to
or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
-- filters any attempt to revoke owner rights on non moderated rooms
function filter_admin_set_query(event)
local origin, stanza = event.origin, event.stanza;
local room_jid = jid_bare(stanza.attr.to);
local room = get_room_from_jid(room_jid);
local item = stanza.tags[1].tags[1];
local _aff = item.attr.affiliation;
-- if it is a moderated room we skip it
if is_moderated(room.jid) then
return nil;
end
-- any revoking is disabled, everyone should be owners
if _aff == 'none' or _aff == 'outcast' or _aff == 'member' then
origin.send(st.error_reply(stanza, "auth", "forbidden"));
return true;
end
end
if not disable_revoke_owners then
-- default prosody priority for handling these is -2
module:hook("iq-set/bare/http://jabber.org/protocol/muc#admin:query", filter_admin_set_query, 5);
module:hook("iq-set/host/http://jabber.org/protocol/muc#admin:query", filter_admin_set_query, 5);
end
|
fix: Fixes kick when allowners is enabled.
|
fix: Fixes kick when allowners is enabled.
Broken after ab18fa7 which disallows the kick as the affiliation attribute is missing in kick iq that is sent.
|
Lua
|
apache-2.0
|
gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet
|
bb1da653a1df8481989e554e135ff5edfc6d2fec
|
src_trunk/resources/admin-system/teleport.lua
|
src_trunk/resources/admin-system/teleport.lua
|
function AdminLoungeTeleport(sourcePlayer)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
setElementPosition ( sourcePlayer, 275.761475, -2052.245605, 3085.291962 )
triggerClientEvent(sourcePlayer, "usedElevator", sourcePlayer)
setPedFrozen(sourcePlayer, true)
setPedGravity(sourcePlayer, 0)
end
end
addCommandHandler("adminlounge", AdminLoungeTeleport)
function setX(sourcePlayer, commandName, newX)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if not (newX) then
outputChatBox("SYNTAX: /" .. commandName .. " [x coordinate]", thePlayer, 255, 194, 14)
else
x, y, z = getElementPosition(sourcePlayer)
setElementPosition(sourcePlayer, newX, y, z)
x, y, z = nil
end
end
end
addCommandHandler("setx", setX)
function setY(sourcePlayer, commandName, newY)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if not (newY) then
outputChatBox("SYNTAX: /" .. commandName .. " [y coordinate]", thePlayer, 255, 194, 14)
else
x, y, z = getElementPosition(sourcePlayer)
setElementPosition(sourcePlayer, x, newY, z)
x, y, z = nil
end
end
end
addCommandHandler("sety", setY)
function setZ(sourcePlayer, commandName, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if not (newZ) then
outputChatBox("SYNTAX: /" .. commandName .. " [z coordinate]", thePlayer, 255, 194, 14)
else
x, y, z = getElementPosition(sourcePlayer)
setElementPosition(sourcePlayer, x, y, newZ)
x, y, z = nil
end
end
end
addCommandHandler("setz", setZ)
function setXYZ(sourcePlayer, commandName, newX, newY, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newX) and (newY) and (newZ) then
setElementPosition(sourcePlayer, newX, newY, newZ)
else
outputChatBox("SYNTAX: /" .. commandName .. " [x coordnate] [y coordinate] [z coordinate]", thePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setxyz", setXYZ)
function setXY(sourcePlayer, commandName, newX, newY)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newX) and (newY) then
setElementPosition(sourcePlayer, newX, newY)
else
outputChatBox("SYNTAX: /" .. commandName .. " [x coordnate] [y coordinate]", thePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setxy", setXY)
function setXZ(sourcePlayer, commandName, newX, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newX) and (newZ) then
setElementPosition(sourcePlayer, newX, newZ)
else
outputChatBox("SYNTAX: /" .. commandName .. " [x coordnate] [z coordinate]", thePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setxz", setXZ)
function setYZ(sourcePlayer, commandName, newY, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newY) and (newZ) then
setElementPosition(sourcePlayer, newY, newZ)
else
outputChatBox("SYNTAX: /" .. commandName .. " [y coordinate] [z coordinate]", thePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setyz", setYZ)
|
function AdminLoungeTeleport(sourcePlayer)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
setElementPosition ( sourcePlayer, 275.761475, -2052.245605, 3085.291962 )
triggerClientEvent(sourcePlayer, "usedElevator", sourcePlayer)
setPedFrozen(sourcePlayer, true)
setPedGravity(sourcePlayer, 0)
end
end
addCommandHandler("adminlounge", AdminLoungeTeleport)
function setX(sourcePlayer, commandName, newX)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if not (newX) then
outputChatBox("SYNTAX: /" .. commandName .. " [x coordinate]", sourcePlayer, 255, 194, 14)
else
x, y, z = getElementPosition(sourcePlayer)
setElementPosition(sourcePlayer, newX, y, z)
x, y, z = nil
end
end
end
addCommandHandler("setx", setX)
function setY(sourcePlayer, commandName, newY)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if not (newY) then
outputChatBox("SYNTAX: /" .. commandName .. " [y coordinate]", sourcePlayer, 255, 194, 14)
else
x, y, z = getElementPosition(sourcePlayer)
setElementPosition(sourcePlayer, x, newY, z)
x, y, z = nil
end
end
end
addCommandHandler("sety", setY)
function setZ(sourcePlayer, commandName, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if not (newZ) then
outputChatBox("SYNTAX: /" .. commandName .. " [z coordinate]", sourcePlayer, 255, 194, 14)
else
x, y, z = getElementPosition(sourcePlayer)
setElementPosition(sourcePlayer, x, y, newZ)
x, y, z = nil
end
end
end
addCommandHandler("setz", setZ)
function setXYZ(sourcePlayer, commandName, newX, newY, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newX) and (newY) and (newZ) then
setElementPosition(sourcePlayer, newX, newY, newZ)
else
outputChatBox("SYNTAX: /" .. commandName .. " [x coordnate] [y coordinate] [z coordinate]", sourcePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setxyz", setXYZ)
function setXY(sourcePlayer, commandName, newX, newY)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newX) and (newY) then
setElementPosition(sourcePlayer, newX, newY)
else
outputChatBox("SYNTAX: /" .. commandName .. " [x coordnate] [y coordinate]", sourcePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setxy", setXY)
function setXZ(sourcePlayer, commandName, newX, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newX) and (newZ) then
setElementPosition(sourcePlayer, newX, newZ)
else
outputChatBox("SYNTAX: /" .. commandName .. " [x coordnate] [z coordinate]", sourcePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setxz", setXZ)
function setYZ(sourcePlayer, commandName, newY, newZ)
if (exports.global:isPlayerAdmin(sourcePlayer)) then
if (newY) and (newZ) then
setElementPosition(sourcePlayer, newY, newZ)
else
outputChatBox("SYNTAX: /" .. commandName .. " [y coordinate] [z coordinate]", sourcePlayer, 255, 194, 14)
end
end
end
addCommandHandler("setyz", setYZ)
|
Fixed globalm essage
|
Fixed globalm essage
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@936 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
98560f4fbc5be2ad47ffadb318b9e329c0a03c4b
|
msgpack.lua
|
msgpack.lua
|
exports.name = "creationix/msgpack"
exports.version = "1.0.0"
exports.description = "A pure lua implementation of the msgpack format."
exports.homepage = "https://github.com/creationix/msgpack-lua"
exports.keywords = {"codec", "msgpack"}
local floor = math.floor
local ceil = math.ceil
local char = string.char
local byte = string.byte
local bit = require('bit')
local rshift = bit.rshift
local lshift = bit.lshift
local band = bit.band
local bor = bit.bor
local concat = table.concat
local function uint16(num)
return char(rshift(num, 8))
.. char(band(num, 0xff))
end
local function uint32(num)
return char(rshift(num, 24))
.. char(band(rshift(num, 16), 0xff))
.. char(band(rshift(num, 8), 0xff))
.. char(band(num, 0xff))
end
local function uint64(num)
return uint32(floor(num / 0x100000000))
.. uint32(num % 0x100000000)
end
local function encode(value)
local t = type(value)
if t == "nil" then
return "\xc0"
elseif t == "boolean" then
return value and "\xc3" or "\xc2"
elseif t == "number" then
if floor(value) == value then
if value >= 0 then
if value < 0x80 then
return char(value)
elseif value < 0x100 then
return "\xcc" .. char(value)
elseif value < 0x10000 then
return "\xcd" .. uint16(value)
elseif value < 0x100000000 then
return "\xce" .. uint32(value)
else
return "\xcf" .. uint64(value)
end
else
if value >= -0x20 then
return char(0x100 + value)
elseif value >= -0x80 then
return "\xd0" .. char(0x100 + value)
elseif value >= -0x8000 then
return "\xd1" .. uint16(0x10000 + value)
elseif value >= -0x80000000 then
return "\xd2" .. uint32(0x100000000 + value)
elseif value >= -0x100000000 then
return "\xd3\xff\xff\xff\xff"
.. uint32(0x100000000 + value)
else
local high = ceil(value / 0x100000000)
local low = value - high * 0x100000000
if low == 0 then
high = 0x100000000 + high
else
high = 0xffffffff + high
low = 0x100000000 + low
end
return "\xd3" .. uint32(high) .. uint32(low)
end
end
else
error("TODO: floating point numbers")
end
elseif t == "string" then
local l = #value
if l < 0x20 then
return char(bor(0xa0, l)) .. value
elseif l < 0x100 then
return "\xd9" .. char(l) .. value
elseif l < 0x10000 then
return "\xda" .. uint16(l) .. value
elseif l < 0x100000000 then
return "\xdb" .. uint32(l) .. value
else
error("String too long: " .. l .. " bytes")
end
elseif t == "table" then
local isMap = false
local index = 1
for key in pairs(value) do
if type(key) ~= "number" or key ~= index then
isMap = true
break
else
index = index + 1
end
end
if isMap then
local count = 0
local parts = {}
for key, part in pairs(value) do
parts[#parts + 1] = encode(key)
parts[#parts + 1] = encode(part)
count = count + 1
end
value = concat(parts)
if count < 16 then
return char(bor(0x80, count)) .. value
elseif count < 0x10000 then
return "\xde" .. uint16(count) .. value
elseif count < 0x100000000 then
return "\xdf" .. uint32(count) .. value
else
error("map too big: " .. count)
end
else
local parts = {}
local l = #value
for i = 1, l do
parts[i] = encode(value[i])
end
value = concat(parts)
if l < 0x10 then
return char(bor(0x90, l)) .. value
elseif l < 0x10000 then
return "\xdc" .. uint16(l) .. value
elseif l < 0x100000000 then
return "\xdd" .. uint32(l) .. value
else
error("Array too long: " .. l .. "items")
end
end
else
error("Unknown type: " .. t)
end
end
exports.encode = encode
local function decode(data)
local c = byte(data, 1)
if c < 0x80 then
return c
elseif c >= 0xe0 then
return c - 0x100
elseif c < 0x90 then
error("TODO: fixmap")
elseif c < 0xa0 then
error("TODO: fixarray")
elseif c < 0xc0 then
error("TODO: fixstring")
elseif c == 0xc0 then
return nil
elseif c == 0xc1 then
return nil, "Invalid type 0xc1"
elseif c == 0xc2 then
return false
elseif c == 0xc3 then
return true
elseif c == 0xcc then
return byte(data, 2)
elseif c == 0xcd then
return bor(
lshift(byte(data, 2), 8),
byte(data, 3))
elseif c == 0xce then
return bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5)) % 0x100000000
elseif c == 0xcf then
return (bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5)) % 0x100000000) * 0x100000000
+ (bor(
lshift(byte(data, 6), 24),
lshift(byte(data, 7), 16),
lshift(byte(data, 8), 8),
byte(data, 9)) % 0x100000000)
elseif c == 0xd0 then
local num = byte(data, 2)
return num >= 0x80 and (num - 0x100) or num
elseif c == 0xd1 then
local num = bor(
lshift(byte(data, 2), 8),
byte(data, 3))
return num >= 0x8000 and (num - 0x10000) or num
elseif c == 0xd2 then
return bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5))
elseif c == 0xd3 then
local high = 0x100000000 - (
byte(data, 2) * 0x1000000 +
byte(data, 3) * 0x10000 +
byte(data, 4) * 0x100 +
byte(data, 5))
local low = 0x100000000 - (
byte(data, 6) * 0x1000000 +
byte(data, 7) * 0x10000 +
byte(data, 8) * 0x100 +
byte(data, 9))
p(high, low)
-- if low == 0xffffffff then
return high * 0x100000000 + low
-- else
-- return (high - 1) * 0x100000000 + low
-- end
else
error("TODO: more types: " .. string.format("%02x", c))
end
end
exports.decode = decode
|
exports.name = "creationix/msgpack"
exports.version = "1.0.0"
exports.description = "A pure lua implementation of the msgpack format."
exports.homepage = "https://github.com/creationix/msgpack-lua"
exports.keywords = {"codec", "msgpack"}
local floor = math.floor
local ceil = math.ceil
local char = string.char
local byte = string.byte
local bit = require('bit')
local rshift = bit.rshift
local lshift = bit.lshift
local band = bit.band
local bor = bit.bor
local concat = table.concat
local function uint16(num)
return char(rshift(num, 8))
.. char(band(num, 0xff))
end
local function uint32(num)
return char(rshift(num, 24))
.. char(band(rshift(num, 16), 0xff))
.. char(band(rshift(num, 8), 0xff))
.. char(band(num, 0xff))
end
local function uint64(num)
return uint32(floor(num / 0x100000000))
.. uint32(num % 0x100000000)
end
local function encode(value)
local t = type(value)
if t == "nil" then
return "\xc0"
elseif t == "boolean" then
return value and "\xc3" or "\xc2"
elseif t == "number" then
if floor(value) == value then
if value >= 0 then
if value < 0x80 then
return char(value)
elseif value < 0x100 then
return "\xcc" .. char(value)
elseif value < 0x10000 then
return "\xcd" .. uint16(value)
elseif value < 0x100000000 then
return "\xce" .. uint32(value)
else
return "\xcf" .. uint64(value)
end
else
if value >= -0x20 then
return char(0x100 + value)
elseif value >= -0x80 then
return "\xd0" .. char(0x100 + value)
elseif value >= -0x8000 then
return "\xd1" .. uint16(0x10000 + value)
elseif value >= -0x80000000 then
return "\xd2" .. uint32(0x100000000 + value)
elseif value >= -0x100000000 then
return "\xd3\xff\xff\xff\xff"
.. uint32(0x100000000 + value)
else
local high = ceil(value / 0x100000000)
local low = value - high * 0x100000000
if low == 0 then
high = 0x100000000 + high
else
high = 0xffffffff + high
low = 0x100000000 + low
end
return "\xd3" .. uint32(high) .. uint32(low)
end
end
else
error("TODO: floating point numbers")
end
elseif t == "string" then
local l = #value
if l < 0x20 then
return char(bor(0xa0, l)) .. value
elseif l < 0x100 then
return "\xd9" .. char(l) .. value
elseif l < 0x10000 then
return "\xda" .. uint16(l) .. value
elseif l < 0x100000000 then
return "\xdb" .. uint32(l) .. value
else
error("String too long: " .. l .. " bytes")
end
elseif t == "table" then
local isMap = false
local index = 1
for key in pairs(value) do
if type(key) ~= "number" or key ~= index then
isMap = true
break
else
index = index + 1
end
end
if isMap then
local count = 0
local parts = {}
for key, part in pairs(value) do
parts[#parts + 1] = encode(key)
parts[#parts + 1] = encode(part)
count = count + 1
end
value = concat(parts)
if count < 16 then
return char(bor(0x80, count)) .. value
elseif count < 0x10000 then
return "\xde" .. uint16(count) .. value
elseif count < 0x100000000 then
return "\xdf" .. uint32(count) .. value
else
error("map too big: " .. count)
end
else
local parts = {}
local l = #value
for i = 1, l do
parts[i] = encode(value[i])
end
value = concat(parts)
if l < 0x10 then
return char(bor(0x90, l)) .. value
elseif l < 0x10000 then
return "\xdc" .. uint16(l) .. value
elseif l < 0x100000000 then
return "\xdd" .. uint32(l) .. value
else
error("Array too long: " .. l .. "items")
end
end
else
error("Unknown type: " .. t)
end
end
exports.encode = encode
local function decode(data)
local c = byte(data, 1)
if c < 0x80 then
return c
elseif c >= 0xe0 then
return c - 0x100
elseif c < 0x90 then
error("TODO: fixmap")
elseif c < 0xa0 then
error("TODO: fixarray")
elseif c < 0xc0 then
error("TODO: fixstring")
elseif c == 0xc0 then
return nil
elseif c == 0xc1 then
return nil, "Invalid type 0xc1"
elseif c == 0xc2 then
return false
elseif c == 0xc3 then
return true
elseif c == 0xcc then
return byte(data, 2)
elseif c == 0xcd then
return bor(
lshift(byte(data, 2), 8),
byte(data, 3))
elseif c == 0xce then
return bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5)) % 0x100000000
elseif c == 0xcf then
return (bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5)) % 0x100000000) * 0x100000000
+ (bor(
lshift(byte(data, 6), 24),
lshift(byte(data, 7), 16),
lshift(byte(data, 8), 8),
byte(data, 9)) % 0x100000000)
elseif c == 0xd0 then
local num = byte(data, 2)
return num >= 0x80 and (num - 0x100) or num
elseif c == 0xd1 then
local num = bor(
lshift(byte(data, 2), 8),
byte(data, 3))
return num >= 0x8000 and (num - 0x10000) or num
elseif c == 0xd2 then
return bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5))
elseif c == 0xd3 then
local high = bor(
lshift(byte(data, 2), 24),
lshift(byte(data, 3), 16),
lshift(byte(data, 4), 8),
byte(data, 5))
local low = bor(
lshift(byte(data, 6), 24),
lshift(byte(data, 7), 16),
lshift(byte(data, 8), 8),
byte(data, 9))
if low < 0 then
high = high + 1
end
return high * 0x100000000 + low
else
error("TODO: more types: " .. string.format("%02x", c))
end
end
exports.decode = decode
|
Fix int64 encoding
|
Fix int64 encoding
|
Lua
|
mit
|
super-agent/msgpack
|
23bbaa922173a75f6d49da170b91a37cfd247ac9
|
lib/app.lua
|
lib/app.lua
|
local getTimer = system.getTimer
local pairs = _G.pairs
local M = {}
M.sound = true
M.music = true
M.deviceID = system.getInfo('deviceID')
if system.getInfo('environment') ~= 'simulator' then
io.output():setvbuf('no')
else
M.isSimulator = true
end
local platform = system.getInfo('platformName')
if platform == 'Android' then
M.isAndroid = true
elseif platform == 'iPhone OS' then
M.isiOS = true
end
local locals = {
_W = display.contentWidth,
_H = display.contentHeight,
_T = display.screenOriginY,
_B = display.viewableContentHeight - display.screenOriginY,
_L = display.screenOriginX,
_R = display.viewableContentWidth - display.screenOriginX,
_CX = math.floor(display.contentWidth * 0.5),
_CY = math.floor(display.contentHeight * 0.5),
mMax = math.max,
mMin = math.min,
mFloor = math.floor,
tInsert = table.insert,
mCeil = math.ceil,
mFloor = math.floor,
mAbs = math.abs,
mAtan2 = math.atan2,
mSin = math.sin,
mCos = math.cos,
mPi = math.pi,
mSqrt = math.sqrt,
mExp = math.exp,
mRandom = math.random,
tInsert = table.insert,
tRemove = table.remove,
tForeach = table.foreach,
tShuffle = table.shuffle,
sSub = string.sub,
sLower = string.lower}
locals._SW = locals._R - locals._L
locals._SH = locals._B - locals._T
function M.setLocals()
local i = 1
repeat
local k, v = debug.getlocal(2, i)
if k and v == nil then
if locals[k] ~= nil then
debug.setlocal(2, i, locals[k])
else
--error('No value for a local variable: ' .. k, 2)
end
end
i = i + 1
until not k
end
local colors = {}
colors['white'] = {1, 1, 1}
colors['grey'] = {0.6, 0.6, 0.6}
colors['black'] = {0, 0, 0}
colors['red'] = {1, 0, 0}
colors['green'] = {0, 1, 0}
colors['blue'] = {0, 0, 1}
colors['yellow'] = {1, 1, 0}
colors['cyan'] = {0, 1, 1}
colors['magenta'] = {1, 0, 1}
colors['orange'] = {1, 0.75, 0}
colors['dark_green'] = {0, 0.5, 0}
colors['res_green'] = {0, 0.3, 0}
colors['res_red'] = {0.7, 0, 0}
local dir = 'scene/game/sfx/'
local sounds = {
button = dir .. 'select.wav',
}
local loadedSounds = {}
local referencePoints = {
TopLeft = {0, 0},
TopRight = {1, 0},
TopCenter = {0.5, 0},
BottomLeft = {0, 1},
BottomRight = {1, 1},
BottomCenter = {0.5, 1},
CenterLeft = {0, 0.5},
CenterRight = {1, 0.5},
Center = {0.5, 0.5}
}
-- ustawianie punktu anchor
function M.setRP(object, rp)
local anchor = referencePoints[rp]
if anchor then
object.anchorX, object.anchorY = anchor[1], anchor[2]
else
error('No such reference point: ' .. tostring(rp), 2)
end
end
-- ustawianie koloru wypełnienia
function M.setFillColor(object, color)
local rgb = colors[color]
if rgb then
object:setFillColor(unpack(rgb))
else
error('No such color: ' .. tostring(color), 2)
end
end
-- ustawianie koloru konturu
function M.setStrokeColor(object, color)
local rgb = colors[color]
if rgb then
object:setStrokeColor(unpack(rgb))
else
error('No such color: ' .. tostring(color), 2)
end
end
-- Funkcje od ładowania i odtwarzania dzwieków
local function loadSound( name )
if ( not loadedSounds[name] ) then
print( 'loadSound= ', name, sounds[name] )
loadedSounds[name] = audio.loadSound( sounds[name] )
end
return loadedSounds[name]
end
function M.loadSounds()
for name in pairs(sounds) do loadSound( name ); print(name) end
end
function M.playSound( name )
print( M.sound, loadedSounds[name] )
if M.sound then audio.play( loadedSounds[name] ) end
end
function M.disposeSounds()
audio.stop()
for sound in pairs(loadedSounds) do
audio.dispose( sound )
loadedSounds[sound] = nil
end
end
-- Funkcję do manipulacji lokalnymi zdarzeniami typu enterFrame
function M.nextFrame(f)
timer.performWithDelay(1, f)
end
function M.enterFrame()
for i = 1, #M.enterFrameFunctions do
M.enterFrameFunctions[i]()
end
end
function M.eachFrame(f)
if not M.enterFrameFunctions then
M.enterFrameFunctions = {}
Runtime:addEventListener('enterFrame', M.enterFrame)
end
table.insert(M.enterFrameFunctions, f)
return f
end
function M.eachFrameRemove(f)
if not f or not M.enterFrameFunctions then return end
local ind = table.indexOf(M.enterFrameFunctions, f)
if ind then
table.remove(M.enterFrameFunctions, ind)
if #M.enterFrameFunctions == 0 then
Runtime:removeEventListener('enterFrame', M.enterFrame)
M.enterFrameFunctions = nil
end
end
end
function M.extend(target, source)
for k, v in pairs(source) do
target[k] = v
end
end
function M.eachFrameRemoveAll()
Runtime:removeEventListener('enterFrame', M.enterFrame)
M.enterFrameFunctions = nil
end
-- Funkcję do manipulacji globalnymi zdarzeniami różnego typu
function M.addRuntimeEvents( events )
if not M.RtEventTable then
M.RtEventTable = { listeners={}, names={} }
end
for i=1, #events * 0.5 do
local name = events[ 2 * i - 1 ]
local listener = events[ 2 * i ]
Runtime:addEventListener( name, listener )
table.insert( M.RtEventTable.listeners, listener )
table.insert( M.RtEventTable.names, name )
end
end
-- usunięcie wybranych zdarzeń
function M.removeRuntimeEvents( events )
for i=1, #events * 0.5 do
local name = events[ 2 * i - 1 ]
local listener = events[ 2 * i ]
if not listener or not M.RtEventTable then break end
local ind = table.indexOf( M.RtEventTable.listeners, listener )
if ind then
table.remove( M.RtEventTable.listeners, ind )
table.remove( M.RtEventTable.names, ind )
Runtime:removeEventListener( name, listener )
end
end
end
-- usunięcie wszystkich zdarzeń
function M.removeAllRuntimeEvents()
if ( M.RtEventTable and M.RtEventTable.listeners ) then
for i=1, #M.RtEventTable.listeners do
local name = M.RtEventTable.names[ i ]
local listener = M.RtEventTable.listeners[ i ]
Runtime:removeEventListener( name, listener )
end
M.RtEventTable.listeners = nil
M.RtEventTable.names = nil
M.RtEventTable = nil
end
end
-- Generowanie dowolnych zdarzeń
--
-- dodanie zdarzenia
function M.listen( name, listener )
M.addRtEvents( { name, listener } )
end
-- usunięcie zdarzenia
function M.ignore( name, listener )
M.removeRtEvents( { name, listener } )
end
-- wygenerowanie zdarzenia
function M.post( name, params )
local params = params or {}
local event = { name = name }
for k,v in pairs( params ) do
event[k] = v
end
if ( not event.time ) then event.time = getTimer() end
Runtime:dispatchEvent( event )
end
return M
|
local getTimer = system.getTimer
local pairs = _G.pairs
local M = {}
M.sound = true
M.music = true
M.deviceID = system.getInfo('deviceID')
if system.getInfo('environment') ~= 'simulator' then
io.output():setvbuf('no')
else
M.isSimulator = true
end
local platform = system.getInfo('platformName')
if platform == 'Android' then
M.isAndroid = true
elseif platform == 'iPhone OS' then
M.isiOS = true
end
local locals = {
_W = display.contentWidth,
_H = display.contentHeight,
_T = display.screenOriginY,
_B = display.viewableContentHeight - display.screenOriginY,
_L = display.screenOriginX,
_R = display.viewableContentWidth - display.screenOriginX,
_CX = math.floor(display.contentWidth * 0.5),
_CY = math.floor(display.contentHeight * 0.5),
mMax = math.max,
mMin = math.min,
mFloor = math.floor,
tInsert = table.insert,
mCeil = math.ceil,
mFloor = math.floor,
mAbs = math.abs,
mAtan2 = math.atan2,
mSin = math.sin,
mCos = math.cos,
mPi = math.pi,
mSqrt = math.sqrt,
mExp = math.exp,
mRandom = math.random,
tInsert = table.insert,
tRemove = table.remove,
tForeach = table.foreach,
tShuffle = table.shuffle,
sSub = string.sub,
sLower = string.lower}
locals._SW = locals._R - locals._L
locals._SH = locals._B - locals._T
function M.setLocals()
local i = 1
repeat
local k, v = debug.getlocal(2, i)
if k and v == nil then
if locals[k] ~= nil then
debug.setlocal(2, i, locals[k])
else
--error('No value for a local variable: ' .. k, 2)
end
end
i = i + 1
until not k
end
local colors = {}
colors['white'] = {1, 1, 1}
colors['grey'] = {0.6, 0.6, 0.6}
colors['black'] = {0, 0, 0}
colors['red'] = {1, 0, 0}
colors['green'] = {0, 1, 0}
colors['blue'] = {0, 0, 1}
colors['yellow'] = {1, 1, 0}
colors['cyan'] = {0, 1, 1}
colors['magenta'] = {1, 0, 1}
colors['orange'] = {1, 0.75, 0}
colors['dark_green'] = {0, 0.5, 0}
colors['res_green'] = {0, 0.3, 0}
colors['res_red'] = {0.7, 0, 0}
local dir = 'scene/game/sfx/'
local sounds = {
button = dir .. 'select.wav',
}
local loadedSounds = {}
local referencePoints = {
TopLeft = {0, 0},
TopRight = {1, 0},
TopCenter = {0.5, 0},
BottomLeft = {0, 1},
BottomRight = {1, 1},
BottomCenter = {0.5, 1},
CenterLeft = {0, 0.5},
CenterRight = {1, 0.5},
Center = {0.5, 0.5}
}
-- ustawianie punktu anchor
function M.setRP(object, rp)
local anchor = referencePoints[rp]
if anchor then
object.anchorX, object.anchorY = anchor[1], anchor[2]
else
error('No such reference point: ' .. tostring(rp), 2)
end
end
-- ustawianie koloru wypełnienia
function M.setFillColor(object, color)
local rgb = colors[color]
if rgb then
object:setFillColor(unpack(rgb))
else
error('No such color: ' .. tostring(color), 2)
end
end
-- ustawianie koloru konturu
function M.setStrokeColor(object, color)
local rgb = colors[color]
if rgb then
object:setStrokeColor(unpack(rgb))
else
error('No such color: ' .. tostring(color), 2)
end
end
-- Funkcje od ładowania i odtwarzania dzwieków
local function loadSound( name )
if ( not loadedSounds[name] ) then
loadedSounds[name] = audio.loadSound( sounds[name] )
end
return loadedSounds[name]
end
function M.loadSounds()
for name in pairs(sounds) do loadSound( name ) end
end
function M.playSound( name )
if M.sound then audio.play( loadedSounds[name] or name ) end
end
function M.disposeSounds()
audio.stop()
for sound in pairs(loadedSounds) do
audio.dispose( sound )
loadedSounds[sound] = nil
end
end
-- Funkcję do manipulacji lokalnymi zdarzeniami typu enterFrame
function M.nextFrame(f)
timer.performWithDelay(1, f)
end
function M.enterFrame()
for i = 1, #M.enterFrameFunctions do
M.enterFrameFunctions[i]()
end
end
function M.eachFrame(f)
if not M.enterFrameFunctions then
M.enterFrameFunctions = {}
Runtime:addEventListener('enterFrame', M.enterFrame)
end
table.insert(M.enterFrameFunctions, f)
return f
end
function M.eachFrameRemove(f)
if not f or not M.enterFrameFunctions then return end
local ind = table.indexOf(M.enterFrameFunctions, f)
if ind then
table.remove(M.enterFrameFunctions, ind)
if #M.enterFrameFunctions == 0 then
Runtime:removeEventListener('enterFrame', M.enterFrame)
M.enterFrameFunctions = nil
end
end
end
function M.extend(target, source)
for k, v in pairs(source) do
target[k] = v
end
end
function M.eachFrameRemoveAll()
Runtime:removeEventListener('enterFrame', M.enterFrame)
M.enterFrameFunctions = nil
end
-- Funkcję do manipulacji globalnymi zdarzeniami różnego typu
function M.addRuntimeEvents( events )
if not M.RtEventTable then
M.RtEventTable = { listeners={}, names={} }
end
for i=1, #events * 0.5 do
local name = events[ 2 * i - 1 ]
local listener = events[ 2 * i ]
Runtime:addEventListener( name, listener )
table.insert( M.RtEventTable.listeners, listener )
table.insert( M.RtEventTable.names, name )
end
end
-- usunięcie wybranych zdarzeń
function M.removeRuntimeEvents( events )
for i=1, #events * 0.5 do
local name = events[ 2 * i - 1 ]
local listener = events[ 2 * i ]
if not listener or not M.RtEventTable then break end
local ind = table.indexOf( M.RtEventTable.listeners, listener )
if ind then
table.remove( M.RtEventTable.listeners, ind )
table.remove( M.RtEventTable.names, ind )
Runtime:removeEventListener( name, listener )
end
end
end
-- usunięcie wszystkich zdarzeń
function M.removeAllRuntimeEvents()
if ( M.RtEventTable and M.RtEventTable.listeners ) then
for i=1, #M.RtEventTable.listeners do
local name = M.RtEventTable.names[ i ]
local listener = M.RtEventTable.listeners[ i ]
Runtime:removeEventListener( name, listener )
end
M.RtEventTable.listeners = nil
M.RtEventTable.names = nil
M.RtEventTable = nil
end
end
-- Generowanie dowolnych zdarzeń
--
-- dodanie zdarzenia
function M.listen( name, listener )
M.addRtEvents( { name, listener } )
end
-- usunięcie zdarzenia
function M.ignore( name, listener )
M.removeRtEvents( { name, listener } )
end
-- wygenerowanie zdarzenia
function M.post( name, params )
local params = params or {}
local event = { name = name }
for k,v in pairs( params ) do
event[k] = v
end
if ( not event.time ) then event.time = getTimer() end
Runtime:dispatchEvent( event )
end
return M
|
Bug fix
|
Bug fix
|
Lua
|
mit
|
ldurniat/My-Pong-Game,ldurniat/The-Great-Pong
|
35e01a2f7e5ab7953d3edb386743c406fd2a2836
|
modules/admin-mini/luasrc/model/cbi/mini/system.lua
|
modules/admin-mini/luasrc/model/cbi/mini/system.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("system"), translate("a_s_desc"))
s = m:section(TypedSection, "system", "")
s.anonymous = true
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("system")).value = system
s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
s:option(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("system"), translate("a_s_desc"))
s = m:section(TypedSection, "system", "")
s.anonymous = true
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("system")).value = system
s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("mem_cached", "")),
100 * membuffers / memtotal,
tostring(translate("mem_buffered", "")),
100 * memfree / memtotal,
tostring(translate("mem_free", ""))
s:option(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
return m
|
modules/admin-mini: fix the same issue in admin-mini
|
modules/admin-mini: fix the same issue in admin-mini
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5149 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
53c89b38d5b41c199e1431184e96235566c6dcc4
|
xmake/rules/utils/merge_archive/xmake.lua
|
xmake/rules/utils/merge_archive/xmake.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: utils.merge.archive
rule("utils.merge.archive")
-- set extensions
set_extensions(".a", ".lib")
-- on build file
on_build_file(function (target, sourcefile_lib, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("core.tool.extractor")
import("core.project.target", {alias = "project_target"})
-- get object directory of the archive file
local objectdir = target:objectfile(sourcefile_lib) .. ".dir"
-- load dependent info
local dependfile = target:dependfile(objectdir)
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectdir)}) then
local objectfiles = os.files(path.join(objectdir, "**" .. project_target.filename("", "object")))
table.join2(target:objectfiles(), objectfiles)
return
end
-- trace progress info
cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress)
if option.get("verbose") then
cprint("${dim color.build.object}inserting.$(mode) %s", sourcefile_lib)
print("extracting %s to %s", sourcefile_lib, objectdir)
else
cprint("${color.build.object}inserting.$(mode) %s", sourcefile_lib)
end
-- flush io buffer to update progress info
io.flush()
-- extract the archive library
os.tryrm(objectdir)
extractor.extract(sourcefile_lib, objectdir)
-- add objectfiles
local objectfiles = os.files(path.join(objectdir, "**" .. project_target.filename("", "object")))
table.join2(target:objectfiles(), objectfiles)
-- update files to the dependent file
dependinfo.files = {}
table.insert(dependinfo.files, sourcefile_lib)
depend.save(dependinfo, dependfile)
end)
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: utils.merge.archive
rule("utils.merge.archive")
-- set extensions
set_extensions(".a", ".lib")
-- on build file
on_build_files(function (target, sourcebatch, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("core.tool.extractor")
import("core.project.target", {alias = "project_target"})
-- @note we cannot process archives in parallel because the current directory may be changed
for i = 1, #sourcebatch.sourcefiles do
-- get library source file
local sourcefile_lib = sourcebatch.sourcefiles[i]
-- get object directory of the archive file
local objectdir = target:objectfile(sourcefile_lib) .. ".dir"
-- load dependent info
local dependfile = target:dependfile(objectdir)
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectdir)}) then
local objectfiles = os.files(path.join(objectdir, "**" .. project_target.filename("", "object")))
table.join2(target:objectfiles(), objectfiles)
return
end
-- trace progress info
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if option.get("verbose") then
cprint(progress_prefix .. "${dim color.build.object}inserting.$(mode) %s", opt.progress, sourcefile_lib)
print("extracting %s to %s", sourcefile_lib, objectdir)
else
cprint(progress_prefix .. "${color.build.object}inserting.$(mode) %s", opt.progress, sourcefile_lib)
end
-- extract the archive library
os.tryrm(objectdir)
extractor.extract(sourcefile_lib, objectdir)
-- add objectfiles
local objectfiles = os.files(path.join(objectdir, "**" .. project_target.filename("", "object")))
table.join2(target:objectfiles(), objectfiles)
-- update files to the dependent file
dependinfo.files = {}
table.insert(dependinfo.files, sourcefile_lib)
depend.save(dependinfo, dependfile)
end
end)
|
fix merge archive
|
fix merge archive
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
474102af9d5fc2f6111eee141e369930fc96641d
|
premake.lua
|
premake.lua
|
Workspace = "workspace/".._ACTION
-- Compilers
PlatformMSVC64 = "MSVC 64"
PlatformMSVC32 = "MSVC 32"
PlatformLLVM64 = "LLVM 64"
PlatformLLVM32 = "LLVM 32"
PlatformOSX64 = "OSX 64"
PlatformLinux64 = "Linux 64"
-- Directories
srcDir = "src"
workspace "hlsl++"
configurations { "Debug", "Release" }
location (Workspace)
includedirs
{
srcDir,
}
if(_ACTION == "xcode4") then
platforms { PlatformOSX64 }
toolset("clang")
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1 -std=c++11" }
linkoptions { "-stdlib=libc++" }
else if(_ACTION == "gmake") then
platforms { PlatformLinux64 }
toolset("gcc")
architecture("x64")
else
platforms { PlatformMSVC64, PlatformMSVC32, PlatformLLVM64, PlatformLLVM32 }
filter { "platforms:"..PlatformMSVC64 }
toolset("msc")
architecture("x64")
filter { "platforms:"..PlatformMSVC32 }
toolset("msc")
filter { "platforms:"..PlatformLLVM64 }
toolset("msc-llvm-vs2014")
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformLLVM32 }
toolset("msc-llvm-vs2014")
buildoptions { "-Wno-unused-variable -msse4.1" }
end
project "hlsl++"
--kind("StaticLib")
kind("ConsoleApp")
language("C++")
files
{
srcDir.."/**.h", srcDir.."/**.cpp"
}
project "UnitTests"
kind("WindowedApp")
--lalal
project("Natvis")
kind("StaticLib")
files{ srcDir.."/**.natvis" }
|
Workspace = "workspace/".._ACTION
-- Compilers
PlatformMSVC64 = "MSVC 64"
PlatformMSVC32 = "MSVC 32"
PlatformLLVM64 = "LLVM 64"
PlatformLLVM32 = "LLVM 32"
PlatformOSX64 = "OSX 64"
PlatformLinux64 = "Linux 64"
-- Directories
srcDir = "src"
workspace "hlsl++"
configurations { "Debug", "Release" }
location (Workspace)
includedirs
{
srcDir,
}
print (_ACTION)
print "lalalalalal"
if(_ACTION == "xcode4") then
platforms { PlatformOSX64 }
toolset("clang")
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1 -std=c++11" }
linkoptions { "-stdlib=libc++" }
elseif(_ACTION == "gmake") then
platforms { PlatformLinux64 }
toolset("gcc")
architecture("x64")
else
platforms { PlatformMSVC64, PlatformMSVC32, PlatformLLVM64, PlatformLLVM32 }
filter { "platforms:"..PlatformMSVC64 }
toolset("msc")
architecture("x64")
filter { "platforms:"..PlatformMSVC32 }
toolset("msc")
filter { "platforms:"..PlatformLLVM64 }
toolset("msc-llvm-vs2014")
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformLLVM32 }
toolset("msc-llvm-vs2014")
buildoptions { "-Wno-unused-variable -msse4.1" }
end
project "hlsl++"
--kind("StaticLib")
kind("ConsoleApp")
language("C++")
files
{
srcDir.."/**.h", srcDir.."/**.cpp"
}
project "UnitTests"
kind("WindowedApp")
--lalal
project("Natvis")
kind("StaticLib")
files{ srcDir.."/**.natvis" }
|
* Fix wrong else if statement (in Lua the correct syntax it elseif)
|
* Fix wrong else if statement (in Lua the correct syntax it elseif)
|
Lua
|
mit
|
redorav/hlslpp,redorav/hlslpp,redorav/hlslpp
|
4820a07e49e06f638cc063a509fa512813094ab6
|
premake.lua
|
premake.lua
|
Workspace = "workspace/".._ACTION
-- Compilers
PlatformMSVC64 = "MSVC 64"
PlatformMSVC32 = "MSVC 32"
PlatformLLVM64 = "LLVM 64"
PlatformLLVM32 = "LLVM 32"
PlatformOSX64 = "OSX 64"
PlatformLinux64_GCC = "Linux64_GCC"
PlatformLinux64_Clang = "Linux64_Clang"
PlatformARM = "MSVC ARM"
PlatformARM64 = "MSVC ARM64"
-- Directories
srcDir = "src"
workspace "hlsl++"
configurations { "Debug", "Release" }
location (Workspace)
includedirs
{
srcDir,
}
vectorextensions ("SSE4.1")
if(_ACTION == "xcode4") then
platforms { PlatformOSX64 }
toolset("clang")
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
linkoptions { "-stdlib=libc++" }
elseif(_ACTION == "gmake") then
platforms { PlatformLinux64_GCC, PlatformLinux64_Clang }
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
filter { "platforms:"..PlatformLinux64_GCC }
toolset("gcc")
filter { "platforms:"..PlatformLinux64_Clang }
toolset("clang")
else
platforms { PlatformMSVC64, PlatformMSVC32, PlatformLLVM64, PlatformLLVM32, PlatformARM }
filter { "platforms:"..PlatformMSVC64 }
toolset("msc")
architecture("x64")
filter { "platforms:"..PlatformMSVC32 }
toolset("msc")
filter { "platforms:"..PlatformLLVM64 }
toolset("msc-llvm")
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformLLVM32 }
toolset("msc-llvm")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformARM }
architecture("arm")
vectorextensions ("default")
-- Doesn't work until a future premake
--filter { "platforms:"..PlatformARM64 }
--architecture("arm64")
end
configuration "Debug"
defines { "DEBUG" }
symbols "on"
inlining("auto") -- hlslpp relies on inlining for speed, big gains in debug builds without losing legibility
optimize("debug")
configuration "Release"
defines { "NDEBUG" }
optimize "on"
inlining("auto")
optimize("full")
project "hlsl++"
kind("StaticLib")
language("C++")
files
{
srcDir.."/**.h",
srcDir.."/hlsl++.cpp"
}
project "unit_tests"
kind("ConsoleApp")
--links { "hlsl++" }
files
{
srcDir.."/hlsl++_unit_tests.cpp",
srcDir.."/**.natvis"
}
includedirs
{
srcDir.."/**.h"
}
|
Workspace = "workspace/".._ACTION
-- Compilers
PlatformMSVC64 = "MSVC 64"
PlatformMSVC32 = "MSVC 32"
PlatformLLVM64 = "LLVM 64"
PlatformLLVM32 = "LLVM 32"
PlatformOSX64 = "OSX 64"
PlatformLinux64_GCC = "Linux64_GCC"
PlatformLinux64_Clang = "Linux64_Clang"
PlatformARM = "MSVC ARM"
PlatformARM64 = "MSVC ARM64"
-- Directories
srcDir = "src"
workspace "hlsl++"
configurations { "Debug", "Release" }
location (Workspace)
includedirs
{
srcDir,
}
vectorextensions ("SSE4.1")
if(_ACTION == "xcode4") then
platforms { PlatformOSX64 }
toolset("clang")
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
linkoptions { "-stdlib=libc++" }
elseif(_ACTION == "gmake") then
platforms { PlatformLinux64_GCC, PlatformLinux64_Clang }
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
filter { "platforms:"..PlatformLinux64_GCC }
toolset("gcc")
filter { "platforms:"..PlatformLinux64_Clang }
toolset("clang")
else
platforms { PlatformMSVC64, PlatformMSVC32, PlatformLLVM64, PlatformLLVM32, PlatformARM }
local llvmToolset;
if (_ACTION == "vs2015") then
llvmToolset = "msc-llvm-vs2014";
else
llvmToolset = "msc-llvm";
end
filter { "platforms:"..PlatformMSVC64 }
toolset("msc")
architecture("x64")
filter { "platforms:"..PlatformMSVC32 }
toolset("msc")
filter { "platforms:"..PlatformLLVM64 }
toolset(llvmToolset)
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformLLVM32 }
toolset(llvmToolset)
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformARM }
architecture("arm")
vectorextensions ("default")
-- Doesn't work until a future premake
--filter { "platforms:"..PlatformARM64 }
--architecture("arm64")
end
configuration "Debug"
defines { "DEBUG" }
symbols "on"
inlining("auto") -- hlslpp relies on inlining for speed, big gains in debug builds without losing legibility
optimize("debug")
configuration "Release"
defines { "NDEBUG" }
optimize "on"
inlining("auto")
optimize("full")
project "hlsl++"
kind("StaticLib")
language("C++")
files
{
srcDir.."/**.h",
srcDir.."/hlsl++.cpp"
}
project "unit_tests"
kind("ConsoleApp")
--links { "hlsl++" }
files
{
srcDir.."/hlsl++_unit_tests.cpp",
srcDir.."/**.natvis"
}
includedirs
{
srcDir.."/**.h"
}
|
Fix LLVM toolset
|
Fix LLVM toolset
VS2015 needs llvm-vs2014 which is what we used to have but VS2017 uses simply llvm
|
Lua
|
mit
|
redorav/hlslpp,redorav/hlslpp,redorav/hlslpp
|
0f720567ab5a2e50eb72dbbdecf4466af511dd05
|
lua/entities/gmod_wire_expression2/core/http.lua
|
lua/entities/gmod_wire_expression2/core/http.lua
|
/*
Simple HTTP Extension
(McLovin)
*/
E2Lib.RegisterExtension( "http", false, "Lets E2 chips make web requests to the real internet.", "Allows any E2 to make your server make arbitrary HTTP GET requests to any site. It can use this to make HTTP requests to any IP address inside your local network." )
local cvar_delay = CreateConVar( "wire_expression2_http_delay", "3", FCVAR_ARCHIVE )
local cvar_timeout = CreateConVar( "wire_expression2_http_timeout", "15", FCVAR_ARCHIVE )
local requests = {}
local run_on = {
clk = 0,
ents = {}
}
local function player_can_request( ply )
local preq = requests[ply]
return !preq or
(preq.in_progress and preq.t_start and (CurTime() - preq.t_start) >= cvar_timeout:GetFloat()) or
(!preq.in_progress and preq.t_end and (CurTime() - preq.t_end) >= cvar_delay:GetFloat())
end
__e2setcost( 20 )
e2function void httpRequest( string url )
local ply = self.player
if !player_can_request( ply ) or url == "" then return end
requests[ply] = {
in_progress = true,
t_start = CurTime(),
t_end = 0,
url = url
}
http.Fetch(url, function( contents, size, headers, code )
if !IsValid( ply ) or !ply:IsPlayer() or !requests[ply] then return end
local preq = requests[ply]
preq.t_end = CurTime()
preq.in_progress = false
preq.data = contents or ""
run_on.clk = 1
for ent,eply in pairs( run_on.ents ) do
if IsValid( ent ) and ent.Execute and eply == ply then
ent:Execute()
end
end
run_on.clk = 0
end)
end
__e2setcost( 5 )
e2function number httpCanRequest()
return ( player_can_request( self.player ) ) and 1 or 0
end
e2function number httpClk()
return run_on.clk
end
e2function string httpData()
local preq = requests[self.player]
return preq and preq.data or ""
end
e2function string httpRequestUrl()
local preq = requests[self.player]
return preq and preq.url or ""
end
e2function string httpUrlEncode(string data)
local ndata = string.gsub( data, "[^%w _~%.%-]", function( str )
local nstr = string.format( "%X", string.byte( str ) )
return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr
end )
return string.gsub( ndata, " ", "+" )
end
e2function string httpUrlDecode(string data)
local ndata = string.gsub( data, "+", " " )
return string.gsub( ndata, "(%%%x%x)", function( str )
return string.char( tonumber( string.Right( str, 2 ), 16 ) )
end )
end
e2function void runOnHTTP( number rohttp )
run_on.ents[self.entity] = ( rohttp != 0 ) and self.player or nil
end
registerCallback( "destruct", function( self )
run_on.ents[self.entity] = nil
end )
|
/*
Simple HTTP Extension
(McLovin)
*/
E2Lib.RegisterExtension( "http", false, "Lets E2 chips make web requests to the real internet.", "Allows any E2 to make your server make arbitrary HTTP GET requests to any site. It can use this to make HTTP requests to any IP address inside your local network." )
local cvar_delay = CreateConVar( "wire_expression2_http_delay", "3", FCVAR_ARCHIVE )
local cvar_timeout = CreateConVar( "wire_expression2_http_timeout", "15", FCVAR_ARCHIVE )
local requests = {}
local run_on = {
clk = 0,
ents = {}
}
local function player_can_request( ply )
local preq = requests[ply]
return !preq or
(preq.in_progress and preq.t_start and (CurTime() - preq.t_start) >= cvar_timeout:GetFloat()) or
(!preq.in_progress and preq.t_end and (CurTime() - preq.t_end) >= cvar_delay:GetFloat())
end
__e2setcost( 20 )
e2function void httpRequest( string url )
local ply = self.player
if !player_can_request( ply ) or url == "" then return end
requests[ply] = {
in_progress = true,
t_start = CurTime(),
t_end = 0,
url = url
}
http.Fetch(url, function( contents, size, headers, code )
if !IsValid( ply ) or !ply:IsPlayer() or !requests[ply] then return end
local preq = requests[ply]
preq.t_end = CurTime()
preq.in_progress = false
preq.data = contents or ""
run_on.clk = 1
local ent = self.entity
if IsValid(ent) and run_on.ents[ent] then
ent:Execute()
end
run_on.clk = 0
end)
end
__e2setcost( 5 )
e2function number httpCanRequest()
return ( player_can_request( self.player ) ) and 1 or 0
end
e2function number httpClk()
return run_on.clk
end
e2function string httpData()
local preq = requests[self.player]
return preq and preq.data or ""
end
e2function string httpRequestUrl()
local preq = requests[self.player]
return preq and preq.url or ""
end
e2function string httpUrlEncode(string data)
local ndata = string.gsub( data, "[^%w _~%.%-]", function( str )
local nstr = string.format( "%X", string.byte( str ) )
return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr
end )
return string.gsub( ndata, " ", "+" )
end
e2function string httpUrlDecode(string data)
local ndata = string.gsub( data, "+", " " )
return string.gsub( ndata, "(%%%x%x)", function( str )
return string.char( tonumber( string.Right( str, 2 ), 16 ) )
end )
end
e2function void runOnHTTP( number rohttp )
run_on.ents[self.entity] = rohttp ~= 0 and true or nil
end
registerCallback( "destruct", function( self )
run_on.ents[self.entity] = nil
end )
|
Fix HTTP executing all owned E2s
|
Fix HTTP executing all owned E2s
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,thegrb93/wire,sammyt291/wire,Grocel/wire,wiremod/wire,dvdvideo1234/wire,garrysmodlua/wire
|
870f449f65f9ce9e54c6b4678fd1f6c52ade4a96
|
premake/cmft_cli.lua
|
premake/cmft_cli.lua
|
--
-- Copyright 2014 Dario Manesku. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function cmftCliProject(_cmftDir, _bxDir)
local CMFT_INCLUDE_DIR = (_cmftDir .. "include/")
local CMFT_SRC_DIR = (_cmftDir .. "src/cmft/")
local CMFT_CLI_SRC_DIR = (_cmftDir .. "src/")
local BX_INCLUDE_DIR = (_bxDir .. "include/")
local BX_THIRDPARTY_DIR = (_bxDir .. "3rdparty/")
project "cmft_cli"
uuid("52267a12-34bf-4834-8245-2bead0100dc8")
kind "ConsoleApp"
targetname ("cmft")
configuration { "*gcc*" }
links { "dl" }
links { "pthread" }
configuration { "vs*" }
buildoptions
{
"/wd 4127" -- disable 'conditional expression is constant' for do {} while(0)
}
configuration { "Debug" }
defines
{
"CMFT_CONFIG_DEBUG=1",
}
configuration { "Release" }
defines
{
"CMFT_CONFIG_DEBUG=0",
}
configuration {}
debugdir (CMFT_RUNTIME_DIR)
files
{
CMFT_SRC_DIR .. "**.h",
CMFT_SRC_DIR .. "**.cpp",
CMFT_SRC_DIR .. "**/**.h",
CMFT_SRC_DIR .. "**/**.cpp",
CMFT_CLI_SRC_DIR .. "**.h",
CMFT_CLI_SRC_DIR .. "**.cpp",
CMFT_INCLUDE_DIR .. "**.h",
}
includedirs
{
BX_INCLUDE_DIR,
CMFT_SRC_DIR,
CMFT_CLI_SRC_DIR,
CMFT_INCLUDE_DIR,
BX_THIRDPARTY_DIR,
}
end -- cmftCliProject
-- vim: set sw=4 ts=4 expandtab:
|
--
-- Copyright 2014 Dario Manesku. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function cmftCliProject(_cmftDir, _bxDir)
local CMFT_INCLUDE_DIR = (_cmftDir .. "include/")
local CMFT_SRC_DIR = (_cmftDir .. "src/cmft/")
local CMFT_CLI_SRC_DIR = (_cmftDir .. "src/")
local CMFT_RUNTIME_DIR = (_cmftDir .. "runtime/")
local BX_INCLUDE_DIR = (_bxDir .. "include/")
local BX_THIRDPARTY_DIR = (_bxDir .. "3rdparty/")
project "cmft_cli"
uuid("52267a12-34bf-4834-8245-2bead0100dc8")
kind "ConsoleApp"
targetname ("cmft")
configuration { "*gcc*" }
links { "dl" }
links { "pthread" }
configuration { "vs*" }
buildoptions
{
"/wd 4127" -- disable 'conditional expression is constant' for do {} while(0)
}
configuration { "Debug" }
defines
{
"CMFT_CONFIG_DEBUG=1",
}
configuration { "Release" }
defines
{
"CMFT_CONFIG_DEBUG=0",
}
configuration {}
debugdir (CMFT_RUNTIME_DIR)
files
{
CMFT_SRC_DIR .. "**.h",
CMFT_SRC_DIR .. "**.cpp",
CMFT_SRC_DIR .. "**/**.h",
CMFT_SRC_DIR .. "**/**.cpp",
CMFT_CLI_SRC_DIR .. "**.h",
CMFT_CLI_SRC_DIR .. "**.cpp",
CMFT_INCLUDE_DIR .. "**.h",
}
includedirs
{
BX_INCLUDE_DIR,
CMFT_SRC_DIR,
CMFT_CLI_SRC_DIR,
CMFT_INCLUDE_DIR,
BX_THIRDPARTY_DIR,
}
end -- cmftCliProject
-- vim: set sw=4 ts=4 expandtab:
|
Fixed cmft runtime dir in premake.
|
Fixed cmft runtime dir in premake.
|
Lua
|
bsd-2-clause
|
leegoonz/cmft,leegoonz/cmft,plepers/cmft,dogdirt2000/cmft,leegoonz/cmft,dogdirt2000/cmft,plepers/cmft,dogdirt2000/cmft,plepers/cmft
|
a11aacf71f69792c3a7a089ca8356d7c5427f554
|
ffi/framebuffer_android.lua
|
ffi/framebuffer_android.lua
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local framebuffer = {}
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- TODO: should we better use these?
-- android.lib.ANativeWindow_getWidth(window)
-- android.lib.ANativeWindow_getHeight(window)
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
framebuffer.parent.init(self)
end
function framebuffer:refreshFullImp()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == ffi.C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == ffi.C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4)
elseif buffer[0].format == ffi.C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2)
else
android.LOGE("unsupported window format!")
end
if bb then
bb:setInverse(self.bb:getInverse())
-- adapt to possible rotation changes
bb:setRotation(self.bb:getRotation())
bb:blitFrom(self.bb)
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
return require("ffi/framebuffer"):extend(framebuffer)
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local framebuffer = {}
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- TODO: should we better use these?
-- android.lib.ANativeWindow_getWidth(window)
-- android.lib.ANativeWindow_getHeight(window)
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
framebuffer.parent.init(self)
end
function framebuffer:refreshFullImp()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == ffi.C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == ffi.C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4)
elseif buffer[0].format == ffi.C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
-- on Android we just do the whole screen
local x = 0
local y = 0
local w = buffer[0].width
local h = buffer[0].height
bb:setInverse(ext_bb:getInverse())
-- adapt to possible rotation changes
bb:setRotation(ext_bb:getRotation())
bb:blitFrom(ext_bb, x, y, x, y, w, h)
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
return require("ffi/framebuffer"):extend(framebuffer)
|
[fix] Android viewport
|
[fix] Android viewport
Fixes https://github.com/koreader/koreader/issues/3148
|
Lua
|
agpl-3.0
|
houqp/koreader-base,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,koreader/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,houqp/koreader-base,koreader/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,apletnev/koreader-base
|
82a9ebda9e245a1ddc4bbcdf25f1b1119cdd825a
|
tests/actions/make/cpp/test_make_linking.lua
|
tests/actions/make/cpp/test_make_linking.lua
|
--
-- tests/actions/make/cpp/test_make_linking.lua
-- Validate the link step generation for makefiles.
-- Copyright (c) 2010-2013 Jason Perkins and the Premake project
--
local suite = test.declare("make_linking")
local make = premake.make
local project = premake.project
--
-- Setup and teardown
--
local sln, prj
function suite.setup()
_OS = "linux"
sln, prj = test.createsolution()
end
local function prepare(calls)
local cfg = test.getconfig(prj, "Debug")
local toolset = premake.tools.gcc
premake.callarray(make, calls, cfg, toolset)
end
--
-- Check link command for a shared C++ library.
--
function suite.links_onCppSharedLib()
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a shared C library.
--
function suite.links_onCSharedLib()
language "C"
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CC) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a static library.
--
function suite.links_onStaticLib()
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = $(AR) -rcs $(TARGET) $(OBJECTS)
]]
end
--
-- Check link command for a Mac OS X universal static library.
--
function suite.links_onMacUniversalStaticLib()
architecture "universal"
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = libtool -o $(TARGET) $(OBJECTS)
]]
end
--
-- Check a linking to a sibling static library.
--
function suite.links_onSiblingStaticLib()
links "MyProject2"
test.createproject(sln)
kind "StaticLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.a
LDDEPS += build/libMyProject2.a
]]
end
--
-- Check a linking to a sibling shared library.
--
function suite.links_onSiblingSharedLib()
links "MyProject2"
test.createproject(sln)
kind "SharedLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.so
LDDEPS += build/libMyProject2.so
]]
end
--
-- When referencing an external library via a path, the directory
-- should be added to the library search paths, and the library
-- itself included via an -l flag.
--
function suite.onExternalLibraryWithPath()
location "MyProject"
links { "libs/SomeLib" }
prepare { "ldFlags", "libs" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -L../libs
LIBS += -lSomeLib
]]
end
|
--
-- tests/actions/make/cpp/test_make_linking.lua
-- Validate the link step generation for makefiles.
-- Copyright (c) 2010-2013 Jason Perkins and the Premake project
--
local suite = test.declare("make_linking")
local make = premake.make
local project = premake.project
--
-- Setup and teardown
--
local sln, prj
function suite.setup()
_OS = "linux"
sln, prj = test.createsolution()
end
local function prepare(calls)
local cfg = test.getconfig(prj, "Debug")
local toolset = premake.tools.gcc
premake.callarray(make, calls, cfg, toolset)
end
--
-- Check link command for a shared C++ library.
--
function suite.links_onCppSharedLib()
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a shared C library.
--
function suite.links_onCSharedLib()
language "C"
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CC) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a static library.
--
function suite.links_onStaticLib()
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = $(AR) -rcs $(TARGET) $(OBJECTS)
]]
end
--
-- Check link command for a Mac OS X universal static library.
--
function suite.links_onMacUniversalStaticLib()
architecture "universal"
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = libtool -o $(TARGET) $(OBJECTS)
]]
end
--
-- Check a linking to a sibling static library.
--
function suite.links_onSiblingStaticLib()
links "MyProject2"
test.createproject(sln)
kind "StaticLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.a
LDDEPS += build/libMyProject2.a
]]
end
--
-- Check a linking to a sibling shared library.
--
function suite.links_onSiblingSharedLib()
links "MyProject2"
test.createproject(sln)
kind "SharedLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.so
LDDEPS += build/libMyProject2.so
]]
end
--
-- When referencing an external library via a path, the directory
-- should be added to the library search paths, and the library
-- itself included via an -l flag.
--
function suite.onExternalLibraryWithPath()
location "MyProject"
links { "libs/SomeLib" }
prepare { "ldFlags", "libs" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -L../libs
LIBS += -lSomeLib
]]
end
--
-- When referencing an external library with a period in the
-- file name make sure it appears correctly in the LIBS
-- directive. Currently the period and everything after it
-- is stripped
--
function suite.onExternalLibraryWithPath()
location "MyProject"
links { "libs/SomeLib-1.1" }
prepare { "libs", }
test.capture [[
LIBS += -lSomeLib-1.1
]]
end
|
Linking gmake test - checks external lib name isn't mangled
|
Linking gmake test - checks external lib name isn't mangled
External libs with a period in the currently get changed.
The period and everything after it is deleted. So:
links {"lua-5.1"}
becomes:
-llua-5
in the makefile. This test checks for that. Fix in next commit
|
Lua
|
bsd-3-clause
|
felipeprov/premake-core,noresources/premake-core,mendsley/premake-core,xriss/premake-core,CodeAnxiety/premake-core,TurkeyMan/premake-core,martin-traverse/premake-core,starkos/premake-core,lizh06/premake-core,mendsley/premake-core,LORgames/premake-core,Yhgenomics/premake-core,soundsrc/premake-core,akaStiX/premake-core,tvandijck/premake-core,grbd/premake-core,Yhgenomics/premake-core,tritao/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,akaStiX/premake-core,mandersan/premake-core,xriss/premake-core,mandersan/premake-core,resetnow/premake-core,starkos/premake-core,alarouche/premake-core,starkos/premake-core,saberhawk/premake-core,martin-traverse/premake-core,mandersan/premake-core,tritao/premake-core,starkos/premake-core,starkos/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,starkos/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,LORgames/premake-core,jstewart-amd/premake-core,kankaristo/premake-core,jsfdez/premake-core,felipeprov/premake-core,akaStiX/premake-core,premake/premake-core,premake/premake-core,sleepingwit/premake-core,kankaristo/premake-core,alarouche/premake-core,grbd/premake-core,tritao/premake-core,martin-traverse/premake-core,jstewart-amd/premake-core,Meoo/premake-core,saberhawk/premake-core,bravnsgaard/premake-core,soundsrc/premake-core,grbd/premake-core,aleksijuvani/premake-core,kankaristo/premake-core,martin-traverse/premake-core,TurkeyMan/premake-core,premake/premake-core,Zefiros-Software/premake-core,mendsley/premake-core,noresources/premake-core,tvandijck/premake-core,felipeprov/premake-core,sleepingwit/premake-core,Tiger66639/premake-core,Zefiros-Software/premake-core,noresources/premake-core,alarouche/premake-core,saberhawk/premake-core,mandersan/premake-core,sleepingwit/premake-core,resetnow/premake-core,premake/premake-core,Tiger66639/premake-core,lizh06/premake-core,kankaristo/premake-core,Blizzard/premake-core,noresources/premake-core,akaStiX/premake-core,dcourtois/premake-core,prapin/premake-core,Tiger66639/premake-core,aleksijuvani/premake-core,prapin/premake-core,Tiger66639/premake-core,LORgames/premake-core,Yhgenomics/premake-core,tvandijck/premake-core,resetnow/premake-core,tritao/premake-core,xriss/premake-core,soundsrc/premake-core,soundsrc/premake-core,grbd/premake-core,saberhawk/premake-core,bravnsgaard/premake-core,Meoo/premake-core,noresources/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,dcourtois/premake-core,xriss/premake-core,PlexChat/premake-core,felipeprov/premake-core,jstewart-amd/premake-core,PlexChat/premake-core,mendsley/premake-core,premake/premake-core,jsfdez/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,Meoo/premake-core,LORgames/premake-core,prapin/premake-core,jsfdez/premake-core,sleepingwit/premake-core,CodeAnxiety/premake-core,jsfdez/premake-core,premake/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,Yhgenomics/premake-core,noresources/premake-core,CodeAnxiety/premake-core,resetnow/premake-core,lizh06/premake-core,xriss/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,resetnow/premake-core,Blizzard/premake-core,dcourtois/premake-core,Meoo/premake-core,Blizzard/premake-core,jstewart-amd/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,PlexChat/premake-core,prapin/premake-core,lizh06/premake-core,Blizzard/premake-core,mendsley/premake-core,bravnsgaard/premake-core,alarouche/premake-core,PlexChat/premake-core,dcourtois/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,mandersan/premake-core,soundsrc/premake-core,starkos/premake-core,CodeAnxiety/premake-core,premake/premake-core,Blizzard/premake-core,noresources/premake-core,LORgames/premake-core,dcourtois/premake-core
|
ccde19ad8ff4a79d1ff06d6c1b9b20c4541ece02
|
goif.lua
|
goif.lua
|
--
-- goif
--
-- Copyright (c) 2016 BearishMushroom
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
--
local goif = goif or {}
goif.frame = 0
goif.active = false
goif.canvas = nil
goif.width = 0
goif.height = 0
goif.data = {}
local path = (...):match("(.-)[^%.]+$")
path = path:gsub('(%.)', '\\')
local libname = 'none'
if love.system.getOS() == "Windows" then
if jit.arch == 'x86' then
libname = 'libgoif_32.dll'
elseif jit.arch == 'x64' then
libname = 'libgoif_64.dll'
else
error("ERROR, UNSUPPORTED ARCH")
end
elseif love.system.getOS() == "Linux" then
libname = 'libgoif.so'
if path == '' then
path = './'
end
end
local lib = package.loadlib(path .. libname, 'luaopen_libgoif')
lib = lib()
local function bind()
love.graphics.setCanvas(goif.canvas)
love.graphics.clear()
end
local function unbind()
love.graphics.setCanvas()
end
goif.start = function()
goif.frame = 0
goif.data = {}
goif.active = true
if goif.canvas == nil then
goif.width = love.graphics.getWidth()
goif.height = love.graphics.getHeight()
goif.canvas = love.graphics.newCanvas(goif.width, goif.height)
end
end
goif.stop = function(file, verbose)
file = file or "gif.gif"
verbose = verbose or false
goif.active = false
if verbose then
print("Frames: " .. tostring(#goif.data))
end
lib.set_frames(goif.frame - 2, goif.width, goif.height, verbose) -- compensate for skipped frames
love.filesystem.createDirectory("goif")
for i = 3, #goif.data do -- skip 2 frames for allocation lag
local e = goif.data[i]
lib.push_frame(e:getPointer(), e:getSize(), verbose)
end
lib.save(file, verbose)
goif.data = {}
collectgarbage()
end
goif.start_frame = function()
if goif.active then
bind()
end
end
goif.end_frame = function()
if goif.active then
unbind()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(goif.canvas)
goif.data[goif.frame + 1] = goif.canvas:newImageData(0, 0, goif.width, goif.height)
goif.frame = goif.frame + 1
end
end
goif.submit_frame = function(canvas)
goif.data[goif.frame + 1] = canvas:newImageData(0, 0, goif.width, goif.height)
goif.frame = goif.frame + 1
end
return goif
|
--
-- goif
--
-- Copyright (c) 2016 BearishMushroom
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
--
local goif = goif or {}
goif.frame = 0
goif.active = false
goif.canvas = nil
goif.width = 0
goif.height = 0
goif.data = {}
local path = (...):match("(.-)[^%.]+$")
path = path:gsub('(%.)', '\\')
local libname = 'none'
if love.system.getOS() == "Windows" then
if jit.arch == 'x86' then
libname = 'libgoif_32.dll'
elseif jit.arch == 'x64' then
libname = 'libgoif_64.dll'
else
error("ERROR, UNSUPPORTED ARCH")
end
elseif love.system.getOS() == "Linux" then
libname = 'libgoif.so'
path = './'
end
local lib = package.loadlib(path .. libname, 'luaopen_libgoif')
lib = lib()
local function bind()
love.graphics.setCanvas(goif.canvas)
love.graphics.clear()
end
local function unbind()
love.graphics.setCanvas()
end
goif.start = function(width, height)
width = width or love.graphics.getWidth()
height = height or love.graphics.getHeght()
goif.frame = 0
goif.data = {}
goif.active = true
if goif.canvas == nil then
goif.width = width
goif.height = height
goif.canvas = love.graphics.newCanvas(goif.width, goif.height)
end
end
goif.stop = function(file, verbose)
file = file or "gif.gif"
verbose = verbose or false
goif.active = false
if verbose then
print("Frames: " .. tostring(#goif.data))
end
lib.set_frames(goif.frame - 2, goif.width, goif.height, verbose) -- compensate for skipped frames
love.filesystem.createDirectory("goif")
for i = 3, #goif.data do -- skip 2 frames for allocation lag
local e = goif.data[i]
lib.push_frame(e:getPointer(), e:getSize(), verbose)
end
lib.save(file, verbose)
goif.data = {}
collectgarbage()
end
goif.start_frame = function()
if goif.active then
bind()
end
end
goif.end_frame = function()
if goif.active then
unbind()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(goif.canvas)
goif.data[goif.frame + 1] = goif.canvas:newImageData(0, 0, goif.width, goif.height)
goif.frame = goif.frame + 1
end
end
goif.submit_frame = function(canvas)
goif.data[goif.frame + 1] = canvas:newImageData(0, 0, goif.width, goif.height)
goif.frame = goif.frame + 1
end
return goif
|
Fixed error on Linux, allow for different-sized canvases.
|
Fixed error on Linux, allow for different-sized canvases.
|
Lua
|
mit
|
BearishMushroom/goif
|
fcb38b551753d4972b4a600b9905caa801828b51
|
runtime.lua
|
runtime.lua
|
local curargs
local laserargs = false
local function selectPattern(name, ...)
if not name then
ledbar.setFunction()
return
end
name = tostring(name)
local pa = patterns[name]
if pa then
curargs = {name,...}
print("Switching to pattern "..name)
ledbar.setFunction(pa, ...)
ledbar.start()
end
end
---- Default Settings -----
local pattparams = {brightness=30, effectbrightness=100, speed=150, hue=0, effecthue=128, randomhue=0, effectrandomhue=0} -- speed: 0..255, hue: 0..255, brightness: 0..100
function pattparams:getHue()
if self.randomhue == 0 then return self.hue else return math.random(0,255) end
end
function pattparams:getEffectHue()
if self.effectrandomhue == 0 then return self.effecthue else return math.random(0,255) end
end
---------------------------
local function mqttChangePattern(data)
laserargs = false
local jd = cjson.decode(data)
if jd.hue then
if type(jd.hue) == "number" and jd.hue >= 0 then
pattparams.hue = jd.hue % 256
pattparams.randomhue = 0
else
pattparams.randomhue = 1
end
end
if jd.brightness and type(jd.brightness) == "number" and jd.brightness >= 0 and jd.brightness <= 100 then
pattparams.brightness = jd.brightness -- 0..100
end
if jd.effecthue then
if type(jd.effecthue) == "number" and jd.effecthue >= 0 then
pattparams.effecthue = jd.effecthue % 256
pattparams.effectrandomhue = 0
else
pattparams.effectrandomhue = 1
end
end
if jd.effectbrightness and type(jd.effectbrightness) == "number" and jd.effectbrightness >= 0 and jd.effectbrightness <= 100 then
pattparams.effectbrightness = jd.effectbrightness -- 0..100
end
if jd.speed and type(jd.speed) == "number" and jd.speed >= 0 and jd.speed <= 255 then
pattparams.speed = jd.speed -- 0..255
end
if jd.pattern then
selectPattern(jd.pattern, pattparams, jd.arg, jd.arg1)
end
end
local function mqttReactToPresence(data)
local jd = cjson.decode(data)
laserargs = false
if jd.Present then
selectPattern("huetwist",pattparams)
else
selectPattern("off")
end
end
local function mqttReactToButton(data)
local oldargs = curargs
selectPattern("uspol")
tmr.alarm(0, 15000, tmr.ALARM_SINGLE, function() selectPattern(unpack(oldargs)) end)
end
local function mqttReactToLaserVentilation(data)
local jd = cjson.decode(data)
if jd.Damper1 == "open" and jd.Fan == "on" then
laserargs = curargs
selectPattern("movingspots", {speed=252}, 7)
elseif laserargs then
selectPattern(unpack(laserargs))
laserargs = false
end
end
local mqtt_topic_prefix = "action/PipeLEDs/"
r3mqtt.setHandler(mqtt_topic_prefix .. "pattern", mqttChangePattern)
r3mqtt.setHandler(mqtt_topic_prefix .. "restart", function() node.restart() end)
r3mqtt.setHandler("realraum/metaevt/presence", mqttReactToPresence)
r3mqtt.setHandler("realraum/pillar/boredoombuttonpressed", mqttReactToButton)
r3mqtt.setHandler("realraum/ventilation/ventstate", mqttReactToLaserVentilation)
r3mqtt.connect()
setglobal("patt", selectPattern)
ledbar.init()
--selectPattern "strobo"
|
local curargs
local laserargs = false
local function selectPattern(name, ...)
if not name then
ledbar.setFunction()
return
end
name = tostring(name)
local pa = patterns[name]
if pa then
curargs = {name,...}
print("Switching to pattern "..name)
ledbar.setFunction(pa, ...)
ledbar.start()
end
end
---- Default Settings -----
local pattparams = {brightness=30, effectbrightness=100, speed=150, hue=0, effecthue=128, randomhue=0, effectrandomhue=0} -- speed: 0..255, hue: 0..255, brightness: 0..100
function pattparams:getHue()
if self.randomhue == 0 then return self.hue else return math.random(0,255) end
end
function pattparams:getEffectHue()
if self.effectrandomhue == 0 then return self.effecthue else return math.random(0,255) end
end
---------------------------
local function mqttChangePattern(data)
laserargs = false
local jd = cjson.decode(data)
if jd.hue then
if type(jd.hue) == "number" and jd.hue >= 0 then
pattparams.hue = jd.hue % 256
pattparams.randomhue = 0
else
pattparams.randomhue = 1
end
end
if jd.brightness and type(jd.brightness) == "number" and jd.brightness >= 0 and jd.brightness <= 100 then
pattparams.brightness = jd.brightness -- 0..100
end
if jd.effecthue then
if type(jd.effecthue) == "number" and jd.effecthue >= 0 then
pattparams.effecthue = jd.effecthue % 256
pattparams.effectrandomhue = 0
else
pattparams.effectrandomhue = 1
end
end
if jd.effectbrightness and type(jd.effectbrightness) == "number" and jd.effectbrightness >= 0 and jd.effectbrightness <= 100 then
pattparams.effectbrightness = jd.effectbrightness -- 0..100
end
if jd.speed and type(jd.speed) == "number" and jd.speed >= 0 and jd.speed <= 255 then
pattparams.speed = jd.speed -- 0..255
end
if jd.pattern then
selectPattern(jd.pattern, pattparams, jd.arg, jd.arg1)
end
end
local function mqttReactToPresence(data)
local jd = cjson.decode(data)
laserargs = false
if jd.Present then
selectPattern("huetwist",pattparams)
else
selectPattern("off")
end
end
local function mqttReactToButton(data)
local oldargs = curargs
selectPattern("uspol")
tmr.alarm(0, 15000, tmr.ALARM_SINGLE, function() selectPattern(unpack(oldargs)) end)
end
local function mqttReactToLaserVentilation(data)
local jd = cjson.decode(data)
if jd.Damper1 == "open" and jd.Fan == "on" then
if laserargs == false then
laserargs = curargs
end
selectPattern("movingspots", {speed=252}, 7)
elseif laserargs then
selectPattern(unpack(laserargs))
laserargs = false
end
end
local mqtt_topic_prefix = "action/PipeLEDs/"
r3mqtt.setHandler(mqtt_topic_prefix .. "pattern", mqttChangePattern)
r3mqtt.setHandler(mqtt_topic_prefix .. "restart", function() node.restart() end)
r3mqtt.setHandler("realraum/metaevt/presence", mqttReactToPresence)
r3mqtt.setHandler("realraum/pillar/boredoombuttonpressed", mqttReactToButton)
r3mqtt.setHandler("realraum/ventilation/ventstate", mqttReactToLaserVentilation)
r3mqtt.connect()
setglobal("patt", selectPattern)
ledbar.init()
--selectPattern "strobo"
|
--bug
|
--bug
|
Lua
|
mit
|
realraum/r3LoTHRPipeLEDs,realraum/r3LoTHRPipeLEDs
|
01e797e70673ce4f4914d8334e4bc006c60db679
|
src/move.lua
|
src/move.lua
|
function getTile(index)
return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y)
end
function getDirectiveEntity(index)
position = {game.players[index].position.x, game.players[index].position.y}
local list = {"left","down","up","right","accelerator_charger"}
for _, name in ipairs(list) do
local target = game.players[index].surface.find_entity(name,position)
if target ~= nil then
return target
end
end
return nil
end
function inboundTile(name)
local tiles = {"copper-floor", "copper-floor2", "copper-floor3"}
for _, tile in ipairs(tiles) do
if tile == name then
return true
end
end
return false
end
function charge_hoverboard(index,entity)
local charge_needed = 5 - global.hoverboard[index].charge
local energy_needed = (charge_needed) * "1000"
if (entity.energy - energy_needed) > 0 then
entity.energy = entity.energy - energy_needed
global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed
else
print("Insufficient energy for charging.")
end
end
function tileCheck(index)
local tile = getTile(index)
if inboundTile(tile.name) == false then
global.hoverboard[index].charge = 0
return
end
local walk = game.players[index].walking_state.walking
local entity = getDirectiveEntity(index)
if entity == nil then
return
end
if entity.name == "accelerator_charger" then
charge_hoverboard(index,entity)
return
end
if entity.name == "up" and global.hoverboard[index].charge > 0 then
game.players[index].walking_state = {walking = walk, direction = defines.direction.north}
elseif entity.name == "down" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.south}
elseif entity.name == "left" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.west}
elseif entity.name == "right" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.east}
end
end
|
function getTile(index)
return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y)
end
function getDirectiveEntity(index)
position = {game.players[index].position.x, game.players[index].position.y}
local list = {"left","down","up","right","accelerator_charger"}
for _, name in ipairs(list) do
local target = game.players[index].surface.find_entity(name,position)
if target ~= nil then
return target
end
end
return nil
end
function inboundTile(name)
local tiles = {"copper-floor", "copper-floor2", "copper-floor3"}
for _, tile in ipairs(tiles) do
if tile == name then
return true
end
end
return false
end
function charge_hoverboard(index,entity)
local charge_needed = 5 - global.hoverboard[index].charge
local energy_needed = (charge_needed) * "1000"
if (entity.energy - energy_needed) > 0 then
entity.energy = entity.energy - energy_needed
global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed
else
print("Insufficient energy for charging.")
end
end
function tileCheck(index)
local tile = getTile(index)
if inboundTile(tile.name) == false then
global.hoverboard[index].charge = 0
return
end
local walk = game.players[index].walking_state.walking
local entity = getDirectiveEntity(index)
if entity == nil then
return
end
if entity.name == "accelerator_charger" then
charge_hoverboard(index,entity)
return
end
if global.hoverboard[index].charge > 0 then
if entity.name == "up" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.north}
elseif entity.name == "down" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.south}
elseif entity.name == "left" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.west}
elseif entity.name == "right" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.east}
end
end
end
|
move a conditional up to a level to fix a bug with directives working even if charge is zero
|
move a conditional up to a level to fix a bug with directives working even if charge is zero
|
Lua
|
mit
|
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
|
bd88776f556d48c67d62317802d1e8cd03a16124
|
show_model_content.lua
|
show_model_content.lua
|
require 'paths'
require 'nn'
require 'cutorch'
require 'cunn'
require 'LeakyReLU'
require 'dpnn'
require 'layers.cudnnSpatialConvolutionUpsample'
require 'stn'
OPT = lapp[[
--save (default "logs") subdirectory in which the model is saved
--network (default "adversarial.net") name of the model file
]]
local filepath = paths.concat(OPT.save, OPT.network)
local tmp = torch.load(filepath)
if tmp.epoch then print("") print("Epoch:") print(tmp.epoch) end
if tmp.opt then print("") print("OPT:") print(tmp.opt) end
if tmp.G then print("") print("G:") print(tmp.G) end
if tmp.G1 then print("") print("G1:") print(tmp.G1) end
if tmp.G2 then print("") print("G2:") print(tmp.G2) end
if tmp.G3 then print("") print("G3:") print(tmp.G3) end
if tmp.D then print("") print("D:") print(tmp.D) end
|
require 'paths'
require 'nn'
require 'cutorch'
require 'cunn'
require 'cudnn'
require 'dpnn'
OPT = lapp[[
--save (default "logs") subdirectory in which the model is saved
--network (default "adversarial.net") name of the model file
]]
local filepath = paths.concat(OPT.save, OPT.network)
local tmp = torch.load(filepath)
if tmp.epoch then print("") print("Epoch:") print(tmp.epoch) end
if tmp.opt then print("") print("OPT:") print(tmp.opt) end
if tmp.G then print("") print("G:") print(tmp.G) end
if tmp.G1 then print("") print("G1:") print(tmp.G1) end
if tmp.G2 then print("") print("G2:") print(tmp.G2) end
if tmp.G3 then print("") print("G3:") print(tmp.G3) end
if tmp.D then print("") print("D:") print(tmp.D) end
|
Fix requires in model shower
|
Fix requires in model shower
|
Lua
|
mit
|
aleju/christmas-generator
|
405196bb0196c12c0914ab8b59fe45477b91e6ea
|
test_scripts/Polices/appID_Management/008_ATF_P_TC_Register_App_Interface_Without_Data_Consent_Assign_pre_DataConsent_Policies.lua
|
test_scripts/Polices/appID_Management/008_ATF_P_TC_Register_App_Interface_Without_Data_Consent_Assign_pre_DataConsent_Policies.lua
|
------------- --------------------------------------------------------------------------------
-- Requirement summary:
-- [RegisterAppInterface] Without data consent, assign "pre_DataConsent" policies
-- to the application which appID does not exist in LocalPT
--
-- Description:
-- SDL should assign "pre_DataConsent" permissions in case the application registers
-- (sends RegisterAppInterface request) with the appID that does not exist in Local Policy Table,
-- and Data Consent either has been denied or has not yet been asked for the device
-- this application registers from
--
-- Preconditions:
-- 1. appID="456_abc" is not registered to SDL yet
-- Steps:
-- 1. Register new application with appID="456_abc"
-- 2. Send "Alert" RPC in order to verify that "pre_DataConsent" permissions are assigned
-- This RPC is not allowed.
-- 3. Verify RPC's respond status
-- 4. Activate application
-- 5. Send "Alert" RPC in order to verify that "default" permissions are assigned
-- This RPC is allowed.
-- 6. Verify RPC's respond status
--
-- Expected result:
-- 3. Status of response: sucess = false, resultCode = "DISALLOWED"
-- 6. Status of response: sucess = true, resultCode = "SUCCESS"
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local testCasesForPolicyAppIdManagament = require("user_modules/shared_testcases/testCasesForPolicyAppIdManagament")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local testCasesForBuildingSDLPolicyFlag = require('user_modules/shared_testcases/testCasesForBuildingSDLPolicyFlag')
--[[ General Precondition before ATF start ]]
testCasesForBuildingSDLPolicyFlag:CheckPolicyFlagAfterBuild("EXTERNAL_PROPRIETARY")
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")
--[[ Local Variables ]]
Test.applicationId = nil
--[[ Local Functions ]]
local function verifyRPC(test, status, code)
local corId = test.mobileSession:SendRPC("Alert",
{
alertText1 = "alertText1",
duration = 3000,
playTone = false
})
test.mobileSession:ExpectResponse(corId, {sucess = status, resultCode = code })
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:StartNewSession()
self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession2:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:RegisterNewApp()
config.application2.registerAppInterfaceParams.appName = "ABC Application"
config.application2.registerAppInterfaceParams.appID = "456_abc"
local corId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "ABC Application" }})
:Do(function(_, data)
self.applicationId = data.params.application.appID
-- self.mobileSession2:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE" })
end)
self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
end
function Test:VerifyRPC()
verifyRPC(self, false, "DISALLOWED")
end
function Test:ActivateApp()
testCasesForPolicyAppIdManagament:activateApp(self, self.applicationId)
end
function Test:VerifyRPC()
verifyRPC(self, true, "SUCCESS")
end
return Test
|
------------- --------------------------------------------------------------------------------
-- Requirement summary:
-- [RegisterAppInterface] Without data consent, assign "pre_DataConsent" policies
-- to the application which appID does not exist in LocalPT
--
-- Description:
-- SDL should assign "pre_DataConsent" permissions in case the application registers
-- (sends RegisterAppInterface request) with the appID that does not exist in Local Policy Table,
-- and Data Consent either has been denied or has not yet been asked for the device
-- this application registers from.
--
-- Preconditions:
-- 1. appID="456_abc" is not registered to SDL yet
-- Steps:
-- 1. Register new application with appID="456_abc"
-- 2. Send "Alert" RPC in order to verify that "pre_DataConsent" permissions are assigned
-- This RPC is not allowed.
-- 3. Verify RPC's respond status
-- 4. Activate application
-- 5. Send "Alert" RPC in order to verify that "default" permissions are assigned
-- This RPC is allowed.
-- 6. Verify RPC's respond status
--
-- Expected result:
-- 3. Status of response: sucess = false, resultCode = "DISALLOWED"
-- 6. Status of response: sucess = true, resultCode = "SUCCESS"
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local testCasesForPolicyAppIdManagament = require("user_modules/shared_testcases/testCasesForPolicyAppIdManagament")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local testCasesForBuildingSDLPolicyFlag = require('user_modules/shared_testcases/testCasesForBuildingSDLPolicyFlag')
--[[ General Precondition before ATF start ]]
testCasesForBuildingSDLPolicyFlag:CheckPolicyFlagAfterBuild("EXTERNAL_PROPRIETARY")
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")
--[[ Local Functions ]]
local function verifyRPC(mob_session, status, code)
local corId = mob_session:SendRPC("Alert",
{
alertText1 = "alertText1",
duration = 3000,
playTone = false
})
mob_session:ExpectResponse(corId, {sucess = status, resultCode = code })
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:StartNewSession()
self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession2:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:RegisterNewApp()
config.application2.registerAppInterfaceParams.appName = "ABC Application"
config.application2.registerAppInterfaceParams.appID = "456_abc"
testCasesForPolicyAppIdManagament:registerApp(self, self.mobileSession2, config.application2)
end
function Test:VerifyRPC()
verifyRPC(self.mobileSession2, false, "DISALLOWED")
end
function Test:ActivateApp()
testCasesForPolicyAppIdManagament:activateApp(self, self.mobileSession2)
end
function Test:VerifyRPC()
verifyRPC(self.mobileSession2, true, "SUCCESS")
end
return Test
|
Fixed issues and made refactoring
|
Fixed issues and made refactoring
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
af28dba1f52990cb7b6c3c8f69f1f1bcf017c90a
|
tests/apis/rules/xmake.lua
|
tests/apis/rules/xmake.lua
|
-- define rule: markdown
rule("markdown")
set_extensions(".md", ".markdown")
on_load(function (target)
print("markdown: on_load")
end)
on_build_file(function (target, sourcefile)
print("compile %s", sourcefile)
os.cp(sourcefile, path.join(target:targetdir(), path.basename(sourcefile) .. ".html"))
end)
-- define rule: man
rule("man")
add_imports("core.project.rule")
on_build_files(function (target, sourcefiles)
for _, sourcefile in ipairs(sourcefiles) do
print("generating man: %s", sourcefile)
end
end)
-- define rule: c code
rule("c code")
add_imports("core.tool.compiler")
before_build_file(function (target, sourcefile)
print("before_build_file: ", sourcefile)
end)
on_build_file(function (target, sourcefile, opt)
import("core.theme.theme")
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
cprint(progress_prefix .. "compiling.$(mode) %s", opt.progress, sourcefile)
local objectfile_o = os.tmpfile() .. ".o"
local sourcefile_c = os.tmpfile() .. ".c"
os.cp(sourcefile, sourcefile_c)
compiler.compile(sourcefile_c, objectfile_o)
table.insert(target:objectfiles(), objectfile_o)
end)
after_build_file(function (target, sourcefile)
print("after_build_file: ", sourcefile)
end)
-- define rule: stub3
rule("stub3")
add_deps("markdown")
on_load(function (target)
print("rule(stub3): on_load")
end)
-- define rule: stub2
rule("stub2")
add_deps("stub3")
on_load(function (target)
print("rule(stub2): on_load")
end)
before_build(function (target)
print("rule(stub2): before_build")
end)
after_build(function (target)
print("rule(stub2): after_build")
end)
-- define rule: stub1
rule("stub1")
add_deps("stub2")
on_load(function (target)
print("rule(stub1): on_load")
end)
before_build(function (target)
print("rule(stub1): before_build")
end)
after_build(function (target)
print("rule(stub1): after_build")
end)
before_clean(function (target)
print("rule(stub1): before_clean")
end)
after_clean(function (target)
print("rule(stub1): after_clean")
end)
before_install(function (target)
print("rule(stub1): before_install")
end)
on_install(function (target)
print("rule(stub1): on_install")
end)
after_install(function (target)
print("rule(stub1): after_install")
end)
before_uninstall(function (target)
print("rule(stub1): before_uninstall")
end)
on_uninstall(function (target)
print("rule(stub1): on_uninstall")
end)
after_uninstall(function (target)
print("rule(stub1): after_uninstall")
end)
before_package(function (target)
print("rule(stub1): before_package")
end)
on_package(function (target)
print("rule(stub1): on_package")
end)
after_package(function (target)
print("rule(stub1): after_package")
end)
before_run(function (target)
print("rule(stub1): before_run")
end)
on_run(function (target)
print("rule(stub1): on_run")
end)
after_run(function (target)
print("rule(stub1): after_run")
end)
-- define rule: stub0b
rule("stub0b")
before_build_file(function (target, sourcefile)
print("rule(stub0b): before_build_file", sourcefile)
end)
-- define rule: stub0a
rule("stub0a")
after_build_file(function (target, sourcefile)
print("rule(stub0a): after_build_file", sourcefile)
end)
-- define target
target("test")
-- set kind
set_kind("binary")
-- add rules
add_rules("stub1")
-- add files
add_files("src/*.c", {rules = {"stub0a", "stub0b"}})
add_files("src/man/*.in", {rule = "man"})
add_files("src/index.md")
add_files("src/test.c.in", {rule = "c code"})
on_load(function (target)
print(target:sourcefiles())
print(target:objectfiles())
end)
|
-- define rule: markdown
rule("markdown")
set_extensions(".md", ".markdown")
on_load(function (target)
print("markdown: on_load")
end)
on_build_file(function (target, sourcefile)
print("compile %s", sourcefile)
os.cp(sourcefile, path.join(target:targetdir(), path.basename(sourcefile) .. ".html"))
end)
-- define rule: man
rule("man")
add_imports("core.project.rule")
on_build_files(function (target, sourcefiles)
for _, sourcefile in ipairs(sourcefiles) do
print("generating man: %s", sourcefile)
end
end)
-- define rule: c code
rule("c code")
add_imports("core.tool.compiler")
before_build_file(function (target, sourcefile)
print("before_build_file: ", sourcefile)
end)
on_build_file(function (target, sourcefile, opt)
import("core.theme.theme")
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
cprint(progress_prefix .. "compiling.$(mode) %s", opt.progress, sourcefile)
local objectfile_o = os.tmpfile() .. ".o"
local sourcefile_c = os.tmpfile() .. ".c"
os.cp(sourcefile, sourcefile_c)
compiler.compile(sourcefile_c, objectfile_o)
table.insert(target:objectfiles(), objectfile_o)
end)
after_build_file(function (target, sourcefile)
print("after_build_file: ", sourcefile)
end)
-- define rule: stub3
rule("stub3")
add_deps("markdown")
on_load(function (target)
print("rule(stub3): on_load")
end)
-- define rule: stub2
rule("stub2")
add_deps("stub3")
on_load(function (target)
print("rule(stub2): on_load")
end)
before_build(function (target)
print("rule(stub2): before_build")
end)
after_build(function (target)
print("rule(stub2): after_build")
end)
-- define rule: stub1
rule("stub1")
add_deps("stub2")
on_load(function (target)
print("rule(stub1): on_load")
end)
before_build(function (target)
print("rule(stub1): before_build")
end)
after_build(function (target)
print("rule(stub1): after_build")
end)
before_clean(function (target)
print("rule(stub1): before_clean")
end)
after_clean(function (target)
print("rule(stub1): after_clean")
end)
before_install(function (target)
print("rule(stub1): before_install")
end)
on_install(function (target)
print("rule(stub1): on_install")
end)
after_install(function (target)
print("rule(stub1): after_install")
end)
before_uninstall(function (target)
print("rule(stub1): before_uninstall")
end)
on_uninstall(function (target)
print("rule(stub1): on_uninstall")
end)
after_uninstall(function (target)
print("rule(stub1): after_uninstall")
end)
before_package(function (target)
print("rule(stub1): before_package")
end)
on_package(function (target)
print("rule(stub1): on_package")
end)
after_package(function (target)
print("rule(stub1): after_package")
end)
before_run(function (target)
print("rule(stub1): before_run")
end)
on_run(function (target)
print("rule(stub1): on_run")
end)
after_run(function (target)
print("rule(stub1): after_run")
end)
-- define rule: stub0b
rule("stub0b")
before_build_file(function (target, sourcefile)
print("rule(stub0b): before_build_file", sourcefile)
end)
-- define rule: stub0a
rule("stub0a")
after_build_file(function (target, sourcefile)
print("rule(stub0a): after_build_file", sourcefile)
end)
-- define target
target("test")
-- set kind
set_kind("binary")
-- add rules
add_rules("stub1")
-- add files
add_files("src/*.c", {rules = {"stub0a", "stub0b"}})
add_files("src/man/*.in", {rule = "man"})
add_files("src/index.md")
add_files("src/test.c.in", {rule = "c code"})
|
fix tests
|
fix tests
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
d64e5ddaf6f32b8ff199dcba50eac51bf4a0d4cc
|
Reshape.lua
|
Reshape.lua
|
local Reshape, parent = torch.class('nn.Reshape', 'nn.Module')
function Reshape:__init(...)
parent.__init(self)
local arg = {...}
self.size = torch.LongStorage()
self.batchsize = torch.LongStorage()
if torch.type(arg[#arg]) == 'boolean' then
self.batchMode = arg[#arg]
table.remove(arg, #arg)
end
local n = #arg
if n == 1 and torch.typename(arg[1]) == 'torch.LongStorage' then
self.size:resize(#arg[1]):copy(arg[1])
else
self.size:resize(n)
for i=1,n do
self.size[i] = arg[i]
end
end
self.nelement = 1
self.batchsize:resize(#self.size+1)
for i=1,#self.size do
self.nelement = self.nelement * self.size[i]
self.batchsize[i+1] = self.size[i]
end
end
function Reshape:updateOutput(input)
if not input:isContiguous() then
self._input = self._input or input.new()
self._gradOutput = self._gradOutput or input.new()
self._input:resizeAs(input)
self._input:copy(input)
input = self._input
end
if (self.batchMode == false) or (
(self.batchMode == nil) and
(input:nElement() == self.nelement and input:size(1) ~= 1)
) then
self.output:view(input, self.size)
else
self.batchsize[1] = input:size(1)
self.output:view(input, self.batchsize)
end
return self.output
end
function Reshape:updateGradInput(input, gradOutput)
if not gradOutput:isContiguous() then
self._gradOutput:resizeAs(gradOutput)
self._gradOutput:copy(gradOutput)
gradOutput = self._gradOutput
end
self.gradInput:viewAs(gradOutput, input)
return self.gradInput
end
function Reshape:__tostring__()
return torch.type(self) .. '(' ..
table.concat(self.size:totable(), 'x') .. ')'
end
function Reshape:clearState()
nn.utils.clear(self, '_input', '_gradOutput')
return parent.clearState(self)
end
|
local Reshape, parent = torch.class('nn.Reshape', 'nn.Module')
function Reshape:__init(...)
parent.__init(self)
local arg = {...}
self.size = torch.LongStorage()
self.batchsize = torch.LongStorage()
if torch.type(arg[#arg]) == 'boolean' then
self.batchMode = arg[#arg]
table.remove(arg, #arg)
end
local n = #arg
if n == 1 and torch.typename(arg[1]) == 'torch.LongStorage' then
self.size:resize(#arg[1]):copy(arg[1])
else
self.size:resize(n)
for i=1,n do
self.size[i] = arg[i]
end
end
self.nelement = 1
self.batchsize:resize(#self.size+1)
for i=1,#self.size do
self.nelement = self.nelement * self.size[i]
self.batchsize[i+1] = self.size[i]
end
end
function Reshape:updateOutput(input)
if not input:isContiguous() then
self._input = self._input or input.new()
self._input:resizeAs(input)
self._input:copy(input)
input = self._input
end
if (self.batchMode == false) or (
(self.batchMode == nil) and
(input:nElement() == self.nelement and input:size(1) ~= 1)
) then
self.output:view(input, self.size)
else
self.batchsize[1] = input:size(1)
self.output:view(input, self.batchsize)
end
return self.output
end
function Reshape:updateGradInput(input, gradOutput)
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput)
self._gradOutput:copy(gradOutput)
gradOutput = self._gradOutput
end
self.gradInput:viewAs(gradOutput, input)
return self.gradInput
end
function Reshape:__tostring__()
return torch.type(self) .. '(' ..
table.concat(self.size:totable(), 'x') .. ')'
end
function Reshape:clearState()
nn.utils.clear(self, '_input', '_gradOutput')
return parent.clearState(self)
end
|
Fixed wrong place of _gradOutput initialization
|
Fixed wrong place of _gradOutput initialization
|
Lua
|
bsd-3-clause
|
kmul00/nn,apaszke/nn,colesbury/nn,joeyhng/nn,eriche2016/nn,nicholas-leonard/nn,PraveerSINGH/nn,diz-vara/nn,elbamos/nn,sagarwaghmare69/nn,jonathantompson/nn,xianjiec/nn,caldweln/nn,jhjin/nn
|
6a3fa3650442a8d8ee712dbafa8f25af88a96c18
|
vrp/client/player_state.lua
|
vrp/client/player_state.lua
|
-- periodic player state update
local state_ready = false
function tvRP.playerStateReady(state)
state_ready = state
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(30000)
if IsPlayerPlaying(PlayerId()) and state_ready then
local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1),true))
vRPserver._updatePos(x,y,z)
vRPserver._updateHealth(tvRP.getHealth())
vRPserver._updateWeapons(tvRP.getWeapons())
vRPserver._updateCustomization(tvRP.getCustomization())
end
end
end)
-- WEAPONS
-- def
local weapon_types = {
"WEAPON_KNIFE",
"WEAPON_STUNGUN",
"WEAPON_FLASHLIGHT",
"WEAPON_NIGHTSTICK",
"WEAPON_HAMMER",
"WEAPON_BAT",
"WEAPON_GOLFCLUB",
"WEAPON_CROWBAR",
"WEAPON_PISTOL",
"WEAPON_COMBATPISTOL",
"WEAPON_APPISTOL",
"WEAPON_PISTOL50",
"WEAPON_MICROSMG",
"WEAPON_SMG",
"WEAPON_ASSAULTSMG",
"WEAPON_ASSAULTRIFLE",
"WEAPON_CARBINERIFLE",
"WEAPON_ADVANCEDRIFLE",
"WEAPON_MG",
"WEAPON_COMBATMG",
"WEAPON_PUMPSHOTGUN",
"WEAPON_SAWNOFFSHOTGUN",
"WEAPON_ASSAULTSHOTGUN",
"WEAPON_BULLPUPSHOTGUN",
"WEAPON_STUNGUN",
"WEAPON_SNIPERRIFLE",
"WEAPON_HEAVYSNIPER",
"WEAPON_REMOTESNIPER",
"WEAPON_GRENADELAUNCHER",
"WEAPON_GRENADELAUNCHER_SMOKE",
"WEAPON_RPG",
"WEAPON_PASSENGER_ROCKET",
"WEAPON_AIRSTRIKE_ROCKET",
"WEAPON_STINGER",
"WEAPON_MINIGUN",
"WEAPON_GRENADE",
"WEAPON_STICKYBOMB",
"WEAPON_SMOKEGRENADE",
"WEAPON_BZGAS",
"WEAPON_MOLOTOV",
"WEAPON_FIREEXTINGUISHER",
"WEAPON_PETROLCAN",
"WEAPON_DIGISCANNER",
"WEAPON_BRIEFCASE",
"WEAPON_BRIEFCASE_02",
"WEAPON_BALL",
"WEAPON_FLARE"
}
function tvRP.getWeaponTypes()
return weapon_types
end
function tvRP.getWeapons()
local player = GetPlayerPed(-1)
local ammo_types = {} -- remember ammo type to not duplicate ammo amount
local weapons = {}
for k,v in pairs(weapon_types) do
local hash = GetHashKey(v)
if HasPedGotWeapon(player,hash) then
local weapon = {}
weapons[v] = weapon
local atype = Citizen.InvokeNative(0x7FEAD38B326B9F74, player, hash)
if ammo_types[atype] == nil then
ammo_types[atype] = true
weapon.ammo = GetAmmoInPedWeapon(player,hash)
else
weapon.ammo = 0
end
end
end
return weapons
end
function tvRP.giveWeapons(weapons,clear_before)
local player = GetPlayerPed(-1)
-- give weapons to player
if clear_before then
RemoveAllPedWeapons(player,true)
end
for k,weapon in pairs(weapons) do
local hash = GetHashKey(k)
local ammo = weapon.ammo or 0
GiveWeaponToPed(player, hash, ammo, false)
end
end
-- set player armour (0-100)
function tvRP.setArmour(amount)
SetPedArmour(GetPlayerPed(-1), amount)
end
--[[
function tvRP.dropWeapon()
SetPedDropsWeapon(GetPlayerPed(-1))
end
--]]
-- PLAYER CUSTOMIZATION
-- parse part key (a ped part or a prop part)
-- return is_proppart, index
local function parse_part(key)
if type(key) == "string" and string.sub(key,1,1) == "p" then
return true,tonumber(string.sub(key,2))
else
return false,tonumber(key)
end
end
function tvRP.getDrawables(part)
local isprop, index = parse_part(part)
if isprop then
return GetNumberOfPedPropDrawableVariations(GetPlayerPed(-1),index)
else
return GetNumberOfPedDrawableVariations(GetPlayerPed(-1),index)
end
end
function tvRP.getDrawableTextures(part,drawable)
local isprop, index = parse_part(part)
if isprop then
return GetNumberOfPedPropTextureVariations(GetPlayerPed(-1),index,drawable)
else
return GetNumberOfPedTextureVariations(GetPlayerPed(-1),index,drawable)
end
end
function tvRP.getCustomization()
local ped = GetPlayerPed(-1)
local custom = {}
custom.modelhash = GetEntityModel(ped)
-- ped parts
for i=0,20 do -- index limit to 20
custom[i] = {GetPedDrawableVariation(ped,i), GetPedTextureVariation(ped,i), GetPedPaletteVariation(ped,i)}
end
-- props
for i=0,10 do -- index limit to 10
custom["p"..i] = {GetPedPropIndex(ped,i), math.max(GetPedPropTextureIndex(ped,i),0)}
end
return custom
end
-- partial customization (only what is set is changed)
function tvRP.setCustomization(custom) -- indexed [drawable,texture,palette] components or props (p0...) plus .modelhash or .model
local r = async()
Citizen.CreateThread(function() -- new thread
if custom then
local ped = GetPlayerPed(-1)
local mhash = nil
-- model
if custom.modelhash then
mhash = custom.modelhash
elseif custom.model then
mhash = GetHashKey(custom.model)
end
if mhash then
local i = 0
while not HasModelLoaded(mhash) and i < 10000 do
RequestModel(mhash)
Citizen.Wait(10)
end
if HasModelLoaded(mhash) then
-- changing player model remove weapons, so save it
local weapons = tvRP.getWeapons()
SetPlayerModel(PlayerId(), mhash)
tvRP.giveWeapons(weapons,true)
SetModelAsNoLongerNeeded(mhash)
end
end
ped = GetPlayerPed(-1)
-- parts
for k,v in pairs(custom) do
if k ~= "model" and k ~= "modelhash" then
local isprop, index = parse_part(k)
if isprop then
if v[1] < 0 then
ClearPedProp(ped,index)
else
SetPedPropIndex(ped,index,v[1],v[2],v[3] or 2)
end
else
SetPedComponentVariation(ped,index,v[1],v[2],v[3] or 2)
end
end
end
end
r()
end)
return r:wait()
end
-- fix invisible players by resetting customization every minutes
--[[
Citizen.CreateThread(function()
while true do
Citizen.Wait(60000)
if state_ready then
local custom = tvRP.getCustomization()
custom.model = nil
custom.modelhash = nil
tvRP.setCustomization(custom)
end
end
end)
--]]
|
-- periodic player state update
local state_ready = false
function tvRP.playerStateReady(state)
state_ready = state
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(30000)
if IsPlayerPlaying(PlayerId()) and state_ready then
local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1),true))
vRPserver._updatePos(x,y,z)
vRPserver._updateHealth(tvRP.getHealth())
vRPserver._updateWeapons(tvRP.getWeapons())
vRPserver._updateCustomization(tvRP.getCustomization())
end
end
end)
-- WEAPONS
-- def
local weapon_types = {
"WEAPON_KNIFE",
"WEAPON_STUNGUN",
"WEAPON_FLASHLIGHT",
"WEAPON_NIGHTSTICK",
"WEAPON_HAMMER",
"WEAPON_BAT",
"WEAPON_GOLFCLUB",
"WEAPON_CROWBAR",
"WEAPON_PISTOL",
"WEAPON_COMBATPISTOL",
"WEAPON_APPISTOL",
"WEAPON_PISTOL50",
"WEAPON_MICROSMG",
"WEAPON_SMG",
"WEAPON_ASSAULTSMG",
"WEAPON_ASSAULTRIFLE",
"WEAPON_CARBINERIFLE",
"WEAPON_ADVANCEDRIFLE",
"WEAPON_MG",
"WEAPON_COMBATMG",
"WEAPON_PUMPSHOTGUN",
"WEAPON_SAWNOFFSHOTGUN",
"WEAPON_ASSAULTSHOTGUN",
"WEAPON_BULLPUPSHOTGUN",
"WEAPON_STUNGUN",
"WEAPON_SNIPERRIFLE",
"WEAPON_HEAVYSNIPER",
"WEAPON_REMOTESNIPER",
"WEAPON_GRENADELAUNCHER",
"WEAPON_GRENADELAUNCHER_SMOKE",
"WEAPON_RPG",
"WEAPON_PASSENGER_ROCKET",
"WEAPON_AIRSTRIKE_ROCKET",
"WEAPON_STINGER",
"WEAPON_MINIGUN",
"WEAPON_GRENADE",
"WEAPON_STICKYBOMB",
"WEAPON_SMOKEGRENADE",
"WEAPON_BZGAS",
"WEAPON_MOLOTOV",
"WEAPON_FIREEXTINGUISHER",
"WEAPON_PETROLCAN",
"WEAPON_DIGISCANNER",
"WEAPON_BRIEFCASE",
"WEAPON_BRIEFCASE_02",
"WEAPON_BALL",
"WEAPON_FLARE"
}
function tvRP.getWeaponTypes()
return weapon_types
end
function tvRP.getWeapons()
local player = GetPlayerPed(-1)
local ammo_types = {} -- remember ammo type to not duplicate ammo amount
local weapons = {}
for k,v in pairs(weapon_types) do
local hash = GetHashKey(v)
if HasPedGotWeapon(player,hash) then
local weapon = {}
weapons[v] = weapon
local atype = Citizen.InvokeNative(0x7FEAD38B326B9F74, player, hash)
if ammo_types[atype] == nil then
ammo_types[atype] = true
weapon.ammo = GetAmmoInPedWeapon(player,hash)
else
weapon.ammo = 0
end
end
end
return weapons
end
function tvRP.giveWeapons(weapons,clear_before)
local player = GetPlayerPed(-1)
-- give weapons to player
if clear_before then
RemoveAllPedWeapons(player,true)
end
for k,weapon in pairs(weapons) do
local hash = GetHashKey(k)
local ammo = weapon.ammo or 0
GiveWeaponToPed(player, hash, ammo, false)
end
end
-- set player armour (0-100)
function tvRP.setArmour(amount)
SetPedArmour(GetPlayerPed(-1), amount)
end
--[[
function tvRP.dropWeapon()
SetPedDropsWeapon(GetPlayerPed(-1))
end
--]]
-- PLAYER CUSTOMIZATION
-- parse part key (a ped part or a prop part)
-- return is_proppart, index
local function parse_part(key)
if type(key) == "string" and string.sub(key,1,1) == "p" then
return true,tonumber(string.sub(key,2))
else
return false,tonumber(key)
end
end
function tvRP.getDrawables(part)
local isprop, index = parse_part(part)
if isprop then
return GetNumberOfPedPropDrawableVariations(GetPlayerPed(-1),index)
else
return GetNumberOfPedDrawableVariations(GetPlayerPed(-1),index)
end
end
function tvRP.getDrawableTextures(part,drawable)
local isprop, index = parse_part(part)
if isprop then
return GetNumberOfPedPropTextureVariations(GetPlayerPed(-1),index,drawable)
else
return GetNumberOfPedTextureVariations(GetPlayerPed(-1),index,drawable)
end
end
function tvRP.getCustomization()
local ped = GetPlayerPed(-1)
local custom = {}
custom.modelhash = GetEntityModel(ped)
-- ped parts
for i=0,20 do -- index limit to 20
custom[i] = {GetPedDrawableVariation(ped,i), GetPedTextureVariation(ped,i), GetPedPaletteVariation(ped,i)}
end
-- props
for i=0,10 do -- index limit to 10
custom["p"..i] = {GetPedPropIndex(ped,i), math.max(GetPedPropTextureIndex(ped,i),0)}
end
return custom
end
-- partial customization (only what is set is changed)
function tvRP.setCustomization(custom) -- indexed [drawable,texture,palette] components or props (p0...) plus .modelhash or .model
local r = async()
Citizen.CreateThread(function() -- new thread
if custom then
local ped = GetPlayerPed(-1)
local mhash = nil
-- model
if custom.modelhash then
mhash = custom.modelhash
elseif custom.model then
mhash = GetHashKey(custom.model)
end
if mhash then
local i = 0
while not HasModelLoaded(mhash) and i < 10000 do
RequestModel(mhash)
Citizen.Wait(10)
end
if HasModelLoaded(mhash) then
-- changing player model remove weapons and armour, so save it
local weapons = tvRP.getWeapons()
local armour = GetPedArmour(ped)
SetPlayerModel(PlayerId(), mhash)
tvRP.giveWeapons(weapons,true)
tvRP.setArmour(armour)
SetModelAsNoLongerNeeded(mhash)
end
end
ped = GetPlayerPed(-1)
-- parts
for k,v in pairs(custom) do
if k ~= "model" and k ~= "modelhash" then
local isprop, index = parse_part(k)
if isprop then
if v[1] < 0 then
ClearPedProp(ped,index)
else
SetPedPropIndex(ped,index,v[1],v[2],v[3] or 2)
end
else
SetPedComponentVariation(ped,index,v[1],v[2],v[3] or 2)
end
end
end
end
r()
end)
return r:wait()
end
-- fix invisible players by resetting customization every minutes
--[[
Citizen.CreateThread(function()
while true do
Citizen.Wait(60000)
if state_ready then
local custom = tvRP.getCustomization()
custom.model = nil
custom.modelhash = nil
tvRP.setCustomization(custom)
end
end
end)
--]]
|
setCustomization armour loss fix.
|
setCustomization armour loss fix.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
4603bb7fc78ea35c5cff2647510c7a6f901e858c
|
nyagos.lua
|
nyagos.lua
|
print("Nihongo Yet Another GOing Shell")
print(string.format("Build at %s with commit %s",nyagos.stamp,nyagos.commit))
print("Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG")
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=os.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function set(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.setenv(left,expand(right))
end
else
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original,1,true) then
right = original
else
right = right .. ";" .. original
end
end
if right then
nyagos.setenv(left,expand(right))
end
end
end
function alias(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.alias(left,right)
end
else
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
x = nyagos.exec
original_print = print
print = nyagos.echo
nyagos.suffixes = {
py={"ipy.exe"},
rb={"ruby.exe"},
lua={"lua.exe"},
pl={"perl.exe"},
awk={"gawk.exe","-f"},
}
nyagos.argsfilter = function(args)
local m = string.match(args[0],"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
for i=0,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
alias{
assoc='%COMSPEC% /c assoc $*',
attrib='%COMSPEC% /c attrib $*',
copy='%COMSPEC% /c copy $*',
del='%COMSPEC% /c del $*',
dir='%COMSPEC% /c dir $*',
['for']='%COMSPEC% /c for $*',
md='%COMSPEC% /c md $*',
mkdir='%COMSPEC% /c mkdir $*',
mklink='%COMSPEC% /c mklink $*',
move='%COMSPEC% /c move $*',
open='%COMSPEC% /c for %I in ($*) do @start "%I"',
rd='%COMSPEC% /c rd $*',
ren='%COMSPEC% /c ren $*',
rename='%COMSPEC% /c rename $*',
rmdir='%COMSPEC% /c rmdir $*',
start='%COMSPEC% /c start $*',
['type']='%COMSPEC% /c type $*',
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
local suffix=string.lower(args[1])
local cmdline=args[2]
nyagos.suffixes[suffix]=cmdline
end
end,
ls='ls -oF $*',
lua_e=function(args)
assert(load(args[1]))()
end,
which=function(args)
for dir1 in string.gmatch(os.getenv('PATH'),"[^;]+") do
for ext1 in string.gmatch(os.getenv('PATHEXT'),"[^;]+") do
local path1 = dir1 .. "\\" .. args[1] .. ext1
if exists(path1) then
nyagos.echo(path1)
end
end
end
end
}
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
x'cd'
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
print("Nihongo Yet Another GOing Shell")
print(string.format("Build at %s with commit %s",nyagos.stamp,nyagos.commit))
print("Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG")
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=os.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function set(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.setenv(left,expand(right))
end
else
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original,1,true) then
right = original
else
right = right .. ";" .. original
end
end
if right then
nyagos.setenv(left,expand(right))
end
end
end
function alias(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.alias(left,right)
end
else
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
x = nyagos.exec
original_print = print
print = nyagos.echo
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
nyagos.setenv("PATHEXT",nyagos.getenv("PATHEXT")..";."..string.upper(suffix))
end
nyagos.suffixes[suffix]=cmdline
end
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
nyagos.argsfilter = function(args)
local m = string.match(args[0],"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
for i=0,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
alias{
assoc='%COMSPEC% /c assoc $*',
attrib='%COMSPEC% /c attrib $*',
copy='%COMSPEC% /c copy $*',
del='%COMSPEC% /c del $*',
dir='%COMSPEC% /c dir $*',
['for']='%COMSPEC% /c for $*',
md='%COMSPEC% /c md $*',
mkdir='%COMSPEC% /c mkdir $*',
mklink='%COMSPEC% /c mklink $*',
move='%COMSPEC% /c move $*',
open='%COMSPEC% /c for %I in ($*) do @start "%I"',
rd='%COMSPEC% /c rd $*',
ren='%COMSPEC% /c ren $*',
rename='%COMSPEC% /c rename $*',
rmdir='%COMSPEC% /c rmdir $*',
start='%COMSPEC% /c start $*',
['type']='%COMSPEC% /c type $*',
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
suffix(args[1],args[2])
end
end,
ls='ls -oF $*',
lua_e=function(args)
assert(load(args[1]))()
end,
which=function(args)
for dir1 in string.gmatch(os.getenv('PATH'),"[^;]+") do
for ext1 in string.gmatch(os.getenv('PATHEXT'),"[^;]+") do
local path1 = dir1 .. "\\" .. args[1] .. ext1
if exists(path1) then
nyagos.echo(path1)
end
end
end
end
}
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
x'cd'
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
suffix コマンド発行時に PATHEXT に登録するようにした。
|
suffix コマンド発行時に PATHEXT に登録するようにした。
|
Lua
|
bsd-3-clause
|
kissthink/nyagos,kissthink/nyagos,hattya/nyagos,tyochiai/nyagos,nocd5/nyagos,zetamatta/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,hattya/nyagos,hattya/nyagos
|
2df0c26c77dcb6e2000ff38b90bb118dc37038bb
|
dmc_lua/lua_error.lua
|
dmc_lua/lua_error.lua
|
--====================================================================--
-- lua_error.lua
--
-- Documentation: http://docs.davidmccuskey.com/display/docs/lua_error.lua
--====================================================================--
--[[
The MIT License (MIT)
Copyright (C) 2014 David McCuskey. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
-- DMC Lua Library : Lua Error
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.1"
--====================================================================--
-- Imports
local Objects = require 'lua_objects'
--====================================================================--
-- Setup, Constants
-- setup some aliases to make code cleaner
local inheritsFrom = Objects.inheritsFrom
local ObjectBase = Objects.ObjectBase
--====================================================================--
-- Support Functions
-- based on https://gist.github.com/cwarden/1207556
local function try( funcs )
local try_f, catch_f, finally_f = funcs[1], funcs[2], funcs[3]
local status, result = pcall(try_f)
if not status and catch_f then
catch_f(result)
end
if finally_f then finally_f() end
return result
end
local function catch(f)
return f[1]
end
local function finally(f)
return f[1]
end
--====================================================================--
-- Error Base Class
--====================================================================--
local Error = inheritsFrom( ObjectBase )
Error.NAME = "Error Instance"
function Error:_init( params )
-- print( "Error:_init" )
params = params or {}
self:superCall( "_init", params )
--==--
if self.is_intermediate then return end
self.message = params.message or "ERROR"
self.traceback = debug.traceback()
local mt = getmetatable( self )
mt.__tostring = function(e)
return table.concat({"ERROR: ",e.message,"\n",e.traceback})
end
end
--====================================================================--
--== Error API Setup
--====================================================================--
-- globals
_G.try = try
_G.catch = catch
_G.finally = finally
return Error
|
--====================================================================--
-- lua_error.lua
--
-- Documentation: http://docs.davidmccuskey.com/display/docs/lua_error.lua
--====================================================================--
--[[
The MIT License (MIT)
Copyright (C) 2014 David McCuskey. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
-- DMC Lua Library : Lua Error
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.1"
--====================================================================--
-- Imports
local Objects = require 'lua_objects'
--====================================================================--
-- Setup, Constants
-- setup some aliases to make code cleaner
local inheritsFrom = Objects.inheritsFrom
local ObjectBase = Objects.ObjectBase
--====================================================================--
-- Support Functions
-- based on https://gist.github.com/cwarden/1207556
local function try( funcs )
local try_f, catch_f, finally_f = funcs[1], funcs[2], funcs[3]
local status, result = pcall(try_f)
if not status and catch_f then
catch_f(result)
end
if finally_f then finally_f() end
return result
end
local function catch(f)
return f[1]
end
local function finally(f)
return f[1]
end
--====================================================================--
-- Error Base Class
--====================================================================--
local Error = inheritsFrom( ObjectBase )
Error.NAME = "Error Instance"
function Error:_init( params )
-- print( "Error:_init" )
params = params or {}
self:superCall( "_init", params )
--==--
if self.is_intermediate then return end
self.prefix = params.prefix or "ERROR: "
self.message = params.message or "there was an error"
self.traceback = debug.traceback()
local mt = getmetatable( self )
mt.__tostring = function(e)
return table.concat({self.prefix,e.message,"\n",e.traceback})
end
end
--====================================================================--
--== Error API Setup
--====================================================================--
-- globals
_G.try = try
_G.catch = catch
_G.finally = finally
return Error
|
allow error prefix to be changed
|
allow error prefix to be changed
|
Lua
|
mit
|
dmccuskey/lua-objects
|
5db14f96401c55f78cfd0953ad47836ca9abe0e1
|
npc/base/talk.lua
|
npc/base/talk.lua
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
require("npc.base.responses")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(npcChar, player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(npcChar, player, text) then
entry:execute(npcChar, player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes
local german, english = self._cycleText:getRandomMessage();
npcChar:talkLanguage(Character.say, Player.german, german);
npcChar:talkLanguage(Character.say, Player.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responseProcessors"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*"
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
local processorFkt = function(_, processor)
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {};
end;
debug("Processor found for response: " .. text);
table.insert(self._responseProcessors[self._responsesCount], processor)
end;
end;
table.foreach(npc.base.responses.processorList, processorFkt);
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(npcChar, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
local responseText = self._responses[selectedResponse];
local responseProcessors = self._responseProcessors[selectedResponse];
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText);
debug("Processing!");
end;
else
debug("No response processors");
end;
npcChar:talk(Character.say, responseText);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(npcChar, player);
end;
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
require("npc.base.responses")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(npcChar, player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(npcChar, player, text) then
entry:execute(npcChar, player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes
local german, english = self._cycleText:getRandomMessage();
npcChar:talkLanguage(Character.say, Player.german, german);
npcChar:talkLanguage(Character.say, Player.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responseProcessors"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*"
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
for _, processor in pairs(npc.base.responses.processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {};
end;
debug("Processor found for response: " .. text);
table.insert(self._responseProcessors[self._responsesCount], processor)
end;
end;
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(npcChar, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
local responseText = self._responses[selectedResponse];
local responseProcessors = self._responseProcessors[selectedResponse];
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText);
debug("Processing!");
end;
else
debug("No response processors");
end;
npcChar:talk(Character.say, responseText);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(npcChar, player);
end;
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
Another try to fix the response processing
|
Another try to fix the response processing
|
Lua
|
agpl-3.0
|
LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content
|
4e703fcb95af93a8a03506a39e6b8d43a222f9f9
|
hammerspoon/.hammerspoon/audio.lua
|
hammerspoon/.hammerspoon/audio.lua
|
local hyper = {"cmd", "alt", "ctrl"}
-- Swap between a Main audio output and a series of ranked secondary outputs
-- Main Output: Vanatoo T0
-- Ranked Secondary Outputs:x
-- 1) JDS Labs DAC
-- 2) Yeti DAC
-- 3) Elgato DAC
-- 4) Laptop Speakers
-------------------------------------------------------------------------------
hs.hotkey.bind(hyper, "s", function()
local currentDeviceName = hs.audiodevice.defaultOutputDevice():name()
local nextDevice
if string.find(currentDeviceName, 'Vanatoo T0') or string.find(currentDeviceName, 'USB audio CODEC') then
nextDevice = hs.audiodevice.findOutputByName('EVO4')
if (nextDevice == nil) then
nextDevice = hs.audiodevice.findOutputByName('External Headphones')
end
else
nextDevice = hs.audiodevice.findOutputByName('Vanatoo T0')
if (nextDevice == nil) then
nextDevice = hs.audiodevice.findOutputByName('USB audio CODEC')
end
end
local didChange = nextDevice:setDefaultOutputDevice()
-- Also set the default Effect device because of a bug where it would change to something random when using setDefaultOutputDevice()
-- it can't keep the "Selected Sound Output Device" setting.
nextDevice:setDefaultEffectDevice()
if (didChange == true) then
hs.alert.closeAll()
hs.alert.show(nextDevice:name())
end
hyper.triggered = true
end)
|
local hyper = {"cmd", "alt", "ctrl"}
-- Swap between a Main audio output and a series of ranked secondary outputs
-- Main Output: Vanatoo T0
-- Ranked Secondary Outputs:x
-- 1) JDS Labs DAC
-- 2) Yeti DAC
-- 3) Elgato DAC
-- 4) Laptop Speakers
-------------------------------------------------------------------------------
hs.hotkey.bind(hyper, "s", function()
local currentDeviceName = hs.audiodevice.defaultOutputDevice():name()
local nextDevice
if string.find(currentDeviceName, 'Vanatoo T0') or string.find(currentDeviceName, 'Studio Display Speakers') then
nextDevice = hs.audiodevice.findOutputByName('EVO4')
if (nextDevice == nil) then
nextDevice = hs.audiodevice.findOutputByName('External Headphones')
end
else
nextDevice = hs.audiodevice.findOutputByName('Vanatoo T0')
if (nextDevice == nil) then
nextDevice = hs.audiodevice.findOutputByName('Studio Display Speakers')
end
end
local didChange = nextDevice:setDefaultOutputDevice()
-- Also set the default Effect device because of a bug where it would change to something random when using setDefaultOutputDevice()
-- it can't keep the "Selected Sound Output Device" setting.
nextDevice:setDefaultEffectDevice()
if (didChange == true) then
hs.alert.closeAll()
hs.alert.show(nextDevice:name())
end
hyper.triggered = true
end)
|
fix audio output switch to support new Studio Display
|
fix audio output switch to support new Studio Display
|
Lua
|
mit
|
francoiscote/dotfiles,francoiscote/dotfiles
|
0f3cb4e13819b1c9ff9c4f79b27a910ebd774d5d
|
translations/others/scripts/actions/dialog.lua
|
translations/others/scripts/actions/dialog.lua
|
require("/scripts/quest/text_generation.lua")
require("/scripts/util.lua")
function context()
return _ENV[entity.entityType()]
end
function entityVariant()
if entity.entityType() == "monster" then
return monster.type()
elseif entity.entityType() == "npc" then
return npc.npcType()
elseif entity.entityType() == "object" then
return world.entityName(entity.id())
end
end
function loadDialog(dialogKey)
local configEntry = config.getParameter(dialogKey)
if type(configEntry) == "string" then
self.dialog[dialogKey] = root.assetJson(configEntry)
elseif type(configEntry) == "table" then
self.dialog[dialogKey] = configEntry
else
self.dialog[dialogKey] = false
end
end
function queryDialog(dialogKey, targetId)
if self.dialog == nil then self.dialog = {} end
if self.dialog[dialogKey] == nil then loadDialog(dialogKey) end
local dialog = self.dialog[dialogKey]
if dialog then
return speciesDialog(dialog, targetId)
end
end
function speciesDialog(dialog, targetId)
local species = context().species and context().species() or "default"
dialog = dialog[species] or dialog.default
local targetDialog
if targetId then
targetDialog = dialog[world.entitySpecies(targetId)] or dialog.default
else
targetDialog = dialog.default
end
if dialog.generic then
targetDialog = util.mergeLists(dialog.generic, targetDialog)
end
return targetDialog
end
function staticRandomizeDialog(list)
math.randomseed(context().seed())
return list[math.random(1, #list)]
end
function sequenceDialog(list, sequenceKey)
self.dialogSequence = self.dialogSequence or {}
self.dialogSequence[sequenceKey] = (self.dialogSequence[sequenceKey] or -1) + 1
return list[(self.dialogSequence[sequenceKey] % #list) + 1]
end
function randomizeDialog(list)
return list[math.random(1, #list)]
end
function randomChatSound()
local chatSounds = config.getParameter("chatSounds", {})
local speciesSounds = chatSounds[npc.species()] or chatSounds.default
if not speciesSounds then return nil end
local genderSounds = speciesSounds[npc.gender()] or speciesSounds.default
if not genderSounds then return nil end
if type(genderSounds) ~= "table" then return genderSounds end
if #genderSounds == 0 then return nil end
return genderSounds[math.random(#genderSounds)]
end
-- output dialog
-- output source
function receiveClueDialog(args, board)
local notification = util.find(self.notifications, function(n) return n.type == "giveClue" end)
if notification then
local dialog = root.assetJson(notification.dialog)
local dialogLine = staticRandomizeDialog(speciesDialog(dialog, notification.sourceId))
world.sendEntityMessage(notification.sourceId, "dialogClueReceived", dialogLine)
return true, {dialog = dialog, source = notification.sourceId}
else
return false
end
end
local function makeTags(args)
local tags = args.tags or {}
local qgen = setmetatable({}, QuestTextGenerator)
tags.selfname = world.entityName(entity.id())
qgen.config = {}
qgen.parameters = {
self = {
id = entity.id,
name = tags.selfname,
type = "entity",
gender = world.entityGender(entity.id())
}
}
if args.entity then
tags.entityname = world.entityName(args.entity)
qgen.parameters.player = {
type = "entity",
gender = world.entityGender(args.entity),
name = tags.entityname,
id = function() return args.entity end,
}
end
local extratags = qgen:generateExtraTags()
if extratags ~= nil then
util.mergeTable(tags, extratags)
end
return tags
end
-- param dialogType
-- param dialog
-- param entity
-- param tags
function sayToEntity(args, board)
local dialog = args.dialog and speciesDialog(args.dialog, args.entity) or queryDialog(args.dialogType, args.entity);
local dialogMode = config.getParameter("dialogMode", "static")
if dialog == nil then
error(string.format("Dialog type %s not specified in %s", args.dialogType, entityVariant()))
end
if dialogMode == "static" then
dialog = staticRandomizeDialog(dialog)
elseif dialogMode == "sequence" then
dialog = sequenceDialog(dialog, args.dialogType)
else
dialog = randomizeDialog(dialog)
end
if dialog == nil then return false end
args.tags = makeTags(args)
local options = {}
-- Only NPCs have sound support
if entity.entityType() == "npc" then
options.sound = randomChatSound()
end
context().say(dialog, args.tags, options)
return true
end
-- param entity
function inspectEntity(args, board)
if not args.entity or not world.entityExists(args.entity) then return false end
local options = {}
local species = nil
if entity.entityType() == "npc" then
species = npc.species()
options.sound = randomChatSound()
end
local dialog = world.entityDescription(args.entity, species)
if not dialog then return false end
local tags = makeTags(args)
context().say(dialog, tags, options)
return true
end
-- param dialogType
-- param entity
function getDialog(args, board)
self.currentDialog = copy(queryDialog(args.dialogType, args.entity))
self.currentDialogTarget = args.entity
if self.currentDialog == nil then
return false
end
return true
end
-- param content
function say(args, board)
local portrait = config.getParameter("chatPortrait")
args.tags = makeTags(args)
local options = {}
if entity.entityType() == "npc" then
options.sound = randomChatSound()
end
if portrait == nil then
context().say(args.content, args.tags, options)
else
context().sayPortrait(args.content, portrait, args.tags, options)
end
return true
end
function sayNext(args, board)
if self.currentDialog == nil or #self.currentDialog == 0 then return false end
local portrait = config.getParameter("chatPortrait")
args.tags = makeTags(args)
if self.currentDialogTarget then args.tags.entityname = world.entityName(self.currentDialogTarget) end
local options = {}
if entity.entityType() == "npc" then
options.sound = randomChatSound()
end
if portrait == nil then
context().say(self.currentDialog[1], args.tags, options)
else
if #self.currentDialog > 1 then
options.drawMoreIndicator = args.drawMoreIndicator
end
context().sayPortrait(self.currentDialog[1], portrait, args.tags, options)
end
table.remove(self.currentDialog, 1)
return true
end
function hasMoreDialog(args, output)
if self.currentDialog == nil or #self.currentDialog == 0 then return false end
return true
end
|
require("/scripts/quest/text_generation.lua")
require("/scripts/util.lua")
function context()
return _ENV[entity.entityType()]
end
function entityVariant()
if entity.entityType() == "monster" then
return monster.type()
elseif entity.entityType() == "npc" then
return npc.npcType()
elseif entity.entityType() == "object" then
return world.entityName(entity.id())
end
end
function loadDialog(dialogKey)
local configEntry = config.getParameter(dialogKey)
if type(configEntry) == "string" then
self.dialog[dialogKey] = root.assetJson(configEntry)
elseif type(configEntry) == "table" then
self.dialog[dialogKey] = configEntry
else
self.dialog[dialogKey] = false
end
end
function queryDialog(dialogKey, targetId)
if self.dialog == nil then self.dialog = {} end
if self.dialog[dialogKey] == nil then loadDialog(dialogKey) end
local dialog = self.dialog[dialogKey]
if dialog then
return speciesDialog(dialog, targetId)
end
end
function speciesDialog(dialog, targetId)
local species = context().species and context().species() or "default"
dialog = dialog[species] or dialog.default
local targetDialog
if targetId then
targetDialog = dialog[world.entitySpecies(targetId)] or dialog.default
else
targetDialog = dialog.default
end
if dialog.generic then
targetDialog = util.mergeLists(dialog.generic, targetDialog)
end
return targetDialog
end
function staticRandomizeDialog(list)
math.randomseed(context().seed())
return list[math.random(1, #list)]
end
function sequenceDialog(list, sequenceKey)
self.dialogSequence = self.dialogSequence or {}
self.dialogSequence[sequenceKey] = (self.dialogSequence[sequenceKey] or -1) + 1
return list[(self.dialogSequence[sequenceKey] % #list) + 1]
end
function randomizeDialog(list)
return list[math.random(1, #list)]
end
function randomChatSound()
local chatSounds = config.getParameter("chatSounds", {})
local speciesSounds = chatSounds[npc.species()] or chatSounds.default
if not speciesSounds then return nil end
local genderSounds = speciesSounds[npc.gender()] or speciesSounds.default
if not genderSounds then return nil end
if type(genderSounds) ~= "table" then return genderSounds end
if #genderSounds == 0 then return nil end
return genderSounds[math.random(#genderSounds)]
end
-- output dialog
-- output source
function receiveClueDialog(args, board)
local notification = util.find(self.notifications, function(n) return n.type == "giveClue" end)
if notification then
local dialog = root.assetJson(notification.dialog)
local dialogLine = staticRandomizeDialog(speciesDialog(dialog, notification.sourceId))
world.sendEntityMessage(notification.sourceId, "dialogClueReceived", dialogLine)
return true, {dialog = dialog, source = notification.sourceId}
else
return false
end
end
local function makeTags(args)
local tags = args.tags or {}
local qgen = setmetatable({}, QuestTextGenerator)
tags.selfname = world.entityName(entity.id())
qgen.config = {}
qgen.parameters = {
self = {
id = entity.id,
name = tags.selfname,
type = "entity",
gender = world.entityGender(entity.id()),
species = world.entitySpecies(entity.id())
}
}
if args.entity then
tags.entityname = world.entityName(args.entity)
qgen.parameters.player = {
type = "entity",
gender = world.entityGender(args.entity),
name = tags.entityname,
species = world.entitySpecies(args.entity),
id = function() return args.entity end,
}
end
if args.cdtarget then
tags.entityname = world.entityName(args.cdtarget)
qgen.parameters.dialogTarget = {
type = "entity",
gender = world.entityGender(args.cdtarget),
name = tags.entityname,
species = world.entitySpecies(args.cdtarget),
id = function() return args.cdtarget end,
}
end
local extratags = qgen:generateExtraTags()
if extratags ~= nil then
util.mergeTable(tags, extratags)
end
return tags
end
-- param dialogType
-- param dialog
-- param entity
-- param tags
function sayToEntity(args, board)
local dialog = args.dialog and speciesDialog(args.dialog, args.entity) or queryDialog(args.dialogType, args.entity);
local dialogMode = config.getParameter("dialogMode", "static")
if dialog == nil then
error(string.format("Dialog type %s not specified in %s", args.dialogType, entityVariant()))
end
if dialogMode == "static" then
dialog = staticRandomizeDialog(dialog)
elseif dialogMode == "sequence" then
dialog = sequenceDialog(dialog, args.dialogType)
else
dialog = randomizeDialog(dialog)
end
if dialog == nil then return false end
args.tags = makeTags(args)
local options = {}
-- Only NPCs have sound support
if entity.entityType() == "npc" then
options.sound = randomChatSound()
end
context().say(dialog, args.tags, options)
return true
end
-- param entity
function inspectEntity(args, board)
if not args.entity or not world.entityExists(args.entity) then return false end
local options = {}
local species = nil
if entity.entityType() == "npc" then
species = npc.species()
options.sound = randomChatSound()
end
local dialog = world.entityDescription(args.entity, species)
if not dialog then return false end
local tags = makeTags(args)
context().say(dialog, tags, options)
return true
end
-- param dialogType
-- param entity
function getDialog(args, board)
self.currentDialog = copy(queryDialog(args.dialogType, args.entity))
self.currentDialogTarget = args.entity
if self.currentDialog == nil then
return false
end
return true
end
-- param content
function say(args, board)
local portrait = config.getParameter("chatPortrait")
args.tags = makeTags(args)
local options = {}
if entity.entityType() == "npc" then
options.sound = randomChatSound()
end
if portrait == nil then
context().say(args.content, args.tags, options)
else
context().sayPortrait(args.content, portrait, args.tags, options)
end
return true
end
function sayNext(args, board)
if self.currentDialog == nil or #self.currentDialog == 0 then return false end
local portrait = config.getParameter("chatPortrait")
if self.currentDialogTarget then args.cdtarget = self.currentDialogTarget end
args.tags = makeTags(args)
if self.currentDialogTarget then args.tags.entityname = world.entityName(self.currentDialogTarget) end
local options = {}
if entity.entityType() == "npc" then
options.sound = randomChatSound()
end
if portrait == nil then
context().say(self.currentDialog[1], args.tags, options)
else
if #self.currentDialog > 1 then
options.drawMoreIndicator = args.drawMoreIndicator
end
context().sayPortrait(self.currentDialog[1], portrait, args.tags, options)
end
table.remove(self.currentDialog, 1)
return true
end
function hasMoreDialog(args, output)
if self.currentDialog == nil or #self.currentDialog == 0 then return false end
return true
end
|
Fixed dialogs after tag generator rewriting
|
Fixed dialogs after tag generator rewriting
|
Lua
|
apache-2.0
|
MrHimera/Starbound_RU,UniverseGuard/Starbound_RU,UniverseGuard/Starbound_RU,SBT-community/Starbound_RU,MrHimera/Starbound_RU,SBT-community/Starbound_RU,GuardOscar/Starbound_RU,GuardOscar/Starbound_RU
|
7e04c97b70d8ef9bf3c5b7091952790809135456
|
frontend/document/pdfdocument.lua
|
frontend/document/pdfdocument.lua
|
require "cache"
require "ui/geometry"
PdfDocument = Document:new{
_document = false,
-- muPDF manages its own additional cache
mupdf_cache_size = 5 * 1024 * 1024,
dc_null = DrawContext.new()
}
function PdfDocument:init()
local ok
ok, self._document = pcall(pdf.openDocument, self.file, self.mupdf_cache_size)
if not ok then
self.error_message = self.doc -- will contain error message
return
end
self.is_open = true
self.info.has_pages = true
if self._document:needsPassword() then
self.is_locked = true
else
self:_readMetadata()
end
end
function PdfDocument:unlock(password)
if not self._document:authenticatePassword(password) then
self._document:close()
return false, "wrong password"
end
self.is_locked = false
return self:_readMetadata()
end
function PdfDocument:getUsedBBox(pageno)
local hash = "pgubbox|"..self.file.."|"..pageno
local cached = Cache:check(hash)
if cached then
return cached.data
end
local page = self._document:openPage(pageno)
local used = {}
used.x, used.y, used.w, used.h = page:getUsedBBox()
Cache:insert(hash, CacheItem:new{ used })
page:close()
return used
end
DocumentRegistry:addProvider("pdf", "application/pdf", PdfDocument)
|
require "cache"
require "ui/geometry"
PdfDocument = Document:new{
_document = false,
-- muPDF manages its own additional cache
mupdf_cache_size = 5 * 1024 * 1024,
dc_null = DrawContext.new()
}
function PdfDocument:init()
local ok
ok, self._document = pcall(pdf.openDocument, self.file, self.mupdf_cache_size)
if not ok then
self.error_message = self.doc -- will contain error message
return
end
self.is_open = true
self.info.has_pages = true
if self._document:needsPassword() then
self.is_locked = true
else
self:_readMetadata()
end
end
function PdfDocument:unlock(password)
if not self._document:authenticatePassword(password) then
self._document:close()
return false, "wrong password"
end
self.is_locked = false
return self:_readMetadata()
end
function PdfDocument:getUsedBBox(pageno)
local hash = "pgubbox|"..self.file.."|"..pageno
local cached = Cache:check(hash)
if cached then
return cached.ubbox
end
local page = self._document:openPage(pageno)
local used = {}
used.x, used.y, used.w, used.h = page:getUsedBBox()
--@TODO give size for cacheitem? 02.12 2012 (houqp)
Cache:insert(hash, CacheItem:new{
ubbox = used,
})
page:close()
return used
end
DocumentRegistry:addProvider("pdf", "application/pdf", PdfDocument)
|
bug fix for PdfDocument:getUsedBBox
|
bug fix for PdfDocument:getUsedBBox
when cache found, we should return cache.ubbox
not cache.data
|
Lua
|
agpl-3.0
|
ashhher3/koreader,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,noname007/koreader,houqp/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,robert00s/koreader,Frenzie/koreader-base,Frenzie/koreader,apletnev/koreader-base,koreader/koreader,mihailim/koreader,Hzj-jie/koreader-base,ashang/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader,NickSavage/koreader,houqp/koreader,lgeek/koreader,Markismus/koreader,frankyifei/koreader-base,houqp/koreader-base,Frenzie/koreader-base,poire-z/koreader,houqp/koreader-base,Frenzie/koreader,Hzj-jie/koreader-base,mwoz123/koreader,frankyifei/koreader-base,houqp/koreader-base,pazos/koreader,apletnev/koreader-base,koreader/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,frankyifei/koreader,chihyang/koreader,koreader/koreader,apletnev/koreader,frankyifei/koreader-base,NiLuJe/koreader,NiLuJe/koreader,NiLuJe/koreader-base,chrox/koreader,Hzj-jie/koreader-base,koreader/koreader-base,poire-z/koreader,koreader/koreader-base
|
8849de47985e14562f72c641e1697f3c7d397ff5
|
lua/main.lua
|
lua/main.lua
|
-- Lua module search path
package.path = './lua/?.lua'
-- C module (shared library) search path
package.cpath = '../MacOS/lib?.dylib;./bin/lib?.so;./bin/?.dll'
assert(jit.os == 'OSX' or jit.os == 'Linux' or jit.os == 'Windows', 'Target OS not supported: ' .. jit.os)
require 'engine.fileutil'.init()
-- =============================================================================
-- Module loading
-- Load and open the LuaFileSystem
-- Note that C module can be loaded using `package.loadlib` instead of `require`
-- but loadlib does not perform any path searching unlike require.
-- Low level C module loading
-- local path = "../MacOS/liblfs.dylib"
-- local f = assert(package.loadlib('lfs', "luaopen_lfs"))
-- f() -- actually open the library
-- Load Lua File System using `require`
local lfs = require 'lfs'
print(lfs.currentdir())
local glfw = require 'engine.glfw'('glfw')
-- Initialize the library
if glfw.Init() == 0 then
return
end
-- Create a windowed mode window and its OpenGL context
local window = glfw.CreateWindow(640, 480, "Hello World")
if window == 0 then
glfw.Terminate()
return
end
-- Make the window's context current
glfw.MakeContextCurrent(window)
-- Loop until the user closes the window
while glfw.WindowShouldClose(window) == 0 do
-- Render here
-- Swap front and back buffers
glfw.SwapBuffers(window)
-- Poll for and process events
glfw.PollEvents()
end
glfw.Terminate()
|
-- Lua module search path
package.path = './lua/?.lua'
-- C module (shared library) search path
package.cpath = '../MacOS/lib?.dylib;./bin/lib?.so;./bin/?.dll'
assert(jit.os == 'OSX' or jit.os == 'Linux' or jit.os == 'Windows', 'Target OS not supported: ' .. jit.os)
require 'engine.fileutil'.init()
-- =============================================================================
-- Module loading
-- Load and open the LuaFileSystem
-- Note that C module can be loaded using `package.loadlib` instead of `require`
-- but loadlib does not perform any path searching unlike require.
-- Low level C module loading
-- local path = "../MacOS/liblfs.dylib"
-- local f = assert(package.loadlib('lfs', "luaopen_lfs"))
-- f() -- actually open the library
-- Load Lua File System using `require`
local lfs = require 'lfs'
print(lfs.currentdir())
local glfw = require 'engine.glfw'(jit.os == 'Windows' and 'glfw3' or 'glfw')
-- Initialize the library
if glfw.Init() == 0 then
return
end
-- Create a windowed mode window and its OpenGL context
local window = glfw.CreateWindow(640, 480, "Hello World")
if window == 0 then
glfw.Terminate()
return
end
-- Make the window's context current
glfw.MakeContextCurrent(window)
-- Loop until the user closes the window
while glfw.WindowShouldClose(window) == 0 do
-- Render here
-- Swap front and back buffers
glfw.SwapBuffers(window)
-- Poll for and process events
glfw.PollEvents()
end
glfw.Terminate()
|
Fix GLFW lib name on WIN
|
Fix GLFW lib name on WIN
|
Lua
|
mit
|
lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot
|
f93b9b9eaaae1ff62d8dbb25b3ed391461faa2ae
|
config/nvim/lua/init/packer.lua
|
config/nvim/lua/init/packer.lua
|
local install_path = vim.fn.stdpath('data') ..
'/site/pack/packer/start/packer.nvim'
if vim.fn.empty(vim.fn.glob(install_path)) > 0 then
vim.fn.system({
'git', 'clone', 'https://github.com/wbthomason/packer.nvim',
install_path
})
end
require('packer').startup(function()
use 'wbthomason/packer.nvim'
use '907th/vim-auto-save'
use 'airblade/vim-gitgutter'
use 'cappyzawa/trim.nvim'
use 'christoomey/vim-tmux-navigator'
use 'cocopon/iceberg.vim'
use 'easymotion/vim-easymotion'
use 'farmergreg/vim-lastplace'
use 'hoob3rt/lualine.nvim'
use 'jiangmiao/auto-pairs'
use 'lukas-reineke/indent-blankline.nvim'
use 'nvim-telescope/telescope.nvim'
use 'pbrisbin/vim-mkdir'
use 'rhysd/clever-f.vim'
use 'svermeulen/vim-yoink'
use 'tpope/vim-abolish'
use 'tpope/vim-commentary'
use 'tpope/vim-fugitive'
use 'tpope/vim-sleuth'
use 'tpope/vim-surround'
use {'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'}
-- languages
use 'ap/vim-css-color'
use 'fatih/vim-go'
use 'hashivim/vim-hashicorp-tools'
use 'hrsh7th/cmp-buffer'
use 'hrsh7th/cmp-emoji'
use 'hrsh7th/cmp-nvim-lsp'
use 'hrsh7th/cmp-path'
use 'hrsh7th/nvim-cmp'
use({
"jose-elias-alvarez/null-ls.nvim",
requires = {"nvim-lua/plenary.nvim", "neovim/nvim-lspconfig"}
})
use 'L3MON4D3/LuaSnip'
use 'neovim/nvim-lspconfig'
use 'pen-lang/pen.vim'
use 'ray-x/cmp-treesitter'
use 'sheerun/vim-polyglot'
use 'styled-components/vim-styled-components'
use {'tzachar/cmp-tabnine', run = './install.sh'}
end)
|
local install_path = vim.fn.stdpath('data') ..
'/site/pack/packer/start/packer.nvim'
if vim.fn.empty(vim.fn.glob(install_path)) > 0 then
vim.fn.system({
'git', 'clone', 'https://github.com/wbthomason/packer.nvim',
install_path
})
end
require('packer').startup(function()
use 'wbthomason/packer.nvim'
use '907th/vim-auto-save'
use 'airblade/vim-gitgutter'
use 'cappyzawa/trim.nvim'
use 'christoomey/vim-tmux-navigator'
use 'cocopon/iceberg.vim'
use 'easymotion/vim-easymotion'
use 'farmergreg/vim-lastplace'
use 'hoob3rt/lualine.nvim'
use 'jiangmiao/auto-pairs'
use 'lukas-reineke/indent-blankline.nvim'
use {'nvim-telescope/telescope.nvim', requires = {"nvim-lua/plenary.nvim"}}
use 'pbrisbin/vim-mkdir'
use 'rhysd/clever-f.vim'
use 'svermeulen/vim-yoink'
use 'tpope/vim-abolish'
use 'tpope/vim-commentary'
use 'tpope/vim-fugitive'
use 'tpope/vim-sleuth'
use 'tpope/vim-surround'
use {'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'}
-- languages
use 'ap/vim-css-color'
use 'fatih/vim-go'
use 'hashivim/vim-hashicorp-tools'
use 'hrsh7th/cmp-buffer'
use 'hrsh7th/cmp-emoji'
use 'hrsh7th/cmp-nvim-lsp'
use 'hrsh7th/cmp-path'
use 'hrsh7th/nvim-cmp'
use({
"jose-elias-alvarez/null-ls.nvim",
requires = {"nvim-lua/plenary.nvim", "neovim/nvim-lspconfig"}
})
use 'L3MON4D3/LuaSnip'
use 'neovim/nvim-lspconfig'
use 'pen-lang/pen.vim'
use 'ray-x/cmp-treesitter'
use 'sheerun/vim-polyglot'
use 'styled-components/vim-styled-components'
use {'tzachar/cmp-tabnine', run = './install.sh'}
end)
|
Fix dependency
|
Fix dependency
|
Lua
|
unlicense
|
raviqqe/dotfiles
|
e54f22b179363669814d9b10e2dbad1570433643
|
kong/plugins/azure-functions/schema.lua
|
kong/plugins/azure-functions/schema.lua
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "azure-functions",
fields = {
{ config = {
type = "record",
fields = {
{ run_on = typedefs.run_on_first },
-- connection basics
{ timeout = { type = "number", default = 600000}, },
{ keepalive = { type = "number", default = 60000 }, },
{ https = { type = "boolean", default = true }, },
{ https_verify = { type = "boolean", default = false }, },
-- authorization
{ apikey = { type = "string" }, },
{ clientid = { type = "string" }, },
-- target/location
{ appname = { type = "string", required = true }, },
{ hostdomain = { type = "string", required = true, default = "azurewebsites.net" }, },
{ routeprefix = { type = "string", default = "api" }, },
{ functionname = { type = "string", required = true }, },
},
}, },
},
}
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "azure-functions",
fields = {
{ run_on = typedefs.run_on_first },
{ config = {
type = "record",
fields = {
-- connection basics
{ timeout = { type = "number", default = 600000}, },
{ keepalive = { type = "number", default = 60000 }, },
{ https = { type = "boolean", default = true }, },
{ https_verify = { type = "boolean", default = false }, },
-- authorization
{ apikey = { type = "string" }, },
{ clientid = { type = "string" }, },
-- target/location
{ appname = { type = "string", required = true }, },
{ hostdomain = { type = "string", required = true, default = "azurewebsites.net" }, },
{ routeprefix = { type = "string", default = "api" }, },
{ functionname = { type = "string", required = true }, },
},
}, },
},
}
|
fix(azure-functions) run_on in schema should be in toplevel fields table, fix #7
|
fix(azure-functions) run_on in schema should be in toplevel fields table, fix #7
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
d93dfb6e6272fe489caeb833282220b30b6507c7
|
MMOCoreORB/bin/scripts/loot/groups/loot_kit_parts.lua
|
MMOCoreORB/bin/scripts/loot/groups/loot_kit_parts.lua
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
loot_kit_parts = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "blue_rug_dye", weight = 150000},
{itemTemplate = "blue_rug_adhesive", weight = 50002},
{itemTemplate = "blue_rug_patches", weight = 150000},
{itemTemplate = "blue_rug_thread_1", weight = 235714},
{itemTemplate = "blue_rug_thread_2", weight = 235714},
{itemTemplate = "blue_rug_thread_3", weight = 235714},
{itemTemplate = "blue_rug_thread_4", weight = 235714},
{itemTemplate = "blue_rug_thread_5", weight = 235714},
{itemTemplate = "blue_rug_thread_6", weight = 235714},
{itemTemplate = "blue_rug_thread_7", weight = 235714},
{itemTemplate = "gong_adhesive", weight = 50002},
{itemTemplate = "gong_skin_back", weight = 150000},
{itemTemplate = "gong_skin_front", weight = 150000},
{itemTemplate = "gong_structure_01", weight = 235714},
{itemTemplate = "gong_structure_02", weight = 235714},
{itemTemplate = "gong_structure_03", weight = 235714},
{itemTemplate = "gong_structure_04", weight = 235714},
{itemTemplate = "gong_structure_05", weight = 235714},
{itemTemplate = "gong_structure_06", weight = 235714},
{itemTemplate = "gong_structure_07", weight = 235714},
{itemTemplate = "light_table_adhesive", weight = 50002},
{itemTemplate = "light_table_glasstop_1", weight = 150000},
{itemTemplate = "light_table_glasstop_2", weight = 150000},
{itemTemplate = "light_table_structure_1", weight = 235714},
{itemTemplate = "light_table_structure_2", weight = 235714},
{itemTemplate = "light_table_structure_3", weight = 235714},
{itemTemplate = "light_table_structure_4", weight = 235714},
{itemTemplate = "light_table_structure_5", weight = 235714},
{itemTemplate = "light_table_structure_6", weight = 235714},
{itemTemplate = "light_table_structure_7", weight = 235714},
{itemTemplate = "orange_rug_adhesive", weight = 50002},
{itemTemplate = "orange_rug_dye", weight = 150000},
{itemTemplate = "orange_rug_patches", weight = 150000},
{itemTemplate = "orange_rug_thread_1", weight = 235714},
{itemTemplate = "orange_rug_thread_2", weight = 235714},
{itemTemplate = "orange_rug_thread_3", weight = 235714},
{itemTemplate = "orange_rug_thread_4", weight = 235714},
{itemTemplate = "orange_rug_thread_5", weight = 235714},
{itemTemplate = "orange_rug_thread_6", weight = 235714},
{itemTemplate = "orange_rug_thread_7", weight = 235714},
{itemTemplate = "sculpture_adhesive", weight = 50002},
{itemTemplate = "sculpture_goldinlay_1", weight = 150000},
{itemTemplate = "sculpture_goldinlay_2", weight = 150000},
{itemTemplate = "sculpture_structure_1", weight = 235714},
{itemTemplate = "sculpture_structure_2", weight = 235714},
{itemTemplate = "sculpture_structure_3", weight = 235714},
{itemTemplate = "sculpture_structure_4", weight = 235714},
{itemTemplate = "sculpture_structure_5", weight = 235714},
{itemTemplate = "sculpture_structure_6", weight = 235714},
{itemTemplate = "sculpture_structure_7", weight = 235714}
}
}
addLootGroupTemplate("loot_kit_parts", loot_kit_parts)
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
loot_kit_parts = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "blue_rug_dye", weight = 202120},
{itemTemplate = "blue_rug_adhesive", weight = 104120},
{itemTemplate = "blue_rug_patches", weight = 204120},
{itemTemplate = "blue_rug_thread_1", weight = 104122},
{itemTemplate = "blue_rug_thread_2", weight = 204122},
{itemTemplate = "blue_rug_thread_3", weight = 304122},
{itemTemplate = "blue_rug_thread_4", weight = 204122},
{itemTemplate = "blue_rug_thread_5", weight = 204122},
{itemTemplate = "blue_rug_thread_6", weight = 204122},
{itemTemplate = "blue_rug_thread_7", weight = 204122},
{itemTemplate = "gong_adhesive", weight = 104122},
{itemTemplate = "gong_skin_back", weight = 204122},
{itemTemplate = "gong_skin_front", weight = 104122},
{itemTemplate = "gong_structure_01", weight = 204122},
{itemTemplate = "gong_structure_02", weight = 204122},
{itemTemplate = "gong_structure_03", weight = 204122},
{itemTemplate = "gong_structure_04", weight = 304122},
{itemTemplate = "gong_structure_05", weight = 204122},
{itemTemplate = "gong_structure_06", weight = 204122},
{itemTemplate = "gong_structure_07", weight = 204122},
{itemTemplate = "light_table_adhesive", weight = 104122},
{itemTemplate = "light_table_glasstop_1", weight = 204122},
{itemTemplate = "light_table_glasstop_2", weight = 104122},
{itemTemplate = "light_table_structure_1", weight = 204122},
{itemTemplate = "light_table_structure_2", weight = 204122},
{itemTemplate = "light_table_structure_3", weight = 302042},
{itemTemplate = "light_table_structure_4", weight = 204122},
{itemTemplate = "light_table_structure_5", weight = 204122},
{itemTemplate = "light_table_structure_6", weight = 204122},
{itemTemplate = "light_table_structure_7", weight = 204122},
{itemTemplate = "orange_rug_adhesive", weight = 204122},
{itemTemplate = "orange_rug_dye", weight = 204122},
{itemTemplate = "orange_rug_patches", weight = 104108},
{itemTemplate = "orange_rug_thread_1", weight = 104122},
{itemTemplate = "orange_rug_thread_2", weight = 204122},
{itemTemplate = "orange_rug_thread_3", weight = 204122},
{itemTemplate = "orange_rug_thread_4", weight = 304122},
{itemTemplate = "orange_rug_thread_5", weight = 204122},
{itemTemplate = "orange_rug_thread_6", weight = 204122},
{itemTemplate = "orange_rug_thread_7", weight = 304122},
{itemTemplate = "sculpture_adhesive", weight = 104122},
{itemTemplate = "sculpture_goldinlay_1", weight = 204122},
{itemTemplate = "sculpture_goldinlay_2", weight = 104122},
{itemTemplate = "sculpture_structure_1", weight = 204122},
{itemTemplate = "sculpture_structure_2", weight = 302122},
{itemTemplate = "sculpture_structure_3", weight = 204122},
{itemTemplate = "sculpture_structure_4", weight = 204122},
{itemTemplate = "sculpture_structure_5", weight = 304122},
{itemTemplate = "sculpture_structure_6", weight = 204122},
{itemTemplate = "sculpture_structure_7", weight = 304122}
}
}
addLootGroupTemplate("loot_kit_parts", loot_kit_parts)
|
[fixed] balanced loot kit drops
|
[fixed] balanced loot kit drops
Change-Id: Ic6fc8afc7fd42d11ee8e656119bf83213822638d
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
623ba7926fdb52ace61fbc38fbcf93f4f62cf51c
|
csharp/tools/tracing-config.lua
|
csharp/tools/tracing-config.lua
|
function RegisterExtractorPack(id)
local extractor = GetPlatformToolsDirectory() ..
'Semmle.Extraction.CSharp.Driver'
if OperatingSystem == 'windows' then extractor = extractor .. '.exe' end
function DotnetMatcherBuild(compilerName, compilerPath, compilerArguments,
_languageId)
if compilerName ~= 'dotnet' and compilerName ~= 'dotnet.exe' then
return nil
end
-- The dotnet CLI has the following usage instructions:
-- dotnet [sdk-options] [command] [command-options] [arguments]
-- we are interested in dotnet build, which has the following usage instructions:
-- dotnet [options] build [<PROJECT | SOLUTION>...]
-- For now, parse the command line as follows:
-- Everything that starts with `-` (or `/`) will be ignored.
-- The first non-option argument is treated as the command.
-- if that's `build`, we append `/p:UseSharedCompilation=false` to the command line,
-- otherwise we do nothing.
local match = false
local argv = compilerArguments.argv
if OperatingSystem == 'windows' then
-- let's hope that this split matches the escaping rules `dotnet` applies to command line arguments
-- or, at least, that it is close enough
argv =
NativeArgumentsToArgv(compilerArguments.nativeArgumentPointer)
end
for i, arg in ipairs(argv) do
-- dotnet options start with either - or / (both are legal)
local firstCharacter = string.sub(arg, 1, 1)
if not (firstCharacter == '-') and not (firstCharacter == '/') then
Log(1, 'Dotnet subcommand detected: %s', arg)
if arg == 'build' or arg == 'msbuild' or arg == 'publish' or arg == 'pack' or arg == 'test' or
arg == 'run' then match = true end
break
end
end
if match then
return {
order = ORDER_REPLACE,
invocation = BuildExtractorInvocation(id, compilerPath,
compilerPath,
compilerArguments, nil, {
'/p:UseSharedCompilation=false'
})
}
end
return nil
end
local windowsMatchers = {
DotnetMatcherBuild,
CreatePatternMatcher({ '^csc.*%.exe$' }, MatchCompilerName, extractor, {
prepend = { '--cil', '--compiler', '"${compiler}"' },
order = ORDER_BEFORE
}),
CreatePatternMatcher({ '^fakes.*%.exe$', 'moles.*%.exe' },
MatchCompilerName, nil, { trace = false }),
function(compilerName, compilerPath, compilerArguments, _languageId)
-- handle cases like `dotnet.exe exec csc.dll <args>`
if compilerName ~= 'dotnet.exe' then
return nil
end
local seenCompilerCall = false
local argv = NativeArgumentsToArgv(compilerArguments.nativeArgumentPointer)
local extractorArgs = { '--cil', '--compiler' }
for _, arg in ipairs(argv) do
if arg:match('csc%.dll$') then
seenCompilerCall = true
end
if seenCompilerCall then
table.insert(extractorArgs, '"' .. arg .. '"')
end
end
if seenCompilerCall then
return {
order = ORDER_BEFORE,
invocation = {
path = AbsolutifyExtractorPath(id, extractor),
arguments = {
commandLineString = table.concat(extractorArgs, " ")
}
}
}
end
return nil
end
}
local posixMatchers = {
DotnetMatcherBuild,
CreatePatternMatcher({ '^mcs%.exe$', '^csc%.exe$' }, MatchCompilerName,
extractor, {
prepend = { '--cil', '--compiler', '"${compiler}"' },
order = ORDER_BEFORE
}), function(compilerName, compilerPath, compilerArguments, _languageId)
if MatchCompilerName('^msbuild$', compilerName, compilerPath,
compilerArguments) or
MatchCompilerName('^xbuild$', compilerName, compilerPath,
compilerArguments) then
return {
order = ORDER_REPLACE,
invocation = BuildExtractorInvocation(id, compilerPath,
compilerPath,
compilerArguments,
nil, {
'/p:UseSharedCompilation=false'
})
}
end
end, function(compilerName, compilerPath, compilerArguments, _languageId)
-- handle cases like `dotnet exec csc.dll <args>` and `mono(-sgen64) csc.exe <args>`
if compilerName ~= 'dotnet' and not compilerName:match('^mono') then
return nil
end
local seenCompilerCall = false
local argv = compilerArguments.argv
local extractorArgs = { '--cil', '--compiler' }
for _, arg in ipairs(argv) do
if arg:match('csc%.dll$') or arg:match('csc%.exe$') or arg:match('mcs%.exe$') then
seenCompilerCall = true
end
if seenCompilerCall then
table.insert(extractorArgs, arg)
end
end
if seenCompilerCall then
return {
order = ORDER_BEFORE,
invocation = {
path = AbsolutifyExtractorPath(id, extractor),
arguments = {
argv = extractorArgs
}
}
}
end
return nil
end
}
if OperatingSystem == 'windows' then
return windowsMatchers
else
return posixMatchers
end
end
-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return { '1.0.0' } end
|
function RegisterExtractorPack(id)
local extractor = GetPlatformToolsDirectory() ..
'Semmle.Extraction.CSharp.Driver'
if OperatingSystem == 'windows' then extractor = extractor .. '.exe' end
function DotnetMatcherBuild(compilerName, compilerPath, compilerArguments,
_languageId)
if compilerName ~= 'dotnet' and compilerName ~= 'dotnet.exe' then
return nil
end
-- The dotnet CLI has the following usage instructions:
-- dotnet [sdk-options] [command] [command-options] [arguments]
-- we are interested in dotnet build, which has the following usage instructions:
-- dotnet [options] build [<PROJECT | SOLUTION>...]
-- For now, parse the command line as follows:
-- Everything that starts with `-` (or `/`) will be ignored.
-- The first non-option argument is treated as the command.
-- if that's `build`, we append `/p:UseSharedCompilation=false` to the command line,
-- otherwise we do nothing.
local match = false
local needsSeparator = false;
local argv = compilerArguments.argv
if OperatingSystem == 'windows' then
-- let's hope that this split matches the escaping rules `dotnet` applies to command line arguments
-- or, at least, that it is close enough
argv =
NativeArgumentsToArgv(compilerArguments.nativeArgumentPointer)
end
for i, arg in ipairs(argv) do
-- dotnet options start with either - or / (both are legal)
local firstCharacter = string.sub(arg, 1, 1)
if not (firstCharacter == '-') and not (firstCharacter == '/') then
Log(1, 'Dotnet subcommand detected: %s', arg)
if arg == 'build' or arg == 'msbuild' or arg == 'publish' or arg == 'pack' or arg == 'test' then
match = true
break
end
if arg == 'run' then
-- for `dotnet run`, we need to make sure that `/p:UseSharedCompilation=false` is
-- not passed in as an argument to the program that is run
match = true
needsSeparator = true
end
end
if arg == '--' then
needsSeparator = false
break
end
end
if match then
local injections = { '/p:UseSharedCompilation=false' }
if needsSeparator then
table.insert(injections, '--')
end
return {
order = ORDER_REPLACE,
invocation = BuildExtractorInvocation(id, compilerPath, compilerPath, compilerArguments, nil, injections)
}
end
return nil
end
local windowsMatchers = {
DotnetMatcherBuild,
CreatePatternMatcher({ '^csc.*%.exe$' }, MatchCompilerName, extractor, {
prepend = { '--cil', '--compiler', '"${compiler}"' },
order = ORDER_BEFORE
}),
CreatePatternMatcher({ '^fakes.*%.exe$', 'moles.*%.exe' },
MatchCompilerName, nil, { trace = false }),
function(compilerName, compilerPath, compilerArguments, _languageId)
-- handle cases like `dotnet.exe exec csc.dll <args>`
if compilerName ~= 'dotnet.exe' then
return nil
end
local seenCompilerCall = false
local argv = NativeArgumentsToArgv(compilerArguments.nativeArgumentPointer)
local extractorArgs = { '--cil', '--compiler' }
for _, arg in ipairs(argv) do
if arg:match('csc%.dll$') then
seenCompilerCall = true
end
if seenCompilerCall then
table.insert(extractorArgs, '"' .. arg .. '"')
end
end
if seenCompilerCall then
return {
order = ORDER_BEFORE,
invocation = {
path = AbsolutifyExtractorPath(id, extractor),
arguments = {
commandLineString = table.concat(extractorArgs, " ")
}
}
}
end
return nil
end
}
local posixMatchers = {
DotnetMatcherBuild,
CreatePatternMatcher({ '^mcs%.exe$', '^csc%.exe$' }, MatchCompilerName,
extractor, {
prepend = { '--cil', '--compiler', '"${compiler}"' },
order = ORDER_BEFORE
}), function(compilerName, compilerPath, compilerArguments, _languageId)
if MatchCompilerName('^msbuild$', compilerName, compilerPath,
compilerArguments) or
MatchCompilerName('^xbuild$', compilerName, compilerPath,
compilerArguments) then
return {
order = ORDER_REPLACE,
invocation = BuildExtractorInvocation(id, compilerPath,
compilerPath,
compilerArguments,
nil, {
'/p:UseSharedCompilation=false'
})
}
end
end, function(compilerName, compilerPath, compilerArguments, _languageId)
-- handle cases like `dotnet exec csc.dll <args>` and `mono(-sgen64) csc.exe <args>`
if compilerName ~= 'dotnet' and not compilerName:match('^mono') then
return nil
end
local seenCompilerCall = false
local argv = compilerArguments.argv
local extractorArgs = { '--cil', '--compiler' }
for _, arg in ipairs(argv) do
if arg:match('csc%.dll$') or arg:match('csc%.exe$') or arg:match('mcs%.exe$') then
seenCompilerCall = true
end
if seenCompilerCall then
table.insert(extractorArgs, arg)
end
end
if seenCompilerCall then
return {
order = ORDER_BEFORE,
invocation = {
path = AbsolutifyExtractorPath(id, extractor),
arguments = {
argv = extractorArgs
}
}
}
end
return nil
end
}
if OperatingSystem == 'windows' then
return windowsMatchers
else
return posixMatchers
end
end
-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return { '1.0.0' } end
|
C#: Fix `/p:UseSharedCompilation=false` tracer injection for `dotnet run`
|
C#: Fix `/p:UseSharedCompilation=false` tracer injection for `dotnet run`
|
Lua
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
fbf90063b9f71ecacc64ba221e5894b3278d0ade
|
mock/audio/SoundSourceAnimatorTrack.lua
|
mock/audio/SoundSourceAnimatorTrack.lua
|
module 'mock'
--------------------------------------------------------------------
CLASS: SoundSourceAnimatorKey ( AnimatorEventKey )
:MODEL{
Field 'clip' :asset('fmod_event') :set( 'setClip' );
}
function SoundSourceAnimatorKey:__init()
self.clip = ''
end
function SoundSourceAnimatorKey:setClip( clip )
self.clip = clip
end
function SoundSourceAnimatorKey:toString()
local clip = self.clip
if not clip then return '<nil>' end
return stripdir( clip )
end
--------------------------------------------------------------------
CLASS: SoundSourceAnimatorTrack ( AnimatorEventTrack )
:MODEL{
}
function SoundSourceAnimatorTrack:getIcon()
return 'track_audio'
end
function SoundSourceAnimatorTrack:toString()
local pathText = self.targetPath:toString()
return pathText..'<clips>'
end
function SoundSourceAnimatorTrack:isPreviewable()
return false
end
function SoundSourceAnimatorTrack:createKey( pos, context )
local key = SoundSourceAnimatorKey()
key:setPos( pos )
self:addKey( key )
local target = context.target --SoundSource
key.clip = target:getDefaultClip()
return key
end
function SoundSourceAnimatorTrack:build( context )
self.idCurve = self:buildIdCurve()
context:updateLength( self:calcLength() )
end
function SoundSourceAnimatorTrack:onStateLoad( state )
local rootEntity, scene = state:getTargetRoot()
local soundSource = self.targetPath:get( rootEntity, scene )
local playContext = { soundSource, 0 }
state:addUpdateListenerTrack( self, playContext )
end
function SoundSourceAnimatorTrack:apply( state, playContext, t )
local soundSource = playContext[1]
local keyId = playContext[2]
local newId = self.idCurve:getValueAtTime( t )
if keyId ~= newId then
playContext[2] = newId
if newId > 0 then
local key = self.keys[ newId ]
local event = key.clip
if not event then
event = soundSource:getDefaultEvent()
end
if event then
if soundSource.is3D then
soundSource:playEvent3D( event, soundSource.follow )
else
soundSource:playEvent2D( event )
end
end
end
end
end
function SoundSourceAnimatorTrack:reset( state, playContext )
-- playContext[2] = 0
end
--------------------------------------------------------------------
registerCustomAnimatorTrackType( SoundSource, 'clips', SoundSourceAnimatorTrack )
|
module 'mock'
--------------------------------------------------------------------
CLASS: SoundSourceAnimatorKey ( AnimatorEventKey )
:MODEL{
Field 'clip' :asset( getSupportedSoundAssetTypes() ) :set( 'setClip' );
}
function SoundSourceAnimatorKey:__init()
self.clip = ''
end
function SoundSourceAnimatorKey:setClip( clip )
self.clip = clip
end
function SoundSourceAnimatorKey:toString()
local clip = self.clip
if not clip then return '<nil>' end
return stripdir( clip )
end
--------------------------------------------------------------------
CLASS: SoundSourceAnimatorTrack ( AnimatorEventTrack )
:MODEL{
}
function SoundSourceAnimatorTrack:getIcon()
return 'track_audio'
end
function SoundSourceAnimatorTrack:toString()
local pathText = self.targetPath:toString()
return pathText..'<clips>'
end
function SoundSourceAnimatorTrack:isPreviewable()
return false
end
function SoundSourceAnimatorTrack:createKey( pos, context )
local key = SoundSourceAnimatorKey()
key:setPos( pos )
self:addKey( key )
local target = context.target --SoundSource
key.clip = target:getDefaultEvent()
return key
end
function SoundSourceAnimatorTrack:build( context )
self.idCurve = self:buildIdCurve()
context:updateLength( self:calcLength() )
end
function SoundSourceAnimatorTrack:onStateLoad( state )
local rootEntity, scene = state:getTargetRoot()
local soundSource = self.targetPath:get( rootEntity, scene )
local playContext = { soundSource, 0 }
state:addUpdateListenerTrack( self, playContext )
end
function SoundSourceAnimatorTrack:apply( state, playContext, t )
local soundSource = playContext[1]
local keyId = playContext[2]
local newId = self.idCurve:getValueAtTime( t )
if keyId ~= newId then
playContext[2] = newId
if newId > 0 then
local key = self.keys[ newId ]
local event = key.clip
if not event then
event = soundSource:getDefaultEvent()
end
if event then
if soundSource.is3D then
soundSource:playEvent3D( event, soundSource.follow )
else
soundSource:playEvent2D( event )
end
end
end
end
end
function SoundSourceAnimatorTrack:reset( state, playContext )
-- playContext[2] = 0
end
--------------------------------------------------------------------
registerCustomAnimatorTrackType( SoundSource, 'clips', SoundSourceAnimatorTrack )
|
soundsource in animator fix
|
soundsource in animator fix
|
Lua
|
mit
|
tommo/mock
|
771476b72d5ca3c1daa11ce2ec0d07f9ec39f0ca
|
src/plugins/finalcutpro/timeline/movetoplayhead.lua
|
src/plugins/finalcutpro/timeline/movetoplayhead.lua
|
--- === plugins.finalcutpro.timeline.movetoplayhead ===
---
--- Move To Playhead.
local require = require
local log = require("hs.logger").new("selectalltimelineclips")
local fcp = require("cp.apple.finalcutpro")
local Do = require("cp.rx.go.Do")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.finalcutpro.timeline.movetoplayhead.moveToPlayhead() -> cp.rx.go.Statement
--- Function
--- Move to Playhead
---
--- Parameters:
--- * None
---
--- Returns:
--- * [Statement](cp.rx.go.Statement.md) to execute.
function mod.doMoveToPlayhead()
local pasteboardManager = mod.pasteboardManager
return Do(pasteboardManager.stopWatching)
:Then(fcp:doShortcut("Cut"))
:Then(fcp:doShortcut("Paste"))
:Catch(function(message)
log.ef("doMoveToPlayhead: %s", message)
end)
:Finally(function()
Do(pasteboardManager.startWatching):After(2000)
end)
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.movetoplayhead",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
["finalcutpro.pasteboard.manager"] = "pasteboardManager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Link to dependancies:
--------------------------------------------------------------------------------
mod.pasteboardManager = deps.pasteboardManager
--------------------------------------------------------------------------------
-- Setup Command:
--------------------------------------------------------------------------------
deps.fcpxCmds
:add("cpMoveToPlayhead")
:whenActivated(function() mod.moveToPlayhead() end)
return mod
end
return plugin
|
--- === plugins.finalcutpro.timeline.movetoplayhead ===
---
--- Move To Playhead.
local require = require
local log = require("hs.logger").new("selectalltimelineclips")
local fcp = require("cp.apple.finalcutpro")
local Do = require("cp.rx.go.Do")
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.movetoplayhead",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
["finalcutpro.pasteboard.manager"] = "pasteboardManager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Link to dependancies:
--------------------------------------------------------------------------------
local pasteboardManager = deps.pasteboardManager
--------------------------------------------------------------------------------
-- Setup Command:
--------------------------------------------------------------------------------
deps.fcpxCmds
:add("cpMoveToPlayhead")
:whenActivated(function()
Do(pasteboardManager.stopWatching)
:Then(fcp:doShortcut("Cut"))
:Then(fcp:doShortcut("Paste"))
:Catch(function(message)
log.ef("doMoveToPlayhead: %s", message)
end)
:Finally(function()
Do(pasteboardManager.startWatching):After(2000)
end)
:Label("Move To Playhead")
:Now()
end)
return mod
end
return plugin
|
#1754
|
#1754
- Fixed bug in “Move to Playhead”
- Closes #1754
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
f98b3c6ab8a8e66761b55dbe0fe8b668b1f73ed8
|
controllers/mg1.lua
|
controllers/mg1.lua
|
--[[
The MG1 policy
Like Cohort scheduling's wavefront pattern, the MG1 policy was based on a very simple idea, namely
that stages should receive time on the CPU in proportion to their load.
The polling tables for the MG1 policy are constructed in such a way that the most heavily-loaded stages are visited more frequently than mostly-idle stages.
Reference: http://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-781.pdf
**************************************** PUC-RIO 2014 ****************************************
Implemented by:
- Breno Riba
Implemented on March 2014
**********************************************************************************************
]]--
local mg1 = {}
local lstage = require 'lstage'
local stages = {}
function mg1.compare(a,b)
return a.visits > b.visits
end
function mg1.buildVisitOrder (pollingTable)
-- Build new polling table
local newVisitOrder = {}
local maxSize = #pollingTable
local firstCell = pollingTable[1]
local lastCell = pollingTable[maxSize]
local index = 1
repeat
-- Insert into polling table
if (pollingTable[index].visits ~= 0) then
table.insert(newVisitOrder, pollingTable[index].stage)
pollingTable[index].visits = pollingTable[index].visits - 1
-- Restart polling table at first stage with visits
-- different from 0
if (index > 1) then
index = 1
else
index = index + 1
end
elseif (index >= maxSize) then
index = 1
else
index = index + 1
end
-- Until last stage
until (firstCell.visits == 0 and lastCell.visits == 0)
return newVisitOrder
end
function is_focused()
require 'math'
-- Validate ID number
if (id ~= 100) then
return
end
local pollingTable = {}
local total = 0
local lastInputCount = 0
local equalInputCount = 1
-- Get demand for each stage
for i,stage in ipairs(stages) do
pollingTable[i] = {}
pollingTable[i].stage = stage
pollingTable[i].load = stage:getInputCount()
pollingTable[i].visits = 0
total = load + pollingTable[i].load
stage:resetStatistics()
if (lastInputCount ~= 0 and lastInputCount ~= pollingTable[i].load) then
lastInputCount = 0
end
lastInputCount = pollingTable[i].load
end
if (equalInputCount == 0) then
local loadRate = 0
local pollingTableSize = #stages * 3
-- Calculate visits
for i,cell in ipairs(pollingTable) do
loadRate = (cell.load * 100) / total
pollingTable[i].visits = math.ceil((loadRate * pollingTableSize) / 100)
end
-- Sort by number of visits
table.sort(pollingTable, mg1.compare)
-- Build new polling table
local newVisitOrder = mg1.buildVisitOrder (pollingTable)
-- Build new polling table
lstage.buildpollingtable(newVisitOrder)
else
-- Same number of visits (we use the stages pipeline)
lstage.buildpollingtable(stages)
end
end
--[[
<summary>
MG1 configure method
</summary>
<param name="stagesTable">LEDA stages table</param>
<param name="numberOfThreads">Number of threads to be created</param>
]]--
function mg1.configure(stagesTable, numberOfThreads)
-- Creating threads
lstage.pool:add(numberOfThreads)
-- Graph with one stage
-- Nothing to do in this case
if (#stagesTable <= 1) then
return
end
-- We keep table in a global because we will
-- use to get stage's rate at "on_timer" callback
stages = stagesTable
lstage.useprivatequeues(0)
lstage.buildpollingtable(stages)
for i,stage in ipairs(stages) do
stage:max_events_when_focused(5)
end
-- Configure last stage to fire when focused
lstage.fireLastFocused()
end
return mg1
|
--[[
The MG1 policy
Like Cohort scheduling's wavefront pattern, the MG1 policy was based on a very simple idea, namely
that stages should receive time on the CPU in proportion to their load.
The polling tables for the MG1 policy are constructed in such a way that the most heavily-loaded stages are visited more frequently than mostly-idle stages.
Reference: http://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-781.pdf
**************************************** PUC-RIO 2014 ****************************************
Implemented by:
- Breno Riba
Implemented on March 2014
**********************************************************************************************
]]--
local mg1 = {}
local lstage = require 'lstage'
local stages = {}
function mg1.compare(a,b)
return a.visits > b.visits
end
function mg1.buildVisitOrder (pollingTable)
-- Build new polling table
local newVisitOrder = {}
local maxSize = #pollingTable
local firstCell = pollingTable[1]
local lastCell = pollingTable[maxSize]
local index = 1
repeat
-- Insert into polling table
if (pollingTable[index].visits ~= 0) then
table.insert(newVisitOrder, pollingTable[index].stage)
pollingTable[index].visits = pollingTable[index].visits - 1
-- Restart polling table at first stage with visits
-- different from 0
if (index > 1) then
index = 1
else
index = index + 1
end
elseif (index >= maxSize) then
index = 1
else
index = index + 1
end
-- Until last stage
until (firstCell.visits == 0 and lastCell.visits == 0)
return newVisitOrder
end
function is_focused()
require 'math'
-- Validate ID number
if (id ~= 100) then
return
end
local pollingTable = {}
local total = 0
local lastInputCount = 0
local equalInputCount = 1
-- Get demand for each stage
for i,stage in ipairs(stages) do
pollingTable[i] = {}
pollingTable[i].stage = stage
pollingTable[i].load = stage:getInputCount()
pollingTable[i].visits = 0
if (lastInputCount ~= 0 and lastInputCount ~= pollingTable[i].load) then
equalInputCount = 0
end
lastInputCount = pollingTable[i].load
total = total + lastInputCount
stage:resetStatistics()
end
if (equalInputCount == 0) then
local loadRate = 0
local pollingTableSize = #stages * 3
-- Calculate visits
for i,cell in ipairs(pollingTable) do
loadRate = (cell.load * 100) / total
pollingTable[i].visits = math.ceil((loadRate * pollingTableSize) / 100)
end
-- Sort by number of visits
table.sort(pollingTable, mg1.compare)
-- Build new polling table
local newVisitOrder = mg1.buildVisitOrder (pollingTable)
-- Build new polling table
lstage.buildpollingtable(newVisitOrder)
else
-- Same number of visits (we use the stages pipeline)
lstage.buildpollingtable(stages)
end
end
--[[
<summary>
MG1 configure method
</summary>
<param name="stagesTable">LEDA stages table</param>
<param name="numberOfThreads">Number of threads to be created</param>
]]--
function mg1.configure(stagesTable, numberOfThreads)
-- Creating threads
lstage.pool:add(numberOfThreads)
-- Graph with one stage
-- Nothing to do in this case
if (#stagesTable <= 1) then
return
end
-- We keep table in a global because we will
-- use to get stage's rate at "on_timer" callback
stages = stagesTable
lstage.buildpollingtable(stages)
lstage.useprivatequeues(0)
for i,stage in ipairs(stages) do
stage:max_events_when_focused(5)
end
-- Configure last stage to fire when focused
lstage.fireLastFocused()
end
return mg1
|
Bug fixes in LG1 controller
|
Bug fixes in LG1 controller
|
Lua
|
mit
|
brenoriba/lstage,brenoriba/lstage
|
0534ccbd399f9addc2fb382a0a735bb07d300733
|
site/api/notifications.lua
|
site/api/notifications.lua
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is thread.lua - a script for fetching a thread based on a message
-- that is in said thread.
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local aaa = require 'lib/aaa'
local user = require 'lib/user'
local cross = require 'lib/cross'
local utils = require 'lib/utils'
function handle(r)
cross.contentType(r, "application/json")
local get = r:parseargs()
-- make sure we're logged in
local account = user.get(r)
if account then
-- callback from the browser when the user has viewed an email. mark it as seen.
if get.seen then
local mid = get.seen
if mid and #mid > 0 then
local doc = elastic.get("notifications", mid)
if doc and doc.seen then
elastic.update("notifications", doc.request_id, { seen = 1 })
r:puts[[{"marked": true}]]
return cross.OK
end
end
r:puts[[{}]]
return cross.OK
end
local peml = {}
-- Find all recent notification docs, up to 50 latest results
local docs = elastic.find("recipient:\"" .. r:sha1(account.cid) .. "\"", 50, "notifications")
for k, doc in pairs(docs) do
-- if we can see the email, push the notif to the list
if aaa.canAccessDoc(r, doc, account) then
doc.id = doc['message-id']
doc.tid = doc.id
doc.nid = doc.request_id
doc.irt = doc['in-reply-to']
table.insert(peml, doc)
end
end
-- spit out JSON
r:puts(JSON.encode{
notifications = peml
})
else
r:puts[[{}]]
end
return cross.OK
end
cross.start(handle)
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is notifications.lua - a script for fetching up to 50 email notifications
-- also marks an email as seen if required
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local aaa = require 'lib/aaa'
local user = require 'lib/user'
local cross = require 'lib/cross'
local utils = require 'lib/utils'
function handle(r)
cross.contentType(r, "application/json")
local get = r:parseargs()
-- make sure we're logged in
local account = user.get(r)
if account then
-- callback from the browser when the user has viewed an email. mark it as seen.
if get.seen then
local mid = get.seen
if mid and #mid > 0 then
local doc = elastic.get("notifications", mid)
if doc and doc.seen then
elastic.update("notifications", doc.request_id, { seen = 1 })
r:puts[[{"marked": true}]]
return cross.OK
end
end
r:puts[[{}]]
return cross.OK
end
local peml = {}
-- Find all recent notification docs, up to 50 latest results
local docs = elastic.find("recipient:\"" .. r:sha1(account.cid) .. "\"", 50, "notifications")
for k, doc in pairs(docs) do
-- if we can see the email, push the notif to the list
if aaa.canAccessDoc(r, doc, account) then
doc.id = doc['message-id']
doc.tid = doc.id
doc.nid = doc.request_id
doc.irt = doc['in-reply-to']
table.insert(peml, doc)
end
end
-- spit out JSON
r:puts(JSON.encode{
notifications = peml
})
else
r:puts[[{}]]
end
return cross.OK
end
cross.start(handle)
|
Docco fix
|
Docco fix
|
Lua
|
apache-2.0
|
jimjag/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,jimjag/ponymail,Humbedooh/ponymail,jimjag/ponymail,jimjag/ponymail
|
e9936e2acec7afdbdb35d9bcf7a6fddad607903d
|
lib/onmt/Encoder.lua
|
lib/onmt/Encoder.lua
|
--[[ Encoder is a unidirectional Sequencer used for the source language.
h_1 => h_2 => h_3 => ... => h_n
| | | |
. . . .
| | | |
h_1 => h_2 => h_3 => ... => h_n
| | | |
| | | |
x_1 x_2 x_3 x_n
Inherits from [onmt.Sequencer](lib+onmt+Sequencer).
--]]
local Encoder, parent = torch.class('onmt.Encoder', 'onmt.Sequencer')
--[[ Construct an encoder layer.
Parameters:
* `input_network` - input module.
* `rnn` - recurrent module.
]]
function Encoder:__init(input_network, rnn)
self.rnn = rnn
self.inputNet = input_network
self.args = {}
self.args.rnn_size = self.rnn.output_size
self.args.num_effective_layers = self.rnn.num_effective_layers
parent.__init(self, self:_buildModel())
self:resetPreallocation()
end
function Encoder.load(pretrained)
local self = torch.factory('onmt.Encoder')()
self.args = pretrained.args
parent.__init(self, pretrained.modules[1])
self:resetPreallocation()
return self
end
--[[ Return data to serialize. ]]
function Encoder:serialize()
return {
modules = self.modules,
args = self.args
}
end
function Encoder:resetPreallocation()
-- Prototype for preallocated hidden and cell states.
self.stateProto = torch.Tensor()
-- Prototype for preallocated output gradients.
self.gradOutputProto = torch.Tensor()
-- Prototype for preallocated context vector.
self.contextProto = torch.Tensor()
end
function Encoder:maskPadding()
self.mask_padding = true
end
--[[ Build one time-step of an encoder
Returns: An nn-graph mapping
$${(c^1_{t-1}, h^1_{t-1}, .., c^L_{t-1}, h^L_{t-1}, x_t) =>
(c^1_{t}, h^1_{t}, .., c^L_{t}, h^L_{t})}$$
Where $$c^l$$ and $$h^l$$ are the hidden and cell states at each layer,
$$x_t$$ is a sparse word to lookup.
--]]
function Encoder:_buildModel()
local inputs = {}
local states = {}
-- Inputs are previous layers first.
for _ = 1, self.args.num_effective_layers do
local h0 = nn.Identity()() -- batch_size x rnn_size
table.insert(inputs, h0)
table.insert(states, h0)
end
-- Input word.
local x = nn.Identity()() -- batch_size
table.insert(inputs, x)
-- Compute input network.
local input = self.inputNet(x)
table.insert(states, input)
-- Forward states and input into the RNN.
local outputs = self.rnn(states)
return nn.gModule(inputs, { outputs })
end
function Encoder:shareInput(other)
self.inputNet:share(other.inputNet, 'weight', 'gradWeight')
end
--[[Compute the context representation of an input.
Parameters:
* `batch` - a [batch struct](lib+data/#opennmtdata) as defined data.lua.
Returns:
1. - final hidden states
2. - context matrix H
--]]
function Encoder:forward(batch)
-- TODO: Change `batch` to `input`.
local final_states
local output_size = self.args.rnn_size
if self.statesProto == nil then
self.statesProto = utils.Tensor.initTensorTable(self.args.num_effective_layers,
self.stateProto,
{ batch.size, output_size })
end
-- Make initial states h_0.
local states = utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, output_size })
-- Preallocated output matrix.
local context = utils.Tensor.reuseTensor(self.contextProto,
{ batch.size, batch.source_length, output_size })
if self.mask_padding and not batch.source_input_pad_left then
final_states = utils.Tensor.recursiveClone(states)
end
if self.train then
self.inputs = {}
end
-- Act like nn.Sequential and call each clone in a feed-forward
-- fashion.
for t = 1, batch.source_length do
-- Construct "inputs". Prev states come first then source.
local inputs = {}
utils.Table.append(inputs, states)
table.insert(inputs, batch:get_source_input(t))
if self.train then
-- Remember inputs for the backward pass.
self.inputs[t] = inputs
end
states = self:net(t):forward(inputs)
-- Special case padding.
if self.mask_padding then
for b = 1, batch.size do
if batch.source_input_pad_left and t <= batch.source_length - batch.source_size[b] then
for j = 1, #states do
states[j][b]:zero()
end
elseif not batch.source_input_pad_left and t == batch.source_size[b] then
for j = 1, #states do
final_states[j][b]:copy(states[j][b])
end
end
end
end
-- Copy output (h^L_t = states[#states]) to context.
context[{{}, t}]:copy(states[#states])
end
if final_states == nil then
final_states = states
end
return final_states, context
end
--[[ Backward pass (only called during training)
Parameters:
* `batch` - must be same as for forward
* `grad_states_output` gradient of loss wrt last state
* `grad_context_output` - gradient of loss wrt full context.
Returns: nil
--]]
function Encoder:backward(batch, grad_states_output, grad_context_output)
-- TODO: change this to (input, gradOutput) as in nngraph.
local output_size = self.args.rnn_size
if self.gradOutputsProto == nil then
self.gradOutputsProto = utils.Tensor.initTensorTable(self.args.num_effective_layers,
self.gradOutputProto,
{ batch.size, output_size })
end
local grad_states_input = utils.Tensor.copyTensorTable(self.gradOutputsProto, grad_states_output)
local gradInput = {}
for t = batch.source_length, 1, -1 do
-- Add context gradients to last hidden states gradients.
grad_states_input[#grad_states_input]:add(grad_context_output[{{}, t}])
local grad_input = self:net(t):backward(self.inputs[t], grad_states_input)
-- Prepare next encoder output gradients.
for i = 1, #grad_states_input do
grad_states_input[i]:copy(grad_input[i])
end
gradInput[t] = grad_states_input[#grad_states_input]:clone()
end
-- TODO: make these names clearer.
-- Useful if input came from another network.
return gradInput
end
|
--[[ Encoder is a unidirectional Sequencer used for the source language.
h_1 => h_2 => h_3 => ... => h_n
| | | |
. . . .
| | | |
h_1 => h_2 => h_3 => ... => h_n
| | | |
| | | |
x_1 x_2 x_3 x_n
Inherits from [onmt.Sequencer](lib+onmt+Sequencer).
--]]
local Encoder, parent = torch.class('onmt.Encoder', 'onmt.Sequencer')
--[[ Construct an encoder layer.
Parameters:
* `input_network` - input module.
* `rnn` - recurrent module.
]]
function Encoder:__init(input_network, rnn)
self.rnn = rnn
self.inputNet = input_network
self.inputNet.name = 'input_network'
self.args = {}
self.args.rnn_size = self.rnn.output_size
self.args.num_effective_layers = self.rnn.num_effective_layers
parent.__init(self, self:_buildModel())
self:resetPreallocation()
end
function Encoder.load(pretrained)
local self = torch.factory('onmt.Encoder')()
self.args = pretrained.args
parent.__init(self, pretrained.modules[1])
self.network:apply(function (m)
if m.name == 'input_network' then
self.inputNet = m
end
end)
self:resetPreallocation()
return self
end
--[[ Return data to serialize. ]]
function Encoder:serialize()
return {
modules = self.modules,
args = self.args
}
end
function Encoder:resetPreallocation()
-- Prototype for preallocated hidden and cell states.
self.stateProto = torch.Tensor()
-- Prototype for preallocated output gradients.
self.gradOutputProto = torch.Tensor()
-- Prototype for preallocated context vector.
self.contextProto = torch.Tensor()
end
function Encoder:maskPadding()
self.mask_padding = true
end
--[[ Build one time-step of an encoder
Returns: An nn-graph mapping
$${(c^1_{t-1}, h^1_{t-1}, .., c^L_{t-1}, h^L_{t-1}, x_t) =>
(c^1_{t}, h^1_{t}, .., c^L_{t}, h^L_{t})}$$
Where $$c^l$$ and $$h^l$$ are the hidden and cell states at each layer,
$$x_t$$ is a sparse word to lookup.
--]]
function Encoder:_buildModel()
local inputs = {}
local states = {}
-- Inputs are previous layers first.
for _ = 1, self.args.num_effective_layers do
local h0 = nn.Identity()() -- batch_size x rnn_size
table.insert(inputs, h0)
table.insert(states, h0)
end
-- Input word.
local x = nn.Identity()() -- batch_size
table.insert(inputs, x)
-- Compute input network.
local input = self.inputNet(x)
table.insert(states, input)
-- Forward states and input into the RNN.
local outputs = self.rnn(states)
return nn.gModule(inputs, { outputs })
end
function Encoder:shareInput(other)
self.inputNet:share(other.inputNet, 'weight', 'gradWeight')
end
--[[Compute the context representation of an input.
Parameters:
* `batch` - a [batch struct](lib+data/#opennmtdata) as defined data.lua.
Returns:
1. - final hidden states
2. - context matrix H
--]]
function Encoder:forward(batch)
-- TODO: Change `batch` to `input`.
local final_states
local output_size = self.args.rnn_size
if self.statesProto == nil then
self.statesProto = utils.Tensor.initTensorTable(self.args.num_effective_layers,
self.stateProto,
{ batch.size, output_size })
end
-- Make initial states h_0.
local states = utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, output_size })
-- Preallocated output matrix.
local context = utils.Tensor.reuseTensor(self.contextProto,
{ batch.size, batch.source_length, output_size })
if self.mask_padding and not batch.source_input_pad_left then
final_states = utils.Tensor.recursiveClone(states)
end
if self.train then
self.inputs = {}
end
-- Act like nn.Sequential and call each clone in a feed-forward
-- fashion.
for t = 1, batch.source_length do
-- Construct "inputs". Prev states come first then source.
local inputs = {}
utils.Table.append(inputs, states)
table.insert(inputs, batch:get_source_input(t))
if self.train then
-- Remember inputs for the backward pass.
self.inputs[t] = inputs
end
states = self:net(t):forward(inputs)
-- Special case padding.
if self.mask_padding then
for b = 1, batch.size do
if batch.source_input_pad_left and t <= batch.source_length - batch.source_size[b] then
for j = 1, #states do
states[j][b]:zero()
end
elseif not batch.source_input_pad_left and t == batch.source_size[b] then
for j = 1, #states do
final_states[j][b]:copy(states[j][b])
end
end
end
end
-- Copy output (h^L_t = states[#states]) to context.
context[{{}, t}]:copy(states[#states])
end
if final_states == nil then
final_states = states
end
return final_states, context
end
--[[ Backward pass (only called during training)
Parameters:
* `batch` - must be same as for forward
* `grad_states_output` gradient of loss wrt last state
* `grad_context_output` - gradient of loss wrt full context.
Returns: nil
--]]
function Encoder:backward(batch, grad_states_output, grad_context_output)
-- TODO: change this to (input, gradOutput) as in nngraph.
local output_size = self.args.rnn_size
if self.gradOutputsProto == nil then
self.gradOutputsProto = utils.Tensor.initTensorTable(self.args.num_effective_layers,
self.gradOutputProto,
{ batch.size, output_size })
end
local grad_states_input = utils.Tensor.copyTensorTable(self.gradOutputsProto, grad_states_output)
local gradInput = {}
for t = batch.source_length, 1, -1 do
-- Add context gradients to last hidden states gradients.
grad_states_input[#grad_states_input]:add(grad_context_output[{{}, t}])
local grad_input = self:net(t):backward(self.inputs[t], grad_states_input)
-- Prepare next encoder output gradients.
for i = 1, #grad_states_input do
grad_states_input[i]:copy(grad_input[i])
end
gradInput[t] = grad_states_input[#grad_states_input]:clone()
end
-- TODO: make these names clearer.
-- Useful if input came from another network.
return gradInput
end
|
fix brnn parameters sharing when retraining
|
fix brnn parameters sharing when retraining
|
Lua
|
mit
|
jsenellart/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,srush/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,cservan/OpenNMT_scores_0.2.0,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT
|
99662a535a5969a1b38a7a2f7b436c62873fb3e4
|
modules/title/post/olds.lua
|
modules/title/post/olds.lua
|
local sql = require'lsqlite3'
local date = require'date'
local patterns = {
-- X://Y url
"^(https?://%S+)",
"^<(https?://%S+)>",
"%f[%S](https?://%S+)",
-- www.X.Y url
"^(www%.[%w_-%%]+%.%S+)",
"%f[%S](www%.[%w_-%%]+%.%S+)",
}
local openDB = function()
local dbfilename = string.format("cache/urls.%s.sql", ivar2.network)
local db = sql.open(dbfilename)
db:exec([[
CREATE TABLE IF NOT EXISTS urls (
nick text,
timestamp integer,
url text,
channel text
);
]])
return db
end
-- check for existing url
local checkOld = function(source, destination, url)
local db = openDB()
-- create a select handle
local sth = db:prepare([[
SELECT
nick,
timestamp
FROM urls
WHERE
url=?
AND
channel=?
ORDER BY timestamp ASC
]])
-- execute select with a url bound to variable
sth:bind_values(url, destination)
local count, first = 0
while(sth:step() == sql.ROW) do
count = count + 1
if(count == 1) then
first = sth:get_named_values()
end
end
sth:finalize()
db:close()
if(count > 0) then
local age = date.relativeTimeShort(first.timestamp)
return first.nick, count, age
end
end
local updateDB = function(source, destination, url)
local db = openDB()
local sth = db:prepare[[
INSERT INTO urls(nick, channel, url, timestamp)
values(?, ?, ?, ?)
]]
sth:bind_values(source.nick, destination, url, os.time())
sth:step()
sth:finalize()
end
do
return function(source, destination, queue)
local nick, count, age = checkOld(source, destination, queue.url)
updateDB(source, destination, queue.url)
-- relativeTimeShort() returns nil if it gets fed os.time().
if(not age) then return end
local prepend
if(count > 1) then
prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age)
else
prepend = string.format("Old! Linked by %s %s ago", nick, age)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
|
local sql = require'lsqlite3'
local date = require'date'
local uri = require"handler.uri"
local uri_parse = uri.parse
local patterns = {
-- X://Y url
"^(https?://%S+)",
"^<(https?://%S+)>",
"%f[%S](https?://%S+)",
-- www.X.Y url
"^(www%.[%w_-%%]+%.%S+)",
"%f[%S](www%.[%w_-%%]+%.%S+)",
}
local openDB = function()
local dbfilename = string.format("cache/urls.%s.sql", ivar2.network)
local db = sql.open(dbfilename)
db:exec([[
CREATE TABLE IF NOT EXISTS urls (
nick text,
timestamp integer,
url text,
channel text
);
]])
return db
end
-- check for existing url
local checkOld = function(source, destination, url)
-- Don't lookup root path URLs.
local info = uri_parse(url)
if(info.path == '' or info.path == '/') then
return
end
local db = openDB()
-- create a select handle
local sth = db:prepare([[
SELECT
nick,
timestamp
FROM urls
WHERE
url=?
AND
channel=?
ORDER BY timestamp ASC
]])
-- execute select with a url bound to variable
sth:bind_values(url, destination)
local count, first = 0
while(sth:step() == sql.ROW) do
count = count + 1
if(count == 1) then
first = sth:get_named_values()
end
end
sth:finalize()
db:close()
if(count > 0) then
local age = date.relativeTimeShort(first.timestamp)
return first.nick, count, age
end
end
local updateDB = function(source, destination, url)
local db = openDB()
local sth = db:prepare[[
INSERT INTO urls(nick, channel, url, timestamp)
values(?, ?, ?, ?)
]]
sth:bind_values(source.nick, destination, url, os.time())
sth:step()
sth:finalize()
end
do
return function(source, destination, queue)
local nick, count, age = checkOld(source, destination, queue.url)
updateDB(source, destination, queue.url)
-- relativeTimeShort() returns nil if it gets fed os.time().
if(not age) then return end
local prepend
if(count > 1) then
prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age)
else
prepend = string.format("Old! Linked by %s %s ago", nick, age)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
|
title/olds: Don't lookup rooth path URLs.
|
title/olds: Don't lookup rooth path URLs.
Fixes #46.
Former-commit-id: 3d7ae5510fa00acb45006848621162ab68bd5e29 [formerly 35eec07d55e7ed36e05f894bf6f7f65162841ff9]
Former-commit-id: 96df969196a36714a8092e321517d75523457016
|
Lua
|
mit
|
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
|
3203b8fe7ea8ddf36c3211262854032f1ad628ac
|
bot.lua
|
bot.lua
|
local bot = {}
-- Requires are moved to init to allow for reloads.
local bindings -- Load Telegram bindings.
local utilities -- Load miscellaneous and cross-plugin functions.
bot.version = '3.7'
function bot:init() -- The function run when the bot is started or reloaded.
bindings = require('bindings')
utilities = require('utilities')
self.config = require('config') -- Load configuration file.
self.BASE_URL = 'https://api.telegram.org/bot' .. self.config.bot_api_key
if self.config.bot_api_key == '' then
error('You did not set your bot token in config.lua!')
end
-- Fetch bot information. Try until it succeeds.
repeat
print('Fetching bot information...')
self.info = bindings.getMe(self)
until self.info
self.info = self.info.result
-- Load the "database"! ;)
if not self.database then
self.database = utilities.load_data(self.info.username..'.db')
end
self.plugins = {} -- Load plugins.
for _,v in ipairs(self.config.plugins) do
local p = require('plugins.'..v)
table.insert(self.plugins, p)
if p.init then p.init(self) end
end
print('@' .. self.info.username .. ', AKA ' .. self.info.first_name ..' ('..self.info.id..')')
self.last_update = self.last_update or 0 -- Set loop variables: Update offset,
self.last_cron = self.last_cron or os.date('%M') -- the time of the last cron job,
self.is_started = true -- and whether or not the bot should be running.
self.database.users = self.database.users or {} -- Table to cache userdata.
self.database.users[tostring(self.info.id)] = self.info
end
function bot:on_msg_receive(msg) -- The fn run whenever a message is received.
-- Cache user info for those involved.
utilities.create_user_entry(self, msg.from)
if msg.forward_from and msg.forward_from.id ~= msg.from.id then
utilities.create_user_entry(self, msg.forward_from)
elseif msg.reply_to_message and msg.reply_to_message.from.id ~= msg.from.id then
utilities.create_user_entry(self, msg.reply_to_message.from)
end
if msg.date < os.time() - 5 then return end -- Do not process old messages.
msg = utilities.enrich_message(msg)
if msg.text:match('^/start .+') then
msg.text = '/' .. utilities.input(msg.text)
msg.text_lower = msg.text:lower()
end
for _,v in ipairs(self.plugins) do
for _,w in pairs(v.triggers) do
if string.match(msg.text:lower(), w) then
local success, result = pcall(function()
return v.action(self, msg)
end)
if not success then
bindings.sendReply(self, msg, 'Sorry, an unexpected error occurred.')
utilities.handle_exception(self, result, msg.from.id .. ': ' .. msg.text)
return
end
-- If the action returns a table, make that table the new msg.
if type(result) == 'table' then
msg = result
-- If the action returns true, continue.
elseif result ~= true then
return
end
end
end
end
end
function bot:run()
bot.init(self) -- Actually start the script. Run the bot_init function.
while self.is_started do -- Start a loop while the bot should be running.
do
local res = bindings.getUpdates(self, self.last_update+1) -- Get the latest updates!
if res then
for _,v in ipairs(res.result) do -- Go through every new message.
self.last_update = v.update_id
bot.on_msg_receive(self, v.message)
end
else
print(self.config.errors.connection)
end
end
if self.last_cron ~= os.date('%M') then -- Run cron jobs every minute.
self.last_cron = os.date('%M')
utilities.save_data(self.info.username..'.db', self.database) -- Save the database.
for i,v in ipairs(self.plugins) do
if v.cron then -- Call each plugin's cron function, if it has one.
local res, err = pcall(function() v.cron(self) end)
if not res then
utilities.handle_exception(self, err, 'CRON: ' .. i)
end
end
end
end
end
-- Save the database before exiting.
utilities.save_data(self.info.username..'.db', self.database)
print('Halted.')
end
return bot
|
local bot = {}
-- Requires are moved to init to allow for reloads.
local bindings -- Load Telegram bindings.
local utilities -- Load miscellaneous and cross-plugin functions.
bot.version = '3.7'
function bot:init() -- The function run when the bot is started or reloaded.
bindings = require('bindings')
utilities = require('utilities')
self.config = require('config') -- Load configuration file.
self.BASE_URL = 'https://api.telegram.org/bot' .. self.config.bot_api_key
if self.config.bot_api_key == '' then
error('You did not set your bot token in config.lua!')
end
-- Fetch bot information. Try until it succeeds.
repeat
print('Fetching bot information...')
self.info = bindings.getMe(self)
until self.info
self.info = self.info.result
-- Load the "database"! ;)
if not self.database then
self.database = utilities.load_data(self.info.username..'.db')
end
self.plugins = {} -- Load plugins.
for _,v in ipairs(self.config.plugins) do
local p = require('plugins.'..v)
table.insert(self.plugins, p)
if p.init then p.init(self) end
end
print('@' .. self.info.username .. ', AKA ' .. self.info.first_name ..' ('..self.info.id..')')
self.last_update = self.last_update or 0 -- Set loop variables: Update offset,
self.last_cron = self.last_cron or os.date('%M') -- the time of the last cron job,
self.is_started = true -- and whether or not the bot should be running.
self.database.users = self.database.users or {} -- Table to cache userdata.
self.database.users[tostring(self.info.id)] = self.info
end
function bot:on_msg_receive(msg) -- The fn run whenever a message is received.
-- Cache user info for those involved.
utilities.create_user_entry(self, msg.from)
if msg.forward_from and msg.forward_from.id ~= msg.from.id then
utilities.create_user_entry(self, msg.forward_from)
elseif msg.reply_to_message and msg.reply_to_message.from.id ~= msg.from.id then
utilities.create_user_entry(self, msg.reply_to_message.from)
end
if msg.date < os.time() - 5 then return end -- Do not process old messages.
msg = utilities.enrich_message(msg)
if msg.text:match('^/start .+') then
msg.text = '/' .. utilities.input(msg.text)
msg.text_lower = msg.text:lower()
end
for _,v in ipairs(self.plugins) do
for _,w in pairs(v.triggers) do
if string.match(msg.text:lower(), w) then
local success, result = pcall(function()
return v.action(self, msg)
end)
if not success then
bindings.sendReply(self, msg, 'Sorry, an unexpected error occurred.')
utilities.handle_exception(self, result, msg.from.id .. ': ' .. msg.text)
return
end
-- If the action returns a table, make that table the new msg.
if type(result) == 'table' then
msg = result
-- If the action returns true, continue.
elseif result ~= true then
return
end
end
end
end
end
function bot:run()
bot.init(self) -- Actually start the script. Run the bot_init function.
while self.is_started do -- Start a loop while the bot should be running.
local res = bindings.getUpdates(self, self.last_update+1) -- Get the latest updates!
if res then
for _,v in ipairs(res.result) do -- Go through every new message.
self.last_update = v.update_id
if v.message then
bot.on_msg_receive(self, v.message)
end
end
else
print(self.config.errors.connection)
end
if self.last_cron ~= os.date('%M') then -- Run cron jobs every minute.
self.last_cron = os.date('%M')
utilities.save_data(self.info.username..'.db', self.database) -- Save the database.
for i,v in ipairs(self.plugins) do
if v.cron then -- Call each plugin's cron function, if it has one.
local res, err = pcall(function() v.cron(self) end)
if not res then
utilities.handle_exception(self, err, 'CRON: ' .. i)
end
end
end
end
end
-- Save the database before exiting.
utilities.save_data(self.info.username..'.db', self.database)
print('Halted.')
end
return bot
|
Fix for the latest API update.
|
Fix for the latest API update.
|
Lua
|
mit
|
barreeeiroo/BarrePolice,topkecleon/otouto,Brawl345/Brawlbot-v2,bb010g/otouto
|
58c5e35a4c529ec7de3aecd6c84383f98c4cabe8
|
lualib/saux/msg.lua
|
lualib/saux/msg.lua
|
local core = require "silly.core"
local np = require "netpacket"
local TAG = "saux.msg"
local msg = {}
local msgserver = {}
local msgclient = {}
local function gc(obj)
if not obj.fd then
return
end
if obj.fd < 0 then
return
end
core.close(obj.fd, TAG)
obj.fd = false
end
local servermt = {__index = msgserver, __gc == gc}
local clientmt = {__index = msgclient, __gc == gc}
---server
local function servercb(sc)
local EVENT = {}
local queue = np.create()
function EVENT.accept(fd, portid, addr)
local ok, err = core.pcall(sc.accept, fd, addr)
if not ok then
print("[msg] EVENT.accept", err)
core.close(fd, TAG)
end
end
function EVENT.close(fd, errno)
local ok, err = core.pcall(assert(sc).close, fd, errno)
if not ok then
print("[msg] EVENT.close", err)
end
end
function EVENT.data()
local f, d, sz = np.pop(queue)
if not f then
return
end
core.fork(EVENT.data)
local ok, err = core.pcall(sc.data, f, d, sz)
if not ok then
print("[msg] dispatch socket", err)
end
end
return function (type, fd, message, ...)
queue = np.message(queue, message)
assert(EVENT[type])(fd, ...)
end
end
local function sendmsg(self, fd, data)
return core.write(fd, np.pack(data))
end
msgserver.send = sendmsg
function msgserver.start(self)
local fd = core.listen(self.addr, servercb(self), TAG)
self.fd = fd
return fd
end
function msgserver.stop(self)
gc(self)
end
function msgserver.close(self, fd)
core.close(fd, TAG)
end
-----client
local function clientcb(sc)
local EVENT = {}
local queue = np.create()
sc.queuedat = {}
function EVENT.accept(fd, portid, addr)
assert(not "never come here")
end
function EVENT.close(fd, errno)
local ok, err = core.pcall(assert(sc).close, fd, errno)
sc.fd = false
if not ok then
print("[msg] EVENT.close", err)
end
end
function EVENT.data()
local f, d, sz = np.pop(queue)
if not f then
return
end
core.fork(EVENT.data)
local ok, err = core.pcall(assert(sc).data, f, d, sz)
if not ok then
print("[msg] EVENT.data", err)
end
end
return function (type, fd, message, ...)
queue = np.message(queue, message)
assert(EVENT[type])(fd, ...)
end
end
local function wakeupall(self)
local q = self.connectqueue
for k, v in pairs(q) do
core.wakeup(v)
q[k] = nil
end
end
local function checkconnect(self)
if self.fd and self.fd >= 0 then
return self.fd
end
if not self.fd then --disconnected
self.fd = -1
local fd = core.connect(self.addr, clientcb(self), nil, TAG)
if not fd then
self.fd = false
else
self.fd = fd
end
wakeupall(self)
return self.fd
else
local co = core.running()
local t = self.connectqueue
t[#t + 1] = co
core.wait()
return self.fd and self.fd > 0
end
end
function msgclient.close(self)
gc(self)
end
function msgclient.send(self, data)
local fd = checkconnect(self)
if not fd then
return false
end
return sendmsg(self, fd, data)
end
function msgclient.connect(self)
local fd = checkconnect(self)
return fd
end
function msg.createclient(config)
local obj = {
fd = false,
connectqueue = {},
}
for k, v in pairs(config) do
assert(not obj[k])
obj[k] = v
end
setmetatable(obj, clientmt)
return obj
end
function msg.createserver(config)
local obj = {
fd = false,
}
for k, v in pairs(config) do
obj[k] = v
end
setmetatable(obj, servermt)
return obj
end
return msg
|
local core = require "silly.core"
local np = require "netpacket"
local TAG = "saux.msg"
local msg = {}
local msgserver = {}
local msgclient = {}
local function gc(obj)
if not obj.fd then
return
end
if obj.fd < 0 then
return
end
core.close(obj.fd, TAG)
obj.fd = false
end
local servermt = {__index = msgserver, __gc == gc}
local clientmt = {__index = msgclient, __gc == gc}
---server
local function servercb(sc, config)
local EVENT = {}
local queue = np.create()
local accept_cb = assert(config.accept, "servercb accept")
local close_cb = assert(config.close, "servercb close")
local data_cb = assert(config.data, "servercb data")
function EVENT.accept(fd, portid, addr)
local ok, err = core.pcall(accept_cb, fd, addr)
if not ok then
print("[msg] EVENT.accept", err)
core.close(fd, TAG)
end
end
function EVENT.close(fd, errno)
local ok, err = core.pcall(close_cb, fd, errno)
if not ok then
print("[msg] EVENT.close", err)
end
end
function EVENT.data()
local f, d, sz = np.pop(queue)
if not f then
return
end
core.fork(EVENT.data)
local ok, err = core.pcall(data_cb, f, d, sz)
if not ok then
print("[msg] dispatch socket", err)
end
end
return function (type, fd, message, ...)
queue = np.message(queue, message)
assert(EVENT[type])(fd, ...)
end
end
local function sendmsg(self, fd, data)
return core.write(fd, np.pack(data))
end
msgserver.send = sendmsg
function msgserver.start(self)
local fd = core.listen(self.addr, self.callback, TAG)
self.fd = fd
return fd
end
function msgserver.stop(self)
gc(self)
end
function msgserver.close(self, fd)
core.close(fd, TAG)
end
-----client
local function clientcb(sc, config)
local EVENT = {}
local queue = np.create()
sc.queuedat = {}
local close_cb = assert(config.close, "clientcb close")
local data_cb = assert(config.data, "clientcb data")
function EVENT.accept(fd, portid, addr)
assert(not "never come here")
end
function EVENT.close(fd, errno)
local ok, err = core.pcall(close_cb, fd, errno)
sc.fd = false
if not ok then
print("[msg] EVENT.close", err)
end
end
function EVENT.data()
local f, d, sz = np.pop(queue)
if not f then
return
end
core.fork(EVENT.data)
local ok, err = core.pcall(data_cb, f, d, sz)
if not ok then
print("[msg] EVENT.data", err)
end
end
return function (type, fd, message, ...)
queue = np.message(queue, message)
assert(EVENT[type])(fd, ...)
end
end
local function wakeupall(self)
local q = self.connectqueue
for k, v in pairs(q) do
core.wakeup(v)
q[k] = nil
end
end
local function checkconnect(self)
if self.fd and self.fd >= 0 then
return self.fd
end
if not self.fd then --disconnected
self.fd = -1
local fd = core.connect(self.addr, self.callback, nil, TAG)
if not fd then
self.fd = false
else
self.fd = fd
end
wakeupall(self)
return self.fd
else
local co = core.running()
local t = self.connectqueue
t[#t + 1] = co
core.wait()
return self.fd and self.fd > 0
end
end
function msgclient.close(self)
gc(self)
end
function msgclient.send(self, data)
local fd = checkconnect(self)
if not fd then
return false
end
return sendmsg(self, fd, data)
end
function msgclient.connect(self)
local fd = checkconnect(self)
return fd
end
function msg.createclient(config)
local obj = {
fd = false,
addr = config.addr,
callback = false,
connectqueue = {},
}
obj.callback = clientcb(obj, config),
setmetatable(obj, clientmt)
return obj
end
function msg.createserver(config)
local obj = {
fd = false,
addr = config.addr,
callback = false,
}
obj.callback = servercb(obj, config)
setmetatable(obj, servermt)
return obj
end
return msg
|
bugfix: saux.msg.close
|
bugfix: saux.msg.close
saux.msg.close conflict with EVENT.close
|
Lua
|
mit
|
findstr/silly
|
184d9e3f334e4f036e8fa8dc12d1d7a12bc76145
|
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_hutt_hideout.lua
|
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_hutt_hideout.lua
|
HuttHideoutScreenPlay = ScreenPlay:new {
numberOfActs = 1,
lootContainers = {
134411,
8496263,
8496262,
8496260
},
lootLevel = 32,
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 200000},
{group = "junk", chance = 6800000},
{group = "rifles", chance = 1000000},
{group = "pistols", chance = 1000000},
{group = "clothing_attachments", chance = 500000},
{group = "armor_attachments", chance = 500000}
},
lootChance = 4000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("HuttHideoutScreenPlay", true)
function HuttHideoutScreenPlay:start()
self:spawnMobiles()
self:initializeLootContainers()
end
function HuttHideoutScreenPlay:spawnMobiles()
spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585)
spawnMobile("tatooine", "jabba_henchman", 200, 1.1, -14.4, -9.3, 15, 4235585)
spawnMobile("tatooine", "jabba_compound_guard", 200, -12.1, -32.2, -34, 19, 4235586)
spawnMobile("tatooine", "jabba_enforcer", 200, -10.5, -40.4, -81.3, -178, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 5.8, -40.9, -79.6, -37, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 14.5, -40.5, -74.2, -131, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 20, -39.6, -77.9, -50, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 10.7, -41.1, -60.3, -124, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 47, -46.7, -50.8, -163, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 50.4, -46.8, -58.6, -19, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 51.6, -46, -91.6, -126, 4235588)
spawnMobile("tatooine", "jabba_enforcer", 200, 47.1, -46.2, -96.3, 46, 4235588)
spawnMobile("tatooine", "jabba_compound_guard", 200, 44.9, -46.2, -102.8, -41, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 13.9, -45, -121.1, 30, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 1.5, -45, -141.6, 117, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -10, -45.6, -148, 26, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -12.4, -45, -130.8, 125, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 58.8, -47.1, -124.6, -21, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 73.5, -52.9, -144.7, -178, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 72.5, -54.4, -151.6, -20, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 38.2, -55.7, -155.4, -78, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 36.9, -56.1, -157.2, -53, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 67.5, -57.3, -176.7, 62, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 58.6, -57.7, -185.3, -70, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 53, -57, -185.3, 59, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 58.8, -56.4, -159.5, -60, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 53.3, -56.6, -160.2, 45, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 6, -63.9, -181.8, 90, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -8.1, -65.1, -201.3, -10, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -37.5, -67, -182.8, 91, 4235590)
spawnMobile("tatooine", "jabba_henchman", 200, -18.7, -65.5, -210.3, -152, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -22.5, -64.6, -220.2, -131, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -17.6, -65.4, -216.8, -7, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -4.8, -64.2, -231.5, 178, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -1.3, -64.2, -238.5, 88, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -224, -65, -249.8, -174, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -19.3, -62.6, -261.6, 43, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -10.6, -63.3, -261.2, -77, 4235591)
end
function HuttHideoutScreenPlay:initializeLootContainers()
for k,v in pairs(self.lootContainers) do
local pContainer = getSceneObject(v)
createObserver(OPENCONTAINER, "HuttHideoutScreenPlay", "spawnContainerLoot", pContainer)
self:spawnContainerLoot(pContainer)
end
end
function HuttHideoutScreenPlay:spawnContainerLoot(pContainer)
if (pContainer == nil) then
return
end
local container = LuaSceneObject(pContainer)
local time = getTimestamp()
if (readData(container:getObjectID()) > time) then
return
end
--If it has loot already, then exit.
if (container:getContainerObjectsSize() > 0) then
return
end
createLootFromCollection(pContainer, self.lootGroups, self.lootLevel)
writeData(container:getObjectID(), time + self.lootContainerRespawn)
end
|
HuttHideoutScreenPlay = ScreenPlay:new {
numberOfActs = 1,
lootContainers = {
134411,
8496263,
8496262,
8496261,
8496260
},
lootLevel = 26,
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 160000},
{group = "junk", chance = 8600000},
{group = "rifles", chance = 500000},
{group = "pistols", chance = 500000},
{group = "clothing_attachments", chance = 300000},
{group = "armor_attachments", chance = 300000}
},
lootChance = 8000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("HuttHideoutScreenPlay", true)
function HuttHideoutScreenPlay:start()
self:spawnMobiles()
self:initializeLootContainers()
end
function HuttHideoutScreenPlay:spawnMobiles()
spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585)
spawnMobile("tatooine", "jabba_henchman", 200, 1.1, -14.4, -9.3, 15, 4235585)
spawnMobile("tatooine", "jabba_compound_guard", 200, -12.1, -32.2, -34, 19, 4235586)
spawnMobile("tatooine", "jabba_enforcer", 200, -10.5, -40.4, -81.3, -178, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 5.8, -40.9, -79.6, -37, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 14.5, -40.5, -74.2, -131, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 20, -39.6, -77.9, -50, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 10.7, -41.1, -60.3, -124, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 47, -46.7, -50.8, -163, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 50.4, -46.8, -58.6, -19, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 51.6, -46, -91.6, -126, 4235588)
spawnMobile("tatooine", "jabba_enforcer", 200, 47.1, -46.2, -96.3, 46, 4235588)
spawnMobile("tatooine", "jabba_compound_guard", 200, 44.9, -46.2, -102.8, -41, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 13.9, -45, -121.1, 30, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 1.5, -45, -141.6, 117, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -10, -45.6, -148, 26, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -12.4, -45, -130.8, 125, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 58.8, -47.1, -124.6, -21, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 73.5, -52.9, -144.7, -178, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 72.5, -54.4, -151.6, -20, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 38.2, -55.7, -155.4, -78, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 36.9, -56.1, -157.2, -53, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 67.5, -57.3, -176.7, 62, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 58.6, -57.7, -185.3, -70, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 53, -57, -185.3, 59, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 58.8, -56.4, -159.5, -60, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 53.3, -56.6, -160.2, 45, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 6, -63.9, -181.8, 90, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -8.1, -65.1, -201.3, -10, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -37.5, -67, -182.8, 91, 4235590)
spawnMobile("tatooine", "jabba_henchman", 200, -18.7, -65.5, -210.3, -152, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -22.5, -64.6, -220.2, -131, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -17.6, -65.4, -216.8, -7, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -4.8, -64.2, -231.5, 178, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -1.3, -64.2, -238.5, 88, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -224, -65, -249.8, -174, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -19.3, -62.6, -261.6, 43, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -10.6, -63.3, -261.2, -77, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -57.1, -70.2, -193, -70, 4235592)
spawnMobile("tatooine", "jabba_compound_guard", 200, -71.8, -68.6, -182.3, 99, 4235592)
spawnMobile("tatooine", "jabba_henchman", 200, -59.3, -69.8, -170.9, -53, 4235592)
spawnMobile("tatooine", "jabba_enforcer", 200, -71.5, -70, -166.7, 141, 4235592)
spawnMobile("tatooine", "jabba_assassin", 200, -98.3, -72.4, -174.9, 72, 4235592)
spawnMobile("tatooine", "jabba_henchman", 200, -112.2, -69.1, -119.7, 84, 4235592)
spawnMobile("tatooine", "jabba_enforcer", 200, -106.1, -68.6, -112.2, -76, 4235592)
spawnMobile("tatooine", "jabba_assassin", 200, -84.2, -70.3, -129.7, 83, 4235592)
spawnMobile("tatooine", "jabba_enforcer", 200, -94.9, -102.6, -137.2, 154, 4235592)
spawnMobile("tatooine", "jabba_enforcer", 200, -95.6, -102.1, -140.6, 0, 4235592)
spawnMobile("tatooine", "jabba_henchman", 200, -51.4, -68.9, -95.4, 135, 4235593)
spawnMobile("tatooine", "jabba_enforcer", 200, -47.6, -69.3, -95.4, -133, 4235593)
spawnMobile("tatooine", "jabba_enforcer", 200, -46.3, -69.3, -99, -52, 4235593)
spawnMobile("tatooine", "jabba_compound_guard", 200, -59.4, -70.1, -88, -179, 4235593)
spawnMobile("tatooine", "jabba_henchman", 200, -69.4, -68.5, -101.7, 110, 4235593)
spawnMobile("tatooine", "jabba_compound_guard", 200, -65.6, -68.3, -103.1, -74, 4235593)
spawnMobile("tatooine", "jabba_assassin", 200, -8.6, -68.6, -97.1, -162, 4235593)
spawnMobile("tatooine", "jabba_compound_guard", 200, -32.1, -80.2, -143.5, 80, 4235594)
spawnMobile("tatooine", "jabba_henchman", 200, -19.7, -79.8, -146.9, -59, 4235594)
spawnMobile("tatooine", "jabba_henchman", 200, -21.2, -79.6, -143.8, 160, 4235594)
spawnMobile("tatooine", "jabba_compound_guard", 200, -79, -100.9, -130, -100, 4235595)
spawnMobile("tatooine", "jabba_assassin", 200, -83.8, -100.6, -106.6, -1, 4235595)
spawnMobile("tatooine", "jabba_enforcer", 200, -86.4, -100.5, -103.6, 123, 4235595)
spawnMobile("tatooine", "jabba_assassin", 200, -100.4, -99.9, -114.2, 162, 4235595)
spawnMobile("tatooine", "jabba_enforcer", 200, -98.3, -100, -105.2, -43, 4235595)
end
function HuttHideoutScreenPlay:initializeLootContainers()
for k,v in pairs(self.lootContainers) do
local pContainer = getSceneObject(v)
createObserver(OPENCONTAINER, "HuttHideoutScreenPlay", "spawnContainerLoot", pContainer)
self:spawnContainerLoot(pContainer)
end
end
function HuttHideoutScreenPlay:spawnContainerLoot(pContainer)
if (pContainer == nil) then
return
end
local container = LuaSceneObject(pContainer)
local time = getTimestamp()
if (readData(container:getObjectID()) > time) then
return
end
--If it has loot already, then exit.
if (container:getContainerObjectsSize() > 0) then
return
end
createLootFromCollection(pContainer, self.lootGroups, self.lootLevel)
writeData(container:getObjectID(), time + self.lootContainerRespawn)
end
|
(unstable) [fixed] Finished spawns and containers in Hutt Hideout cave.
|
(unstable) [fixed] Finished spawns and containers in Hutt Hideout cave.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5498 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
d0ff07d2624a2c216900284da9ba8643e1dc9106
|
build/scripts/tools/ndk_server.lua
|
build/scripts/tools/ndk_server.lua
|
TOOL.Name = "SDKServer"
TOOL.Directory = "../SDK/lib"
TOOL.Kind = "Library"
TOOL.Defines = {
"NDK_BUILD",
"NDK_SERVER"
}
TOOL.Includes = {
"../SDK/include"
}
TOOL.Files = {
"../SDK/include/NDK/**.hpp",
"../SDK/include/NDK/**.inl",
"../SDK/src/NDK/**.hpp",
"../SDK/src/NDK/**.inl",
"../SDK/src/NDK/**.cpp"
}
-- Exlude client-only files
TOOL.FilesExclusion = {
"../SDK/**/CameraComponent.*",
"../SDK/**/GraphicsComponent.*",
"../SDK/**/LightComponent.*",
"../SDK/**/ListenerComponent.*",
"../SDK/**/ListenerSystem.*",
"../SDK/**/RenderSystem.*",
"../SDK/**/LuaInterface_Audio.*"
}
TOOL.Libraries = {
"NazaraCore",
"NazaraLua",
"NazaraNoise",
"NazaraPhysics",
"NazaraUtility"
}
|
TOOL.Name = "SDKServer"
TOOL.Directory = "../SDK/lib"
TOOL.Kind = "Library"
TOOL.Defines = {
"NDK_BUILD",
"NDK_SERVER"
}
TOOL.Includes = {
"../SDK/include"
}
TOOL.Files = {
"../SDK/include/NDK/**.hpp",
"../SDK/include/NDK/**.inl",
"../SDK/src/NDK/**.hpp",
"../SDK/src/NDK/**.inl",
"../SDK/src/NDK/**.cpp"
}
-- Exlude client-only files
TOOL.FilesExclusion = {
"../SDK/**/CameraComponent.*",
"../SDK/**/Console.*",
"../SDK/**/GraphicsComponent.*",
"../SDK/**/LightComponent.*",
"../SDK/**/ListenerComponent.*",
"../SDK/**/ListenerSystem.*",
"../SDK/**/RenderSystem.*",
"../SDK/**/LuaAPI_Audio.*",
"../SDK/**/LuaAPI_Graphics.*",
}
TOOL.Libraries = {
"NazaraCore",
"NazaraLua",
"NazaraNoise",
"NazaraPhysics",
"NazaraUtility"
}
|
Build/SdkServer: Fix Console.cpp being included in the project
|
Build/SdkServer: Fix Console.cpp being included in the project
Former-commit-id: 62d706654c398a60946282e112d7e139107ac745
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
0f692c7712658e317fd7c46a542ada83612bfe16
|
share/media/liveleak.lua
|
share/media/liveleak.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2013 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local LiveLeak = {} -- Utility functions specific to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = LiveLeak.can_parse_url(qargs),
domains = table.concat({'liveleak.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.title = p:match("<title>LiveLeak.com%s+%-%s+(.-)</") or ''
qargs.id = qargs.input_url:match('view%?i=([%w_]+)') or ''
local d = p:match("setup%((.-)%)%.")
if not d then -- Try the first iframe
qargs.goto_url = p:match('<iframe.-src="(.-)"') or ''
if #qargs.goto_url >0 then
return qargs
else
error('no match: setup')
end
end
-- Cleanup the JSON, otherwise 'json' module will croak.
d = d:gsub('%+encodeURIComponent%(document%.URL%)', '')
local J = require 'json'
local j = J.decode(d)
qargs.thumb_url = j['image'] or ''
qargs.streams = LiveLeak.iter_streams(j)
return qargs
end
--
-- Utility functions
--
function LiveLeak.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('liveleak%.com$')
and t.path and t.path:lower():match('^/view')
and t.query and t.query:lower():match('i=[_%w]+')
then
return true
else
return false
end
end
function LiveLeak.iter_streams(j)
local u = j['file'] or error('no match: media stream URL')
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2013 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local LiveLeak = {} -- Utility functions specific to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = LiveLeak.can_parse_url(qargs),
domains = table.concat({'liveleak.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.title = p:match("<title>LiveLeak.com%s+%-%s+(.-)</") or ''
qargs.id = qargs.input_url:match('view%?i=([%w_]+)') or ''
local d = p:match("setup%((.-)%)%.")
if not d then -- Try the first iframe
qargs.goto_url = p:match('<iframe.-src="(.-)"') or ''
if #qargs.goto_url >0 then
return qargs
else
error('no match: setup')
end
end
-- Cleanup the JSON, otherwise 'json' module will croak.
d = d:gsub('code:.-%),','')
local J = require 'json'
local j = J.decode(d)
qargs.thumb_url = j['image'] or ''
qargs.streams = LiveLeak.iter_streams(j)
return qargs
end
--
-- Utility functions
--
function LiveLeak.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('liveleak%.com$')
and t.path and t.path:lower():match('^/view')
and t.query and t.query:lower():match('i=[_%w]+')
then
return true
else
return false
end
end
function LiveLeak.iter_streams(j)
local u = j['file'] or error('no match: media stream URL')
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/liveleak.lua: Sanitize input for LuaJSON
|
FIX: media/liveleak.lua: Sanitize input for LuaJSON
Otherwise the script will throw an error that looks like:
/usr/share/lua/5.1/json/decode/util.lua:40: unexpected character @
character: 733 17:16 [e] line:
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
|
370bfef803199ca5be55217ddc047b4230057e04
|
check/apache.lua
|
check/apache.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local BaseCheck = require('./base').BaseCheck
local CheckResult = require('./base').CheckResult
local misc = require('virgo/util/misc')
local constants = require('../constants')
local url = require('url')
local http = require('http')
local https = require('https')
local Error = require('core').Error
local fmt = require('string').format
local ApacheCheck = BaseCheck:extend()
function ApacheCheck:initialize(params)
BaseCheck.initialize(self, params)
self._url = params.details.url and params.details.url or 'http://127.0.0.1/server-status?auto'
self._timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
-- setup default port
local parsed = url.parse(self._url)
if not parsed.port then
if parsed.protocol == 'http' then
parsed.port = 80
else
parsed.port = 443
end
end
self._parsed = parsed
self._parsed.path = '/server-status?auto'
end
function ApacheCheck:getType()
return 'agent.apache'
end
-- "_" Waiting for Connection, "S" Starting up, "R" Reading Request,
-- "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
-- "C" Closing connection, "L" Logging, "G" Gracefully finishing,
-- "I" Idle cleanup of worker, "." Open slot with no current process
function ApacheCheck:_parseScoreboard(board)
local t = { waiting = 0, starting = 0, reading = 0, sending = 0,
keepalive = 0, dns = 0, closing = 0, logging = 0,
gracefully_finishing = 0, idle = 0, open = 0 }
for c in board:gmatch"." do
if c == '_' then t.waiting = t.waiting + 1
elseif c == 'S' then t.starting = t.starting + 1
elseif c == 'R' then t.reading = t.reading + 1
elseif c == 'W' then t.sending = t.sending + 1
elseif c == 'K' then t.keepalive = t.keepalive + 1
elseif c == 'D' then t.dns = t.dns + 1
elseif c == 'C' then t.closing = t.closing + 1
elseif c == 'L' then t.logging = t.logging + 1
elseif c == 'G' then t.gracefully_finishing = t.gracefully_finishing + 1
elseif c == 'I' then t.idle = t.idle + 1
elseif c == '.' then t.open = t.open + 1
end
end
return t
end
function ApacheCheck:_parseLine(line, checkResult)
local i = line:find(":")
if not i then
return Error:new('Invalid Apache Status Page')
end
local f = line:sub(0, i-1)
local v = line:sub(i+1, #line)
f = misc.trim(f:gsub(" ", "_"))
v = misc.trim(v)
local metrics = {
['Total_Accesses'] = {
['type'] = 'gauge',
['name'] = 'total_accesses',
['unit'] = 'accesses'
},
['Total_kBytes'] = {
['type'] = 'uint64',
['name'] = 'total_kbytes',
['unit'] = 'kilobytes'
},
['Uptime'] = {
['type'] = 'uint64',
['name'] = 'uptime',
['unit'] = 'milliseconds'
},
['BytesPerSec'] = {
['type'] = 'uint64',
['name'] = 'bytes_per_second',
['unit'] = 'bytes'
},
['BytesPerReq'] = {
['type'] = 'uint64',
['name'] = 'bytes_per_request',
['unit'] = 'bytes'
},
['BusyWorkers'] = {
['type'] = 'uint64',
['name'] = 'busy_workers',
['unit'] = 'workers'
},
['IdleWorkers'] = {
['type'] = 'uint64',
['name'] = 'idle_workers',
['unit'] = 'workers'
},
['CPULoad'] = {
['type'] = 'double',
['name'] = 'cpu_load',
['unit'] = 'percent'
},
['ReqPerSec'] = {
['type'] = 'double',
['name'] = 'requests_per_second',
['unit'] = 'requests'
}
}
if metrics[f] then
checkResult:addMetric(metrics[f].name, nil, metrics[f].type, v)
end
if f == 'ReqPerSec' then
checkResult:setStatus(fmt('Handling %.2f requests per second', v))
end
if f == 'Scoreboard' then
local t = self:_parseScoreboard(v)
for j, x in pairs(t) do
checkResult:addMetric(j, nil, 'uint64', x)
end
end
return
end
function ApacheCheck:_parse(data, checkResult)
for line in data:gmatch("([^\n]*)\n") do
local err = self:_parseLine(line, checkResult)
if err then
checkResult:setError(err.message)
return
end
end
end
function ApacheCheck:run(callback)
callback = misc.fireOnce(callback)
local checkResult = CheckResult:new(self, {})
local protocol = self._parsed.protocol == 'http' and http or https
local req = protocol.request(self._parsed, function(res)
local data = ''
res:on('data', function(_data)
data = data .. _data
end)
res:on('end', function()
self:_parse(data, checkResult)
res:destroy()
callback(checkResult)
end)
res:on('error', function(err)
checkResult:setError(err.message)
callback(checkResult)
end)
end)
req:on('error', function(err)
checkResult:setError(err.message)
callback(checkResult)
end)
req:done()
end
exports.ApacheCheck = ApacheCheck
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local BaseCheck = require('./base').BaseCheck
local CheckResult = require('./base').CheckResult
local misc = require('virgo/util/misc')
local constants = require('../constants')
local url = require('url')
local http = require('http')
local https = require('https')
local Error = require('core').Error
local fmt = require('string').format
local ApacheCheck = BaseCheck:extend()
function ApacheCheck:initialize(params)
BaseCheck.initialize(self, params)
self._url = params.details.url and params.details.url or 'http://127.0.0.1/server-status?auto'
self._timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
-- setup default port
local parsed = url.parse(self._url)
if not parsed.port then
if parsed.protocol == 'http' then
parsed.port = 80
else
parsed.port = 443
end
end
self._parsed = parsed
self._parsed.path = parsed.path ~= '/' and parsed.path or '/server-status?auto'
end
function ApacheCheck:getType()
return 'agent.apache'
end
-- "_" Waiting for Connection, "S" Starting up, "R" Reading Request,
-- "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
-- "C" Closing connection, "L" Logging, "G" Gracefully finishing,
-- "I" Idle cleanup of worker, "." Open slot with no current process
function ApacheCheck:_parseScoreboard(board)
local t = { waiting = 0, starting = 0, reading = 0, sending = 0,
keepalive = 0, dns = 0, closing = 0, logging = 0,
gracefully_finishing = 0, idle = 0, open = 0 }
for c in board:gmatch"." do
if c == '_' then t.waiting = t.waiting + 1
elseif c == 'S' then t.starting = t.starting + 1
elseif c == 'R' then t.reading = t.reading + 1
elseif c == 'W' then t.sending = t.sending + 1
elseif c == 'K' then t.keepalive = t.keepalive + 1
elseif c == 'D' then t.dns = t.dns + 1
elseif c == 'C' then t.closing = t.closing + 1
elseif c == 'L' then t.logging = t.logging + 1
elseif c == 'G' then t.gracefully_finishing = t.gracefully_finishing + 1
elseif c == 'I' then t.idle = t.idle + 1
elseif c == '.' then t.open = t.open + 1
end
end
return t
end
function ApacheCheck:_parseLine(line, checkResult)
local i = line:find(":")
if not i then
return Error:new('Invalid Apache Status Page')
end
local f = line:sub(0, i-1)
local v = line:sub(i+1, #line)
f = misc.trim(f:gsub(" ", "_"))
v = misc.trim(v)
local metrics = {
['Total_Accesses'] = {
['type'] = 'gauge',
['name'] = 'total_accesses',
['unit'] = 'accesses'
},
['Total_kBytes'] = {
['type'] = 'uint64',
['name'] = 'total_kbytes',
['unit'] = 'kilobytes'
},
['Uptime'] = {
['type'] = 'uint64',
['name'] = 'uptime',
['unit'] = 'milliseconds'
},
['BytesPerSec'] = {
['type'] = 'uint64',
['name'] = 'bytes_per_second',
['unit'] = 'bytes'
},
['BytesPerReq'] = {
['type'] = 'uint64',
['name'] = 'bytes_per_request',
['unit'] = 'bytes'
},
['BusyWorkers'] = {
['type'] = 'uint64',
['name'] = 'busy_workers',
['unit'] = 'workers'
},
['IdleWorkers'] = {
['type'] = 'uint64',
['name'] = 'idle_workers',
['unit'] = 'workers'
},
['CPULoad'] = {
['type'] = 'double',
['name'] = 'cpu_load',
['unit'] = 'percent'
},
['ReqPerSec'] = {
['type'] = 'double',
['name'] = 'requests_per_second',
['unit'] = 'requests'
}
}
if metrics[f] then
checkResult:addMetric(metrics[f].name, nil, metrics[f].type, v)
end
if f == 'ReqPerSec' then
checkResult:setStatus(fmt('Handling %.2f requests per second', v))
end
if f == 'Scoreboard' then
local t = self:_parseScoreboard(v)
for j, x in pairs(t) do
checkResult:addMetric(j, nil, 'uint64', x)
end
end
return
end
function ApacheCheck:_parse(data, checkResult)
for line in data:gmatch("([^\n]*)\n") do
local err = self:_parseLine(line, checkResult)
if err then
checkResult:setError(err.message)
return
end
end
end
function ApacheCheck:run(callback)
callback = misc.fireOnce(callback)
local checkResult = CheckResult:new(self, {})
local protocol = self._parsed.protocol == 'http' and http or https
local req = protocol.request(self._parsed, function(res)
local data = ''
res:on('data', function(_data)
data = data .. _data
end)
res:on('end', function()
self:_parse(data, checkResult)
res:destroy()
callback(checkResult)
end)
res:on('error', function(err)
checkResult:setError(err.message)
callback(checkResult)
end)
end)
req:on('error', function(err)
checkResult:setError(err.message)
callback(checkResult)
end)
req:done()
end
exports.ApacheCheck = ApacheCheck
|
fix(check/apache): Fixes problem with the script overwriting custom paths specified by users. Resolves #832
|
fix(check/apache): Fixes problem with the script overwriting custom paths specified by users. Resolves #832
also check for an empty path
|
Lua
|
apache-2.0
|
kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
|
a01286c0f1da00faa8f18ffe9c0ae9467e6f2fbd
|
.Framework/src/MY.InfoCache.lua
|
.Framework/src/MY.InfoCache.lua
|
-----------------------------------------------
-- @Desc : ֵļָٴ洢ģ
-- @Author: @˫ @Ӱ
-- @Date : 2015-11-3 16:24:28
-- @Email : [email protected]
-- @Last Modified by: һ @tinymins
-- @Last Modified time: 2015-11-3 16:24:40
-----------------------------------------------
local tconcat = table.concat
local tremove = table.remove
local tinsert = table.insert
local string2byte = string.byte
local function DefaultValueComparer(v1, v2)
if v1 == v2 then
return 0
else
return 1
end
end
--[[
Sample:
------------------
-- Get an instance
local IC = MY.InfoCache("cache/PLAYER_INFO/$server/TONG/<SEG>.$lang.jx3dat", 2, 3000)
--------------------
-- Setter and Getter
-- Set value
IC["Test"] = "this is a demo"
-- Get value
print(IC["Test"])
-------------
-- Management
IC("save") -- Save to DB
IC("save", 5) -- Save to DB with a max saving len
IC("save", nil, true) -- Save to DB and release memory
IC("save", 5, true) -- Save to DB with a max saving len and release memory
IC("clear") -- Delete all data
]]
function MY.InfoCache(SZ_DATA_PATH, SEG_LEN, L1_SIZE, ValueComparer)
if not ValueComparer then
ValueComparer = DefaultValueComparer
end
local aCache, tCache = {}, setmetatable({}, { __mode = "v" }) -- high speed L1 CACHE
local tInfos, tInfoVisit, tInfoModified = {}, {}, {}
return setmetatable({}, {
__index = function(t, k)
-- if hit in L1 CACHE
if tCache[k] then
-- Log("INFO CACHE L1 HIT " .. k)
return tCache[k]
end
-- read info from saved data
local szSegID = tconcat({string2byte(k, 1, SEG_LEN)}, "-")
if not tInfos[szSegID] then
tInfos[szSegID] = MY.LoadLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID))) or {}
end
tInfoVisit[szSegID] = GetTime()
return tInfos[szSegID][k]
end,
__newindex = function(t, k, v)
local bModified
------------------------------------------------------
-- judge if info has been updated and need to be saved
-- read from L1 CACHE
local tInfo = tCache[k]
local szSegID = tconcat({string2byte(k, 1, SEG_LEN)}, "-")
-- read from DataBase if L1 CACHE not hit
if not tInfo then
if not tInfos[szSegID] then
tInfos[szSegID] = MY.LoadLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID))) or {}
end
tInfo = tInfos[szSegID][k]
tInfoVisit[szSegID] = GetTime()
end
-- judge data
if tInfo then
bModified = ValueComparer(v, tInfo) ~= 0
else
bModified = true
end
------------
-- save info
-- update L1 CACHE
if bModified or not tCache[k] then
if #aCache > L1_SIZE then
tremove(aCache, 1)
end
tinsert(aCache, v)
tCache[k] = v
end
------------------
-- update DataBase
if bModified then
-- save info to DataBase
if not tInfos[szSegID] then
tInfos[szSegID] = MY.LoadLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID))) or {}
end
tInfos[szSegID][k] = v
tInfoVisit[szSegID] = GetTime()
tInfoModified[szSegID] = GetTime()
end
end,
__call = function(t, cmd, arg0, arg1, ...)
if cmd == "clear" then
-- clear all data file
tInfos, tInfoVisit, tInfoModified = {}, {}, {}
tName2ID, tName2IDModified = {}, {}
local aSeg = {}
for i = 1, SEG_LEN do
tinsert(aSeg, 0)
end
while aSeg[SEG_LEN + 1] ~= 1 do
local szSegID = tconcat(aSeg, "-")
if IsFileExist(MY.GetLUADataPath((SZ_DATA_PATH:gsub("<SEG>", szSegID)))) then
MY.SaveLUAData(szSegID, nil)
end
-- bit add one
local i = 1
aSeg[i] = (aSeg[i] or 0) + 1
while aSeg[i] == 256 do
aSeg[i] = 0
i = i + 1
aSeg[i] = (aSeg[i] or 0) + 1
end
end
elseif cmd == "save" then -- save data to db, if nCount has been set and data saving reach the max, fn will return true
local dwTime = arg0
local nCount = arg1
local bCollect = arg2
-- save info data
for szSegID, dwLastVisitTime in pairs(tInfoVisit) do
if not dwTime or dwTime > dwLastVisitTime then
if nCount then
if nCount == 0 then
return true
end
nCount = nCount - 1
end
if tInfoModified[szSegID] then
MY.SaveLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID)), tInfos[szSegID])
else
MY.Debug({"INFO Unloaded: " .. szSegID}, "InfoCache", MY_DEBUG.LOG)
end
if bCollect then
tInfos[szSegID] = nil
end
tInfoVisit[szSegID] = nil
tInfoModified[szSegID] = nil
end
end
end
end
})
end
|
-----------------------------------------------
-- @Desc : ֵļָٴ洢ģ
-- @Author: @˫ @Ӱ
-- @Date : 2015-11-3 16:24:28
-- @Email : [email protected]
-- @Last Modified by: һ @tinymins
-- @Last Modified time: 2015-11-3 16:24:40
-----------------------------------------------
local tconcat = table.concat
local tremove = table.remove
local tinsert = table.insert
local string2byte = string.byte
local function DefaultValueComparer(v1, v2)
if v1 == v2 then
return 0
else
return 1
end
end
--[[
Sample:
------------------
-- Get an instance
local IC = MY.InfoCache("cache/PLAYER_INFO/$server/TONG/<SEG>.$lang.jx3dat", 2, 3000)
--------------------
-- Setter and Getter
-- Set value
IC["Test"] = "this is a demo"
-- Get value
print(IC["Test"])
-------------
-- Management
IC("save") -- Save to DB
IC("save", 5) -- Save to DB with a max saving len
IC("save", nil, true) -- Save to DB and release memory
IC("save", 5, true) -- Save to DB with a max saving len and release memory
IC("clear") -- Delete all data
]]
function MY.InfoCache(SZ_DATA_PATH, SEG_LEN, L1_SIZE, ValueComparer)
if not ValueComparer then
ValueComparer = DefaultValueComparer
end
local aCache, tCache = {}, setmetatable({}, { __mode = "v" }) -- high speed L1 CACHE
local tInfos, tInfoVisit, tInfoModified = {}, {}, {}
return setmetatable({}, {
__index = function(t, k)
-- if hit in L1 CACHE
if tCache[k] then
-- Log("INFO CACHE L1 HIT " .. k)
return tCache[k]
end
-- read info from saved data
local szSegID = tconcat({string2byte(k, 1, SEG_LEN)}, "-")
if not tInfos[szSegID] then
tInfos[szSegID] = MY.LoadLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID))) or {}
end
tInfoVisit[szSegID] = GetTime()
return tInfos[szSegID][k]
end,
__newindex = function(t, k, v)
local bModified
------------------------------------------------------
-- judge if info has been updated and need to be saved
-- read from L1 CACHE
local tInfo = tCache[k]
local szSegID = tconcat({string2byte(k, 1, SEG_LEN)}, "-")
-- read from DataBase if L1 CACHE not hit
if not tInfo then
if not tInfos[szSegID] then
tInfos[szSegID] = MY.LoadLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID))) or {}
end
tInfo = tInfos[szSegID][k]
tInfoVisit[szSegID] = GetTime()
end
-- judge data
if tInfo then
bModified = ValueComparer(v, tInfo) ~= 0
else
bModified = true
end
------------
-- save info
-- update L1 CACHE
if bModified or not tCache[k] then
if #aCache > L1_SIZE then
tremove(aCache, 1)
end
tinsert(aCache, v)
tCache[k] = v
end
------------------
-- update DataBase
if bModified then
-- save info to DataBase
if not tInfos[szSegID] then
tInfos[szSegID] = MY.LoadLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID))) or {}
end
tInfos[szSegID][k] = v
tInfoVisit[szSegID] = GetTime()
tInfoModified[szSegID] = GetTime()
end
end,
__call = function(t, cmd, arg0, arg1, ...)
if cmd == "clear" then
-- clear all data file
tInfos, tInfoVisit, tInfoModified = {}, {}, {}
tName2ID, tName2IDModified = {}, {}
local aSeg = {}
for i = 1, SEG_LEN do
tinsert(aSeg, 0)
end
while aSeg[SEG_LEN + 1] ~= 1 do
local szSegID = tconcat(aSeg, "-")
local szPath = SZ_DATA_PATH:gsub("<SEG>", szSegID)
if IsFileExist(MY.GetLUADataPath(szPath)) then
MY.SaveLUAData(szPath, nil)
-- Log("INFO CACHE CLEAR @" .. szSegID)
end
-- bit add one
local i = 1
aSeg[i] = (aSeg[i] or 0) + 1
while aSeg[i] == 256 do
aSeg[i] = 0
i = i + 1
aSeg[i] = (aSeg[i] or 0) + 1
end
end
elseif cmd == "save" then -- save data to db, if nCount has been set and data saving reach the max, fn will return true
local dwTime = arg0
local nCount = arg1
local bCollect = arg2
-- save info data
for szSegID, dwLastVisitTime in pairs(tInfoVisit) do
if not dwTime or dwTime > dwLastVisitTime then
if nCount then
if nCount == 0 then
return true
end
nCount = nCount - 1
end
if tInfoModified[szSegID] then
MY.SaveLUAData((SZ_DATA_PATH:gsub("<SEG>", szSegID)), tInfos[szSegID])
else
MY.Debug({"INFO Unloaded: " .. szSegID}, "InfoCache", MY_DEBUG.LOG)
end
if bCollect then
tInfos[szSegID] = nil
end
tInfoVisit[szSegID] = nil
tInfoModified[szSegID] = nil
end
end
end
end
})
end
|
IC引擎清除数据的一处BUG
|
IC引擎清除数据的一处BUG
|
Lua
|
bsd-3-clause
|
tinymins/MY
|
6a0da42befb970b56f93c0bf109a9cb7475e8e0c
|
libs/web/luasrc/dispatcher.lua
|
libs/web/luasrc/dispatcher.lua
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Indexdump
local indexcache = "/tmp/.luciindex"
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w_]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
-- Load default translation
require("luci.i18n").loadc("default")
if c and type(c.target) == "function" then
dispatched = c
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cachetime = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cachetime = luci.fs.mtime(indexcache)
if not cachetime then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
end
end
if not cachetime or luci.fs.mtime(path) > cachetime then
for i,c in ipairs(controllers) do
c = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
stat, mod = pcall(require, c)
if stat and mod and type(mod.index) == "function" then
index[c] = mod.index
if indexcache then
luci.fs.writefile(indexcache .. "/" .. c, string.dump(mod.index))
end
end
end
if indexcache then
luci.fs.unlink(indexcache .. "/.index")
luci.fs.writefile(indexcache .. "/.index", "")
end
else
for i,c in ipairs(luci.fs.dir(indexcache)) do
if c:sub(1) ~= "." then
index[c] = loadfile(indexcache .. "/" .. c)
end
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
for k, v in pairs(index) do
luci.util.updfenv(v, _M)
local stat, mod = pcall(require, k)
if stat then
luci.util.updfenv(v, mod)
end
pcall(v)
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Indexdump
local indexcache = "/tmp/.luciindex"
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w_]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
-- Load default translation
require("luci.i18n").loadc("default")
if c and type(c.target) == "function" then
dispatched = c
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cachetime = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cachetime = luci.fs.mtime(indexcache)
if not cachetime then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
end
end
if not cachetime then
for i,c in ipairs(controllers) do
c = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
stat, mod = pcall(require, c)
if stat and mod and type(mod.index) == "function" then
index[c] = mod.index
if indexcache then
luci.fs.writefile(indexcache .. "/" .. c, string.dump(mod.index))
end
end
end
else
for i,c in ipairs(luci.fs.dir(indexcache)) do
if c:sub(1) ~= "." then
index[c] = loadfile(indexcache .. "/" .. c)
end
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
for k, v in pairs(index) do
luci.util.updfenv(v, _M)
local stat, mod = pcall(require, k)
if stat then
luci.util.updfenv(v, mod)
end
pcall(v)
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
* Fixed caching mechanism
|
* Fixed caching mechanism
|
Lua
|
apache-2.0
|
tcatm/luci,remakeelectric/luci,kuoruan/luci,LuttyYang/luci,openwrt-es/openwrt-luci,urueedi/luci,palmettos/cnLuCI,rogerpueyo/luci,cshore/luci,joaofvieira/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,jorgifumi/luci,wongsyrone/luci-1,fkooman/luci,NeoRaider/luci,opentechinstitute/luci,wongsyrone/luci-1,mumuqz/luci,dwmw2/luci,chris5560/openwrt-luci,RuiChen1113/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,kuoruan/lede-luci,obsy/luci,deepak78/new-luci,forward619/luci,jorgifumi/luci,palmettos/cnLuCI,thesabbir/luci,NeoRaider/luci,openwrt-es/openwrt-luci,david-xiao/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,hnyman/luci,aa65535/luci,cshore/luci,forward619/luci,obsy/luci,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,MinFu/luci,Noltari/luci,jorgifumi/luci,dismantl/luci-0.12,wongsyrone/luci-1,thess/OpenWrt-luci,nwf/openwrt-luci,opentechinstitute/luci,cappiewu/luci,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,kuoruan/luci,kuoruan/lede-luci,marcel-sch/luci,aa65535/luci,jchuang1977/luci-1,MinFu/luci,bright-things/ionic-luci,Hostle/luci,ff94315/luci-1,fkooman/luci,ollie27/openwrt_luci,artynet/luci,fkooman/luci,fkooman/luci,dismantl/luci-0.12,daofeng2015/luci,taiha/luci,palmettos/test,fkooman/luci,male-puppies/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,joaofvieira/luci,maxrio/luci981213,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,NeoRaider/luci,joaofvieira/luci,kuoruan/luci,cshore-firmware/openwrt-luci,MinFu/luci,schidler/ionic-luci,nwf/openwrt-luci,thesabbir/luci,schidler/ionic-luci,oyido/luci,hnyman/luci,zhaoxx063/luci,keyidadi/luci,openwrt-es/openwrt-luci,mumuqz/luci,Wedmer/luci,lcf258/openwrtcn,harveyhu2012/luci,keyidadi/luci,rogerpueyo/luci,wongsyrone/luci-1,ollie27/openwrt_luci,slayerrensky/luci,Wedmer/luci,cshore-firmware/openwrt-luci,jorgifumi/luci,florian-shellfire/luci,teslamint/luci,ollie27/openwrt_luci,nwf/openwrt-luci,tcatm/luci,dismantl/luci-0.12,cappiewu/luci,kuoruan/lede-luci,maxrio/luci981213,sujeet14108/luci,Hostle/luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,thess/OpenWrt-luci,jchuang1977/luci-1,david-xiao/luci,marcel-sch/luci,oyido/luci,lcf258/openwrtcn,teslamint/luci,artynet/luci,maxrio/luci981213,rogerpueyo/luci,981213/luci-1,marcel-sch/luci,sujeet14108/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,fkooman/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,Noltari/luci,palmettos/cnLuCI,kuoruan/lede-luci,florian-shellfire/luci,Noltari/luci,slayerrensky/luci,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,openwrt-es/openwrt-luci,RuiChen1113/luci,dwmw2/luci,daofeng2015/luci,981213/luci-1,daofeng2015/luci,palmettos/test,jlopenwrtluci/luci,981213/luci-1,tcatm/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,Wedmer/luci,artynet/luci,Sakura-Winkey/LuCI,Wedmer/luci,urueedi/luci,RuiChen1113/luci,remakeelectric/luci,deepak78/new-luci,joaofvieira/luci,aa65535/luci,Wedmer/luci,kuoruan/lede-luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,male-puppies/luci,tcatm/luci,mumuqz/luci,aa65535/luci,taiha/luci,lbthomsen/openwrt-luci,artynet/luci,nmav/luci,RedSnake64/openwrt-luci-packages,Noltari/luci,taiha/luci,LuttyYang/luci,nwf/openwrt-luci,joaofvieira/luci,forward619/luci,jchuang1977/luci-1,sujeet14108/luci,artynet/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,cappiewu/luci,oyido/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,rogerpueyo/luci,hnyman/luci,thess/OpenWrt-luci,RuiChen1113/luci,taiha/luci,zhaoxx063/luci,kuoruan/luci,oneru/luci,daofeng2015/luci,palmettos/test,lbthomsen/openwrt-luci,NeoRaider/luci,Hostle/luci,lcf258/openwrtcn,lcf258/openwrtcn,Wedmer/luci,florian-shellfire/luci,teslamint/luci,dismantl/luci-0.12,mumuqz/luci,cshore/luci,hnyman/luci,nmav/luci,urueedi/luci,palmettos/test,maxrio/luci981213,MinFu/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,cshore-firmware/openwrt-luci,urueedi/luci,keyidadi/luci,thess/OpenWrt-luci,981213/luci-1,male-puppies/luci,RuiChen1113/luci,florian-shellfire/luci,slayerrensky/luci,daofeng2015/luci,lcf258/openwrtcn,NeoRaider/luci,bittorf/luci,male-puppies/luci,teslamint/luci,remakeelectric/luci,NeoRaider/luci,bittorf/luci,maxrio/luci981213,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,Sakura-Winkey/LuCI,urueedi/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,openwrt/luci,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,Hostle/luci,marcel-sch/luci,chris5560/openwrt-luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,mumuqz/luci,cshore/luci,lcf258/openwrtcn,jchuang1977/luci-1,deepak78/new-luci,nmav/luci,NeoRaider/luci,jorgifumi/luci,kuoruan/luci,palmettos/test,nmav/luci,openwrt/luci,aa65535/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,oneru/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,obsy/luci,deepak78/new-luci,Kyklas/luci-proto-hso,marcel-sch/luci,oneru/luci,daofeng2015/luci,deepak78/new-luci,bittorf/luci,schidler/ionic-luci,chris5560/openwrt-luci,dwmw2/luci,ff94315/luci-1,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,openwrt/luci,harveyhu2012/luci,Sakura-Winkey/LuCI,harveyhu2012/luci,dwmw2/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,opentechinstitute/luci,Noltari/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,tobiaswaldvogel/luci,sujeet14108/luci,aa65535/luci,tobiaswaldvogel/luci,opentechinstitute/luci,lcf258/openwrtcn,teslamint/luci,opentechinstitute/luci,jlopenwrtluci/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,ollie27/openwrt_luci,urueedi/luci,remakeelectric/luci,slayerrensky/luci,tobiaswaldvogel/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,MinFu/luci,jorgifumi/luci,keyidadi/luci,obsy/luci,kuoruan/luci,nmav/luci,thesabbir/luci,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,ollie27/openwrt_luci,male-puppies/luci,wongsyrone/luci-1,jorgifumi/luci,bittorf/luci,bright-things/ionic-luci,forward619/luci,cshore-firmware/openwrt-luci,mumuqz/luci,jchuang1977/luci-1,ollie27/openwrt_luci,david-xiao/luci,cappiewu/luci,ff94315/luci-1,david-xiao/luci,david-xiao/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,tcatm/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,forward619/luci,oyido/luci,oneru/luci,taiha/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,hnyman/luci,981213/luci-1,ff94315/luci-1,bright-things/ionic-luci,thess/OpenWrt-luci,openwrt/luci,opentechinstitute/luci,deepak78/new-luci,david-xiao/luci,jchuang1977/luci-1,Wedmer/luci,nwf/openwrt-luci,MinFu/luci,remakeelectric/luci,bittorf/luci,openwrt/luci,Hostle/luci,keyidadi/luci,ff94315/luci-1,jorgifumi/luci,jlopenwrtluci/luci,opentechinstitute/luci,dismantl/luci-0.12,david-xiao/luci,schidler/ionic-luci,zhaoxx063/luci,NeoRaider/luci,bright-things/ionic-luci,chris5560/openwrt-luci,slayerrensky/luci,deepak78/new-luci,RedSnake64/openwrt-luci-packages,Sakura-Winkey/LuCI,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,forward619/luci,oyido/luci,taiha/luci,thesabbir/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,cappiewu/luci,chris5560/openwrt-luci,sujeet14108/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,slayerrensky/luci,joaofvieira/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,Noltari/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,obsy/luci,zhaoxx063/luci,thesabbir/luci,sujeet14108/luci,Kyklas/luci-proto-hso,urueedi/luci,harveyhu2012/luci,palmettos/cnLuCI,bright-things/ionic-luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,tobiaswaldvogel/luci,florian-shellfire/luci,cappiewu/luci,kuoruan/luci,daofeng2015/luci,palmettos/test,cshore/luci,Sakura-Winkey/LuCI,sujeet14108/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,RuiChen1113/luci,LuttyYang/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,oyido/luci,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,harveyhu2012/luci,thesabbir/luci,remakeelectric/luci,tcatm/luci,remakeelectric/luci,Hostle/luci,fkooman/luci,keyidadi/luci,wongsyrone/luci-1,taiha/luci,oyido/luci,keyidadi/luci,LuttyYang/luci,bright-things/ionic-luci,thess/OpenWrt-luci,schidler/ionic-luci,oneru/luci,palmettos/cnLuCI,RuiChen1113/luci,rogerpueyo/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,981213/luci-1,oyido/luci,artynet/luci,tcatm/luci,tcatm/luci,palmettos/test,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,daofeng2015/luci,rogerpueyo/luci,remakeelectric/luci,dwmw2/luci,cshore/luci,chris5560/openwrt-luci,bright-things/ionic-luci,maxrio/luci981213,artynet/luci,aa65535/luci,openwrt-es/openwrt-luci,cshore/luci,jlopenwrtluci/luci,ff94315/luci-1,jlopenwrtluci/luci,shangjiyu/luci-with-extra,LuttyYang/luci,palmettos/cnLuCI,openwrt/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,oneru/luci,slayerrensky/luci,keyidadi/luci,rogerpueyo/luci,hnyman/luci,joaofvieira/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,mumuqz/luci,bright-things/ionic-luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,nmav/luci,nmav/luci,LuttyYang/luci,nmav/luci,deepak78/new-luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,openwrt/luci,florian-shellfire/luci,maxrio/luci981213,dwmw2/luci,palmettos/test,981213/luci-1,chris5560/openwrt-luci,cappiewu/luci,aa65535/luci,dismantl/luci-0.12,kuoruan/luci,hnyman/luci,obsy/luci,hnyman/luci,teslamint/luci,cshore/luci,florian-shellfire/luci,david-xiao/luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,forward619/luci,nmav/luci,thess/OpenWrt-luci,dwmw2/luci,forward619/luci,marcel-sch/luci,slayerrensky/luci,Wedmer/luci,chris5560/openwrt-luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,urueedi/luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,fkooman/luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,zhaoxx063/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,marcel-sch/luci,thesabbir/luci,openwrt-es/openwrt-luci,Noltari/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,mumuqz/luci
|
592f9464e5a64649a824eb5eaf88a6e0a97e6009
|
lib/luvit/utils.lua
|
lib/luvit/utils.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if not _G.useColors then
_G.useColors = true
end
function utils.color(color_name)
if _G.useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. string .. utils.color(reset_name)
end
local backslash, null, newline, carraige, tab, quote, quote2, obracket, cbracket
function utils.loadColors (n)
if n ~= nil then _G.useColors = n end
backslash = utils.colorize("Bgreen", "\\\\", "green")
null = utils.colorize("Bgreen", "\\0", "green")
newline = utils.colorize("Bgreen", "\\n", "green")
carraige = utils.colorize("Bgreen", "\\r", "green")
tab = utils.colorize("Bgreen", "\\t", "green")
quote = utils.colorize("Bgreen", '"', "green")
quote2 = utils.colorize("Bgreen", '"')
obracket = utils.colorize("white", '[')
cbracket = utils.colorize("white", ']')
end
utils.loadColors ()
function utils.dump(o, depth)
local t = type(o)
if t == 'string' then
return quote .. o:gsub("\\", backslash):gsub("%z", null):gsub("\n", newline):gsub("\r", carraige):gsub("\t", tab) .. quote2
end
if t == 'nil' then
return utils.colorize("Bblack", "nil")
end
if t == 'boolean' then
return utils.colorize("yellow", tostring(o))
end
if t == 'number' then
return utils.colorize("blue", tostring(o))
end
if t == 'userdata' then
return utils.colorize("magenta", tostring(o))
end
if t == 'thread' then
return utils.colorize("Bred", tostring(o))
end
if t == 'function' then
return utils.colorize("cyan", tostring(o))
end
if t == 'cdata' then
return utils.colorize("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return utils.colorize("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fun, self, ...)
local bind_args = {...}
return function(...)
local args = {...}
for i=#bind_args,1,-1 do
table.insert(args, 1, bind_args[i])
end
fun(self, unpack(args))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. string .. utils.color(reset_name)
end
local backslash, null, newline, carriage, tab, quote, quote2, obracket, cbracket
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
backslash = utils.colorize("Bgreen", "\\\\", "green")
null = utils.colorize("Bgreen", "\\0", "green")
newline = utils.colorize("Bgreen", "\\n", "green")
carriage = utils.colorize("Bgreen", "\\r", "green")
tab = utils.colorize("Bgreen", "\\t", "green")
quote = utils.colorize("Bgreen", '"', "green")
quote2 = utils.colorize("Bgreen", '"')
obracket = utils.colorize("white", '[')
cbracket = utils.colorize("white", ']')
end
utils.loadColors ()
function utils.dump(o, depth)
local t = type(o)
if t == 'string' then
return quote .. o:gsub("\\", backslash):gsub("%z", null):gsub("\n", newline):gsub("\r", carriage):gsub("\t", tab) .. quote2
end
if t == 'nil' then
return utils.colorize("Bblack", "nil")
end
if t == 'boolean' then
return utils.colorize("yellow", tostring(o))
end
if t == 'number' then
return utils.colorize("blue", tostring(o))
end
if t == 'userdata' then
return utils.colorize("magenta", tostring(o))
end
if t == 'thread' then
return utils.colorize("Bred", tostring(o))
end
if t == 'function' then
return utils.colorize("cyan", tostring(o))
end
if t == 'cdata' then
return utils.colorize("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return utils.colorize("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fun, self, ...)
local bind_args = {...}
return function(...)
local args = {...}
for i=#bind_args,1,-1 do
table.insert(args, 1, bind_args[i])
end
fun(self, unpack(args))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
Do not polute global namespace with useColors and fix typo
|
Do not polute global namespace with useColors and fix typo
|
Lua
|
apache-2.0
|
boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,sousoux/luvit,sousoux/luvit,connectFree/lev,boundary/luvit,AndrewTsao/luvit,boundary/luvit,rjeli/luvit,luvit/luvit,sousoux/luvit,rjeli/luvit,rjeli/luvit,kaustavha/luvit,zhaozg/luvit,kaustavha/luvit,zhaozg/luvit,kaustavha/luvit,boundary/luvit,bsn069/luvit,sousoux/luvit,AndrewTsao/luvit,DBarney/luvit,luvit/luvit,connectFree/lev,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,DBarney/luvit,sousoux/luvit,boundary/luvit,AndrewTsao/luvit,sousoux/luvit,bsn069/luvit,DBarney/luvit,bsn069/luvit,boundary/luvit
|
c04634778e29139d7c4485725da49fd3ac6dfb09
|
modules/shipment.lua
|
modules/shipment.lua
|
local util = require'util'
local simplehttp = util.simplehttp
local json = util.json
local apiurl = 'http://sporing.bring.no/sporing.json?q=%s&%s'
local duration = 60
-- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage
if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end
local split = function(str, pattern)
local out = {}
str:gsub(pattern, function(match)
table.insert(out, match)
end)
return out
end
local getCacheBust = function()
return math.floor(os.time() / 60)
end
local eventHandler = function(event)
if not event then return nil end
local city = event.city
if city ~= '' then city = ' ('..city..')' end
return string.format('%s %s %s%s', event.displayDate, event.displayTime, event.description, city)
end
local shipmentTrack = function(self, source, destination, message)
local nick = source.nick
local comps = split(message, '%S+')
-- Couldn't figure out what the user wanted.
if #comps < 2 then
return say('Usage: !sporing pakkeid alias')
end
local pid = comps[1]
local alias = comps[2]
local id = pid .. nick
-- Store the eventcount in the ivar2 global
-- if the eventcount increases it means new events on the shipment happened.
local eventCount = self.shipmentEvents[id]
if not eventCount then
self.shipmentEvents[id] = -1
end
self:Timer('shipment', duration,
function(loop, timer, revents)
simplehttp(string.format(apiurl, pid, getCacheBust()), function(data)
local info = json.decode(data)
local cs = info.consignmentSet
if not cs[1] then return else cs = cs[1] end
local err = cs['error']
if err then
local errmsg = err['message']
if self.shipmentEvents[id] == -1 then
say('%s: \002%s\002 %s', nick, alias, errmsg)
end
self.shipmentEvents[id] = 0
return
end
local ps = cs['packageSet'][1]
local eventset = ps['eventSet']
local newEventCount = #eventset
local out = {}
--print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id])
if newEventCount < self.shipmentEvents[id]
then newEventCount = self.shipmentEvents[id]
end
for i=self.shipmentEvents[id]+1,newEventCount do
--print('loop:',i)
local event = eventset[i]
if event then
table.insert(out, eventHandler(event))
local status = event.status
-- Cancel event if package is delivered
if status == 'DELIVERED' then
self.timers[id]:stop(ivar2.Loop)
self.timers[id] = nil
end
end
end
if #out > 0 then
say('%s: \002%s\002 %s', nick, alias, table.concat(out, ', '))
end
self.shipmentEvents[id] = newEventCount
end)
end)
end
local shipmentLocate = function(self, source, destination, pid)
local nick = source.nick
simplehttp(string.format(apiurl, pid, getCacheBust()), function(data)
local info = json.decode(data)
local cs = info.consignmentSet
if not cs[1] then return else cs = cs[1] end
local err = cs['error']
if err then
local errmsg = err['message']
say('%s: %s', nick, errmsg)
return
end
local out = {}
local ps = cs['packageSet'][1]
for i,event in pairs(ps['eventSet']) do
table.insert(out, eventHandler(event))
end
say('%s: %s', nick, table.concat(out, ', '))
end)
end
local shipmentHelp = function(self, source, destination)
return say('For lookup: !pakke pakkeid. For tracking: !sporing pakkeid alias')
end
return {
PRIVMSG = {
['^%psporing (.*)$'] = shipmentTrack,
['^%pspor (.*)$'] = shipmentTrack,
['^%ppakke (.*)$'] = shipmentLocate,
['^%psporing$'] = shipmentHelp,
['^%ppakke$'] = shipmentHelp,
},
}
|
local util = require'util'
local simplehttp = util.simplehttp
local json = util.json
local apiurl = 'http://sporing.bring.no/sporing.json?q=%s&%s'
local duration = 60
-- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage
if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end
local split = function(str, pattern)
local out = {}
str:gsub(pattern, function(match)
table.insert(out, match)
end)
return out
end
local getCacheBust = function()
return math.floor(os.time() / 60)
end
local eventHandler = function(event)
if not event then return nil end
local city = event.city
if city ~= '' then city = ' ('..city..')' end
return string.format('%s %s %s%s', event.displayDate, event.displayTime, event.description, city)
end
local shipmentTrack = function(self, source, destination, message)
local nick = source.nick
local comps = split(message, '%S+')
-- Couldn't figure out what the user wanted.
if #comps < 2 then
return say('Usage: !sporing pakkeid alias')
end
local pid = comps[1]
local alias = comps[2]
local id = pid .. nick
-- Store the eventcount in the ivar2 global
-- if the eventcount increases it means new events on the shipment happened.
local eventCount = self.shipmentEvents[id]
if not eventCount then
self.shipmentEvents[id] = -1
end
local shipmentPoller = function()
simplehttp(string.format(apiurl, pid, getCacheBust()), function(data)
local info = json.decode(data)
local cs = info.consignmentSet
if not cs[1] then return else cs = cs[1] end
local err = cs['error']
if err then
local errmsg = err['message']
if self.shipmentEvents[id] == -1 then
say('%s: \002%s\002 %s', nick, alias, errmsg)
end
self.shipmentEvents[id] = 0
return
end
local ps = cs['packageSet'][1]
local eventset = ps['eventSet']
local newEventCount = #eventset
local out = {}
--print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id])
if newEventCount < self.shipmentEvents[id]
then newEventCount = self.shipmentEvents[id]
end
for i=self.shipmentEvents[id]+1,newEventCount do
--print('loop:',i)
local event = eventset[i]
if event then
table.insert(out, eventHandler(event))
local status = event.status
-- Cancel event if package is delivered
if status == 'DELIVERED' then
self.timers[id]:stop(ivar2.Loop)
--self.timers[id] = nil
end
end
end
if #out > 0 then
say('%s: \002%s\002 %s', nick, alias, table.concat(out, ', '))
end
self.shipmentEvents[id] = newEventCount
end)
end
self:Timer(id, duration, duration, shipmentPoller)
shipmentPoller()
end
local shipmentLocate = function(self, source, destination, pid)
local nick = source.nick
simplehttp(string.format(apiurl, pid, getCacheBust()), function(data)
local info = json.decode(data)
local cs = info.consignmentSet
if not cs[1] then return else cs = cs[1] end
local err = cs['error']
if err then
local errmsg = err['message']
say('%s: %s', nick, errmsg)
return
end
local out = {}
local ps = cs['packageSet'][1]
for i,event in pairs(ps['eventSet']) do
table.insert(out, eventHandler(event))
end
say('%s: %s', nick, table.concat(out, ', '))
end)
end
local shipmentHelp = function(self, source, destination)
return say('For lookup: !pakke pakkeid. For tracking: !sporing pakkeid alias')
end
return {
PRIVMSG = {
['^%psporing (.*)$'] = shipmentTrack,
['^%pspor (.*)$'] = shipmentTrack,
['^%ppakke (.*)$'] = shipmentLocate,
['^%psporing$'] = shipmentHelp,
['^%ppakke$'] = shipmentHelp,
},
}
|
shipment: fix timer and polling
|
shipment: fix timer and polling
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
|
ebbdaefea493a1065a3f5a34f46df30c6b8aa0fe
|
libs/weblit-app.lua
|
libs/weblit-app.lua
|
exports.name = "creationix/weblit-app"
exports.version = "0.1.1"
exports.dependencies = {
'creationix/[email protected]',
'creationix/[email protected]',
'luvit/[email protected]',
}
--[[
Web App Framework
Middleware Contract:
function middleware(req, res, go)
req.method
req.path
req.params
req.headers
req.version
req.keepAlive
req.body
res.code
res.headers
res.body
go() - Run next in chain, can tail call or wait for return and do more
headers is a table/list with numerical headers. But you can also read and
write headers using string keys, it will do case-insensitive compare for you.
body can be a string or a stream. A stream is nothing more than a function
you can call repeatedly to get new values. Returns nil when done.
server
.bind({
host = "0.0.0.0"
port = 8080
})
.bind({
host = "0.0.0.0",
port = 8443,
tls = true
})
.route({
method = "GET",
host = "^creationix.com",
path = "/:path:"
}, middleware)
.use(middleware)
.start()
]]
local createServer = require('coro-tcp').createServer
local wrapper = require('coro-wrapper')
local readWrap, writeWrap = wrapper.reader, wrapper.writer
local httpCodec = require('http-codec')
local server = {}
local handlers = {}
local bindings = {}
-- Provide a nice case insensitive interface to headers.
local headerMeta = {
__index = function (list, name)
if type(name) ~= "string" then
return rawget(list, name)
end
name = name:lower()
for i = 1, #list do
local key, value = unpack(list[i])
if key:lower() == name then return value end
end
end,
__newindex = function (list, name, value)
if type(name) ~= "string" then
return rawset(list, name, value)
end
local lowerName = name:lower()
for i = 1, #list do
local key = list[i][1]
if key:lower() == lowerName then
if value == nil then
table.remove(list, i)
else
list[i] = {name, tostring(value)}
end
return
end
end
if value == nil then return end
rawset(list, #list + 1, {name, tostring(value)})
end,
}
local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
local function escape(str)
return str:gsub(quotepattern, "%%%1")
end
local function compileGlob(glob)
local parts = {"^"}
for a, b in glob:gmatch("([^*]*)(%**)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #b > 0 then
parts[#parts + 1] = "(.*)"
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
return string:match(pattern)
end
end
local function compileRoute(route)
local parts = {"^"}
local names = {}
for a, b, c, d in route:gmatch("([^:]*):([_%a][_%w]*)(:?)([^:]*)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = "(.*)"
else
parts[#parts + 1] = "([^/]*)"
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (string)
if string == route then return {} end
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
local matches = {string:match(pattern)}
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[i] = matches[i]
results[names[i]] = matches[i]
end
return results
end
end
end
local function handleRequest(head, input)
local req = {
method = head.method,
path = head.path,
headers = setmetatable({}, headerMeta),
version = head.version,
keepAlive = head.keepAlive,
body = input
}
for i = 1, #head do
req.headers[i] = head[i]
end
local res = {
code = 404,
headers = setmetatable({}, headerMeta),
body = "Not Found\n",
}
local function run(i)
local success, err = pcall(function ()
i = i or 1
local go = i < #handlers
and function ()
return run(i + 1)
end
or function () end
return handlers[i](req, res, go)
end)
if not success then
res.code = 500
res.headers = setmetatable({}, headerMeta)
res.body = err
print(err)
end
end
run(1)
local out = {
code = res.code,
keepAlive = res.keepAlive,
}
for i = 1, #res.headers do
out[i] = res.headers[i]
end
return out, res.body
end
local function handleConnection(rawRead, rawWrite)
-- Speak in HTTP events
local read = readWrap(rawRead, httpCodec.decoder())
local write = writeWrap(rawWrite, httpCodec.encoder())
for req in read do
local parts = {}
for chunk in read do
if #chunk > 0 then
parts[#parts + 1] = chunk
else
break
end
end
req.parts = #parts > 0 and table.concat(parts) or nil
local res, body = handleRequest(req)
write(res)
write(body)
if not (res.keepAlive and req.keepAlive) then
break
end
end
write()
end
function server.bind(options)
bindings[#bindings + 1] = options
return server
end
function server.use(handler)
handlers[#handlers + 1] = handler
return server
end
function server.route(options, handler)
local method = options.method
local path = options.path and compileRoute(options.path)
local host = options.host and compileGlob(options.host)
handlers[#handlers + 1] = function (req, res, go)
if method and req.method ~= method then return go() end
if host and not (req.headers.host and host(req.headers.host)) then return go() end
local params
if path then
params = path(req.path)
if not params then return go() end
end
req.params = params or {}
return handler(req, res, go)
end
return server
end
function server.start()
for i = 1, #bindings do
local options = bindings[i]
-- TODO: handle options.tls
createServer(options.host, options.port, handleConnection)
print("HTTP server listening at http://" .. options.host .. ":" .. options.port .. "/")
end
return server
end
return server
|
exports.name = "creationix/weblit-app"
exports.version = "0.1.2"
exports.dependencies = {
'creationix/[email protected]',
'creationix/[email protected]',
'luvit/[email protected]',
}
--[[
Web App Framework
Middleware Contract:
function middleware(req, res, go)
req.method
req.path
req.params
req.headers
req.version
req.keepAlive
req.body
res.code
res.headers
res.body
go() - Run next in chain, can tail call or wait for return and do more
headers is a table/list with numerical headers. But you can also read and
write headers using string keys, it will do case-insensitive compare for you.
body can be a string or a stream. A stream is nothing more than a function
you can call repeatedly to get new values. Returns nil when done.
server
.bind({
host = "0.0.0.0"
port = 8080
})
.bind({
host = "0.0.0.0",
port = 8443,
tls = true
})
.route({
method = "GET",
host = "^creationix.com",
path = "/:path:"
}, middleware)
.use(middleware)
.start()
]]
local createServer = require('coro-tcp').createServer
local wrapper = require('coro-wrapper')
local readWrap, writeWrap = wrapper.reader, wrapper.writer
local httpCodec = require('http-codec')
local server = {}
local handlers = {}
local bindings = {}
-- Provide a nice case insensitive interface to headers.
local headerMeta = {
__index = function (list, name)
if type(name) ~= "string" then
return rawget(list, name)
end
name = name:lower()
for i = 1, #list do
local key, value = unpack(list[i])
if key:lower() == name then return value end
end
end,
__newindex = function (list, name, value)
if type(name) ~= "string" then
return rawset(list, name, value)
end
local lowerName = name:lower()
for i = 1, #list do
local key = list[i][1]
if key:lower() == lowerName then
if value == nil then
table.remove(list, i)
else
list[i] = {name, tostring(value)}
end
return
end
end
if value == nil then return end
rawset(list, #list + 1, {name, tostring(value)})
end,
}
local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
local function escape(str)
return str:gsub(quotepattern, "%%%1")
end
local function compileGlob(glob)
local parts = {"^"}
for a, b in glob:gmatch("([^*]*)(%**)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #b > 0 then
parts[#parts + 1] = "(.*)"
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
return string:match(pattern)
end
end
local function compileRoute(route)
local parts = {"^"}
local names = {}
for a, b, c, d in route:gmatch("([^:]*):([_%a][_%w]*)(:?)([^:]*)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = "(.*)"
else
parts[#parts + 1] = "([^/]*)"
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (string)
if string == route then return {} end
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
local matches = {string:match(pattern)}
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[i] = matches[i]
results[names[i]] = matches[i]
end
return results
end
end
end
local function handleRequest(head, input, socket)
local req = {
socket = socket,
method = head.method,
path = head.path,
headers = setmetatable({}, headerMeta),
version = head.version,
keepAlive = head.keepAlive,
body = input
}
for i = 1, #head do
req.headers[i] = head[i]
end
local res = {
code = 404,
headers = setmetatable({}, headerMeta),
body = "Not Found\n",
}
local function run(i)
local success, err = pcall(function ()
i = i or 1
local go = i < #handlers
and function ()
return run(i + 1)
end
or function () end
return handlers[i](req, res, go)
end)
if not success then
res.code = 500
res.headers = setmetatable({}, headerMeta)
res.body = err
print(err)
end
end
run(1)
local out = {
code = res.code,
keepAlive = res.keepAlive,
}
for i = 1, #res.headers do
out[i] = res.headers[i]
end
return out, res.body
end
local function handleConnection(rawRead, rawWrite, socket)
-- Speak in HTTP events
local read = readWrap(rawRead, httpCodec.decoder())
local write = writeWrap(rawWrite, httpCodec.encoder())
for head in read do
local parts = {}
for chunk in read do
if #chunk > 0 then
parts[#parts + 1] = chunk
else
break
end
end
local res, body = handleRequest(head, #parts > 0 and table.concat(parts) or nil, socket)
write(res)
write(body)
if not (res.keepAlive and head.keepAlive) then
break
end
end
write()
end
function server.bind(options)
bindings[#bindings + 1] = options
return server
end
function server.use(handler)
handlers[#handlers + 1] = handler
return server
end
function server.route(options, handler)
local method = options.method
local path = options.path and compileRoute(options.path)
local host = options.host and compileGlob(options.host)
handlers[#handlers + 1] = function (req, res, go)
if method and req.method ~= method then return go() end
if host and not (req.headers.host and host(req.headers.host)) then return go() end
local params
if path then
params = path(req.path)
if not params then return go() end
end
req.params = params or {}
return handler(req, res, go)
end
return server
end
function server.start()
for i = 1, #bindings do
local options = bindings[i]
-- TODO: handle options.tls
createServer(options.host, options.port, handleConnection)
print("HTTP server listening at http://" .. options.host .. ":" .. options.port .. "/")
end
return server
end
return server
|
Fix post and add socket access
|
Fix post and add socket access
|
Lua
|
mit
|
zhaozg/weblit
|
d64f5cdb7b8fffea2004a137796736769eddfefc
|
lua/entities/gmod_wire_igniter.lua
|
lua/entities/gmod_wire_igniter.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Igniter"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Igniter"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "A", "Length" })
self.IgniteLength = 10
self:Setup(false, 2048)
end
function ENT:Setup(trgply,Range)
self.TargetPlayers = trgply
if Range then self:SetBeamLength(Range) end
end
function ENT:TriggerInput(iname, value)
if (iname == "A") then
if (value ~= 0) then
local vStart = self:GetPos()
local vForward = self:GetUp()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * self:GetBeamLength())
trace.filter = { self }
local trace = util.TraceLine( trace )
local svarTargetPlayers = GetConVarNumber('sbox_wire_igniters_allowtrgply') > 0
if not IsValid(trace.Entity) then return false end
if (trace.Entity:IsPlayer() && (!self.TargetPlayers || !svarTargetPlayers)) then return false end
if (trace.Entity:IsWorld()) then return false end
trace.Entity:Extinguish()
trace.Entity:Ignite( self.IgniteLength, 0 )
end
else
if(iname == "Length") then
self.IgniteLength = math.min(value,GetConVarNumber("sbox_wire_igniters_maxlen"))
end
end
end
duplicator.RegisterEntityClass("gmod_wire_igniter", WireLib.MakeWireEnt, "Data", "TargetPlayers", "Range")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Igniter"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Igniter"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "A", "Length" })
self.IgniteLength = 10
self:Setup(false, 2048)
end
function ENT:Setup(trgply,Range)
self.TargetPlayers = trgply
if Range then self:SetBeamLength(Range) end
end
function ENT:TriggerInput(iname, value)
if (iname == "A") then
if (value ~= 0) then
local vStart = self:GetPos()
local vForward = self:GetUp()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * self:GetBeamLength())
trace.filter = { self }
local trace = util.TraceLine( trace )
local svarTargetPlayers = GetConVarNumber('sbox_wire_igniters_allowtrgply') > 0
if not IsValid(trace.Entity) then return false end
if not gamemode.Call("CanProperty", self:GetOwner(), "ignite", trace.Entity) then return false end
if (trace.Entity:IsPlayer() && (!self.TargetPlayers || !svarTargetPlayers)) then return false end
if (trace.Entity:IsWorld()) then return false end
trace.Entity:Extinguish()
trace.Entity:Ignite( self.IgniteLength, 0 )
end
else
if(iname == "Length") then
self.IgniteLength = math.min(value,GetConVarNumber("sbox_wire_igniters_maxlen"))
end
end
end
duplicator.RegisterEntityClass("gmod_wire_igniter", WireLib.MakeWireEnt, "Data", "TargetPlayers", "Range")
|
Fix #545. Igniter now obeys prop protection.
|
Fix #545. Igniter now obeys prop protection.
|
Lua
|
apache-2.0
|
plinkopenguin/wiremod,wiremod/wire,rafradek/wire,thegrb93/wire,immibis/wiremod,CaptainPRICE/wire,notcake/wire,bigdogmat/wire,garrysmodlua/wire,NezzKryptic/Wire,Python1320/wire,mitterdoo/wire,sammyt291/wire,mms92/wire,dvdvideo1234/wire,Grocel/wire
|
d09550bbfd482a50e241bd0db307aae0c723b77a
|
lua/plugins/lsp.lua
|
lua/plugins/lsp.lua
|
local nvim = require('nvim')
local sys = require('sys')
local executable = require('nvim').fn.executable
local isdirectory = require('nvim').fn.isdirectory
local nvim_set_autocmd = require('nvim').nvim_set_autocmd
-- local nvim_set_command = require('nvim').nvim_set_command
local ok, lsp = pcall(require, 'nvim_lsp')
if not ok then
return nil
end
local servers = {
sh = { bashls = { name = 'bash-language-server'}, },
rust = { rust_analyzer = { name = 'rust_analyzer'}, },
go = { gopls = { name = 'gopls'}, },
tex = { texlab = { name = 'texlab'}, },
vim = { vimls = { name = 'vimls'}, },
dockerfile = { dockerls = { name = 'docker-langserver'}, },
lua = {
sumneko_lua = {
name = 'sumneko_lua',
options = {
settings = {
Lua = {
diagnostics = {
globals = {
'vim',
}
},
},
},
},
},
},
python = {
pyls = {
name = 'pyls',
options = {
settings = {
pyls = {
plugins = {
mccabe = {
threshold = 20
},
pycodestyle = {
maxLineLength = 120
},
},
},
},
},
},
},
c = {
ccls = {
name = 'ccls',
options = {
cmd = { 'ccls', '--log-file=' .. sys.tmp('ccls.log') },
init_options = {
cache = {
directory = sys.cache..'/ccls'
},
highlight = {
lsRanges = true;
},
completion = {
filterAndSort = true,
caseSensitivity = 1,
detailedLabel = false,
},
},
},
},
clangd = {
name = 'clangd',
options = {
cmd = {
'clangd',
'--index',
'--background-index',
'--suggest-missing-includes',
'--clang-tidy',
},
}
},
},
}
local available_languages = {}
for language,options in pairs(servers) do
for option,server in pairs(options) do
if executable(server['name']) == 1 or isdirectory(sys.home .. '/.cache/nvim/nvim_lsp/' .. server['name']) == 1 then
local init = server['options'] ~= nil and server['options'] or {}
lsp[option].setup(init)
available_languages[#available_languages + 1] = language
if language == 'c' then
available_languages[#available_languages + 1] = 'cpp'
available_languages[#available_languages + 1] = 'objc'
available_languages[#available_languages + 1] = 'objcpp'
elseif language == 'dockerfile' then
available_languages[#available_languages + 1] = 'Dockerfile'
elseif language == 'tex' then
available_languages[#available_languages + 1] = 'bib'
end
break
end
end
end
nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> <c-]> :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gd :lua vim.lsp.buf.declaration()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.implementation()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gr :lua vim.lsp.buf.references()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('References', 'lua vim.lsp.buf.references()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"autocmd CursorHold <buffer> lua vim.lsp.buf.hover()",
{group = 'NvimLSP', nested = true}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
do
local method = 'textDocument/publishDiagnostics'
local default_callback = vim.lsp.callbacks[method]
vim.lsp.callbacks[method] = function(err, method, result, client_id)
default_callback(err, method, result, client_id)
if result and result.diagnostics then
for _, v in ipairs(result.diagnostics) do
v.uri = v.uri or result.uri
end
vim.lsp.util.set_loclist(result.diagnostics)
end
end
end
|
local nvim = require('nvim')
local sys = require('sys')
local executable = require('nvim').fn.executable
local isdirectory = require('nvim').fn.isdirectory
local nvim_set_autocmd = require('nvim').nvim_set_autocmd
-- local nvim_set_command = require('nvim').nvim_set_command
local ok, lsp = pcall(require, 'nvim_lsp')
if not ok then
return nil
end
local servers = {
sh = { bashls = { name = 'bash-language-server'}, },
rust = { rust_analyzer = { name = 'rust_analyzer'}, },
go = { gopls = { name = 'gopls'}, },
tex = { texlab = { name = 'texlab'}, },
vim = { vimls = { name = 'vimls'}, },
dockerfile = { dockerls = { name = 'docker-langserver'}, },
lua = {
sumneko_lua = {
name = 'sumneko_lua',
options = {
settings = {
Lua = {
diagnostics = {
globals = {
'vim',
}
},
},
},
},
},
},
python = {
pyls = {
name = 'pyls',
options = {
cmd = {
'pyls',
'--log-file=' .. sys.tmp('pyls.log'),
},
settings = {
pyls = {
plugins = {
mccabe = {
threshold = 20
},
pycodestyle = {
maxLineLength = 120
},
},
},
},
},
},
},
c = {
ccls = {
name = 'ccls',
options = {
cmd = { 'ccls', '--log-file=' .. sys.tmp('ccls.log') },
init_options = {
cache = {
directory = sys.cache..'/ccls'
},
highlight = {
lsRanges = true;
},
completion = {
filterAndSort = true,
caseSensitivity = 1,
detailedLabel = false,
},
},
},
},
clangd = {
name = 'clangd',
options = {
cmd = {
'clangd',
'--index',
'--background-index',
'--suggest-missing-includes',
'--clang-tidy',
},
}
},
},
}
local available_languages = {}
for language,options in pairs(servers) do
for option,server in pairs(options) do
if executable(server['name']) == 1 or isdirectory(sys.home .. '/.cache/nvim/nvim_lsp/' .. server['name']) == 1 then
local init = server['options'] ~= nil and server['options'] or {}
lsp[option].setup(init)
available_languages[#available_languages + 1] = language
if language == 'c' then
available_languages[#available_languages + 1] = 'cpp'
available_languages[#available_languages + 1] = 'objc'
available_languages[#available_languages + 1] = 'objcpp'
elseif language == 'dockerfile' then
available_languages[#available_languages + 1] = 'Dockerfile'
elseif language == 'tex' then
available_languages[#available_languages + 1] = 'bib'
end
break
end
end
end
nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> <c-]> :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gd :lua vim.lsp.buf.declaration()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.implementation()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gr :lua vim.lsp.buf.references()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('References', 'lua vim.lsp.buf.references()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"autocmd CursorHold <buffer> lua vim.lsp.buf.hover()",
{group = 'NvimLSP', nested = true}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
do
local method = 'textDocument/publishDiagnostics'
local default_callback = vim.lsp.callbacks[method]
vim.lsp.callbacks[method] = function(err, method, result, client_id)
default_callback(err, method, result, client_id)
if result and result.diagnostics then
for _, v in ipairs(result.diagnostics) do
v.uri = v.uri or result.uri
end
vim.lsp.util.set_loclist(result.diagnostics)
end
end
end
|
fix: Add log to pyls
|
fix: Add log to pyls
Add log arg to pyls in nvim-lsp settings
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
cd32fd370aa8b58a39e93989cf900c80f11313cd
|
hammerspoon/init.lua
|
hammerspoon/init.lua
|
function setFrame(frameBuilder, multiplier)
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local gap = 10
local frame = frameBuilder(win, frame, max, gap, multiplier)
informativeText = "x: " .. frame.x .. " y: " .. frame.y .. " w: " .. frame.w .. " h: ".. frame.h
hs.notify.new({title="Hammerspoon", informativeText=informativeText}):send()
win:setFrame(frame)
end
function full(win, frame, max, gap)
frame.x = max.x + gap
frame.y = max.y + gap
frame.w = max.w - gap * 2
frame.h = max.h - gap * 2
return frame
end
function up(win, frame, max, gap, multiplier)
frame.y = max.y + gap
frame.h = (max.h * multiplier) - (gap * 3 * multiplier)
return frame
end
function down(win, frame, max, gap, multiplier)
frame.y = max.y + (max.h * multiplier) + (gap * multiplier)
frame.h = (max.h * multiplier) - (gap * 3 * multiplier)
return frame
end
function left(win, frame, max, gap, multiplier)
frame.x = max.x + gap
frame.w = (max.w * multiplier) - (gap * 3 * multiplier)
return frame
end
function right(win, frame, max, gap, multiplier)
frame.x = max.x + (max.w * multiplier) + (gap * multiplier)
frame.w = (max.w * multiplier) - (gap * 3 * multiplier)
return frame
end
hs.hotkey.bind({"cmd", "alt"}, "r", hs.reload)
hs.hotkey.bind({"cmd", "alt"}, "f", function() setFrame(full) end)
hs.hotkey.bind({"cmd", "alt"}, "h", function() setFrame(left, 1 / 2) end)
hs.hotkey.bind({"cmd", "alt", "shift"}, "h", function() setFrame(left, 2 / 3) end)
hs.hotkey.bind({"cmd", "alt"}, "j", function() setFrame(down, 1 / 2) end)
hs.hotkey.bind({"cmd", "alt"}, "k", function() setFrame(up , 1 / 2) end)
hs.hotkey.bind({"cmd", "alt"}, "l", function() setFrame(right, 1 / 2) end)
hs.hotkey.bind({"cmd", "alt", "shift"}, "l", function() setFrame(right, 1 / 3) end)
hs.window.animationDuration = 0.1
hs.notify.new({title="Hammerspoon", informativeText="Config loaded"}):send()
|
function setFrame(frameBuilder)
local win = hs.window.focusedWindow()
local frame = win:frame()
local screen = win:screen()
local max = screen:frame()
local gap = 10
local frame = frameBuilder(win, frame, max, gap)
informativeText = "x: " .. frame.x .. " y: " .. frame.y .. " w: " .. frame.w .. " h: ".. frame.h
hs.notify.new({title="Hammerspoon", informativeText=informativeText}):send()
win:setFrame(frame)
end
function full(win, frame, max, gap)
frame.x = max.x + gap
frame.y = max.y + gap
frame.w = max.w - gap * 2
frame.h = max.h - gap * 2
return frame
end
function up50(win, frame, max, gap)
frame.y = max.y + gap
frame.h = (max.h / 2) - (gap * 3 / 2)
return frame
end
function down50(win, frame, max, gap)
frame.y = max.y + (max.h / 2) + (gap / 2)
frame.h = (max.h / 2) - (gap * 3 / 2)
return frame
end
function left50(win, frame, max, gap)
frame.x = max.x + gap
frame.w = (max.w / 2) - (gap * 3 / 2)
return frame
end
function right50(win, frame, max, gap)
frame.x = max.x + (max.w / 2) + (gap / 2)
frame.w = (max.w / 2) - (gap * 3 / 2)
return frame
end
function left66(win, frame, max, gap)
frame.x = max.x + gap
frame.w = (max.w / 3 * 2) - (gap * 3 / 2)
return frame
end
function right33(win, frame, max, gap)
frame.x = max.x + (max.w / 3 * 2) + (gap / 2)
frame.w = (max.w / 3) - (gap * 3 / 2)
return frame
end
hs.hotkey.bind({"cmd", "alt"}, "r", hs.reload)
hs.hotkey.bind({"cmd", "alt"}, "f", function() setFrame(full) end)
hs.hotkey.bind({"cmd", "alt"}, "h", function() setFrame(left50) end)
hs.hotkey.bind({"cmd", "alt", "shift"}, "h", function() setFrame(left66) end)
hs.hotkey.bind({"cmd", "alt"}, "j", function() setFrame(down50) end)
hs.hotkey.bind({"cmd", "alt"}, "k", function() setFrame(up50) end)
hs.hotkey.bind({"cmd", "alt"}, "l", function() setFrame(right50) end)
hs.hotkey.bind({"cmd", "alt", "shift"}, "l", function() setFrame(right33) end)
hs.window.animationDuration = 0.1
hs.notify.new({title="Hammerspoon", informativeText="Config loaded"}):send()
|
Revert to fixed functions per layout thing
|
Revert to fixed functions per layout thing
|
Lua
|
mit
|
b-ggs/dotfiles
|
eeaacc90ffa6e35110cae509f2613284226791eb
|
modulefiles/Core/geant4/9.4p02.lua
|
modulefiles/Core/geant4/9.4p02.lua
|
help(
[[
This module loads Geant4 9.4p02. Geant4 is a detector simulator for HEP.
]])
whatis("Loads Geant4 9.4p02")
local version "," "9.4p02"
local base "," "/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/"..version
prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib"))
prepend_path("LIBRARY_PATH", pathJoin(base, "lib64"))
pushenv("G4SYSTEM","Linux-g++")
pushenv("G4INSTALL","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/src/geant4")
pushenv("G4LIB","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/lib/geant4")
pushenv("G4LEVELGAMMADATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/PhotonEvaporation2.1")
pushenv("G4RADIOACTIVEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/RadioactiveDecay3.3")
pushenv("G4LEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/G4EMLOW6.19")
pushenv("G4NEUTRONHPDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/G4NDL3.14")
pushenv("G4ABLADATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/G4ABLA3.0")
pushenv("G4LIB_BUILD_SHARED","1")
family('geant4')
load('gcc/4.9.2', 'clhep/2.1.0.1')
|
help(
[[
This module loads Geant4 9.4p02. Geant4 is a detector simulator for HEP.
]])
whatis("Loads Geant4 9.4p02")
local version = "9.4p02"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/"..version
prepend_path("LD_LIBRARY_PATH", "/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/lib/geant4/Linux-g++")
prepend_path("LIBRARY_PATH", pathJoin(base, "lib64"))
pushenv("G4SYSTEM","Linux-g++")
pushenv("G4INSTALL","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/src/geant4")
pushenv("G4LIB","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/lib/geant4")
pushenv("G4LEVELGAMMADATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/PhotonEvaporation2.1")
pushenv("G4RADIOACTIVEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/RadioactiveDecay3.3")
pushenv("G4LEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/G4EMLOW6.19")
pushenv("G4NEUTRONHPDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/G4NDL3.14")
pushenv("G4ABLADATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/9.4p02/data/G4ABLA3.0")
pushenv("G4LIB_BUILD_SHARED","1")
family('geant4')
load('gcc/4.9.2', 'clhep/2.1.0.1')
|
Fix paths and broken modulefile
|
Fix paths and broken modulefile
|
Lua
|
apache-2.0
|
OSGConnect/modulefiles,OSGConnect/modulefiles,OSGConnect/modulefiles
|
07d153d2527dd9b6ced7e61102d9cf56bf788e94
|
site/api/mbox.lua
|
site/api/mbox.lua
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is mbox.lua - a script for generating mbox archives
local elastic = require 'lib/elastic'
local cross = require 'lib/cross'
local user = require 'lib/user'
local aaa = require 'lib/aaa'
local utils = require 'lib/utils'
--[[
Parse the source to construct a valid 'From ' line.
Look for:
Return-Path: <dev-return-648-archive-asf-public=cust-asf.ponee.io@ponymail.incubator.apache.org>
...
Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183])
by cust-asf2.ponee.io (Postfix) with ESMTP id 9B3A0200BD9
for <[email protected]>; Fri, 9 Dec 2016 13:48:01 +0100 (CET)
...
]]--
local function getFromLine(r, source)
local replyTo = source:match("Return%-Path: +<(.-)>")
if not replyTo then replyTo = "MAILER-DAEMON" end
local received = source:match("Received: +from .-; +(.-)[\r\n]")
if not received then received = "" end
local recd = r.date_parse_rfc(received) or 0
local timeStamp = os.date('%c', recd) -- ctime format
return "From " .. replyTo .. " " .. timeStamp
end
function handle(r)
cross.contentType(r, "application/mbox")
local get = r:parseargs()
if get.list and get.date then
local lid = ("<%s>"):format(get.list:gsub("@", "."):gsub("[<>]", ""))
local flid = get.list:gsub("[.@]", "_")
local month = get.date:match("(%d+%-%d+)")
if not month then
cross.contentType(r, "text/plain")
r:puts("Wrong date format given!\n")
return cross.OK
end
if r.headers_out then
r.headers_out['Content-Disposition'] = "attachment; filename=" .. flid .. "_" .. month .. ".mbox"
end
local y, m = month:match("(%d+)%-(%d+)")
m = tonumber(m)
y = tonumber(y)
local d = utils.lastDayOfMonth(y,m)
-- fetch all results from the list (up to 10k results), make sure to get the 'private' element
local docs = elastic.raw {
_source = {'mid','private'},
query = {
bool = {
must = {
{
range = {
date = {
gte = ("%04d/%02d/%02d 00:00:00"):format(y,m,1),
lte = ("%04d/%02d/%02d 23:59:59"):format(y,m,d)
}
}
},
{
term = {
list_raw = lid
}
}
}
}
},
sort = {
{
epoch = {
order = "asc"
}
}
},
size = 10000
}
local account = user.get(r)
local listAccessible = nil -- not yet initialised
-- for each email, get the actual source of it to plop into the mbox file
for k, v in pairs(docs.hits.hits) do
v = v._source
-- aaa.rights() can be expensive, so only do it once per download
if v.private and listAccessible == nil then
-- we are dealing with a single list here so only need to check once
listAccessible = aaa.canAccessList(r, lid, account)
end
if listAccessible or not v.private then
local doc = elastic.get('mbox_source', v.mid)
if doc and doc.source then
r:puts(getFromLine(r, doc.source))
r:puts("\n")
-- pick out individual lines (including last which may not have EOL)
for line in doc.source:gmatch("[^\r\n]*\r?\n?") do
-- check if 'From ' needs to be escaped
if line:match("^From ") then r:puts(">") end
-- TODO consider whether to optionally prefix '>From ', '^>>From ' etc.
-- If so, just change the RE to "^>*From "
r:puts(line) -- original line
end
r:puts("\n")
end
end
end
else
cross.contentType(r, "text/plain")
r:puts("Both list and date are required!\n")
end
return cross.OK
end
cross.start(handle)
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is mbox.lua - a script for generating mbox archives
local elastic = require 'lib/elastic'
local cross = require 'lib/cross'
local user = require 'lib/user'
local aaa = require 'lib/aaa'
local utils = require 'lib/utils'
--[[
Parse the source to construct a valid 'From ' line.
e.g.
From dev-return-648-archive-asf-public=cust-asf.ponee.io@ponymail.incubator.apache.org Fri Dec 09 2016 12:48:01 2016
Note that the timestamp must be in the same format as unix ctime and must be in UTC
All the fields have constant width, i.e. the day of the month is zero-padded
(There are some existing archives that use space padding instead).
Look for:
Return-Path: <dev-return-648-archive-asf-public=cust-asf.ponee.io@ponymail.incubator.apache.org>
...
Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183])
by cust-asf2.ponee.io (Postfix) with ESMTP id 9B3A0200BD9
for <[email protected]>; Fri, 9 Dec 2016 13:48:01 +0100 (CET)
...
]]--
local function getFromLine(r, source)
local replyTo = source:match("Return%-Path: +<(.-)>")
if not replyTo then replyTo = "MAILER-DAEMON" end
local received = source:match("Received: +from .-; +(.-)[\r\n]")
if not received then received = "" end
local recd = r.date_parse_rfc(received) or 0
local timeStamp = os.date('!%a %b %d %H:%M:%S %Y', recd) -- ctime format in UTC
return "From " .. replyTo .. " " .. timeStamp
end
function handle(r)
cross.contentType(r, "application/mbox")
local get = r:parseargs()
if get.list and get.date then
local lid = ("<%s>"):format(get.list:gsub("@", "."):gsub("[<>]", ""))
local flid = get.list:gsub("[.@]", "_")
local month = get.date:match("(%d+%-%d+)")
if not month then
cross.contentType(r, "text/plain")
r:puts("Wrong date format given!\n")
return cross.OK
end
if r.headers_out then
r.headers_out['Content-Disposition'] = "attachment; filename=" .. flid .. "_" .. month .. ".mbox"
end
local y, m = month:match("(%d+)%-(%d+)")
m = tonumber(m)
y = tonumber(y)
local d = utils.lastDayOfMonth(y,m)
-- fetch all results from the list (up to 10k results), make sure to get the 'private' element
local docs = elastic.raw {
_source = {'mid','private'},
query = {
bool = {
must = {
{
range = {
date = {
gte = ("%04d/%02d/%02d 00:00:00"):format(y,m,1),
lte = ("%04d/%02d/%02d 23:59:59"):format(y,m,d)
}
}
},
{
term = {
list_raw = lid
}
}
}
}
},
sort = {
{
epoch = {
order = "asc"
}
}
},
size = 10000
}
local account = user.get(r)
local listAccessible = nil -- not yet initialised
-- for each email, get the actual source of it to plop into the mbox file
for k, v in pairs(docs.hits.hits) do
v = v._source
-- aaa.rights() can be expensive, so only do it once per download
if v.private and listAccessible == nil then
-- we are dealing with a single list here so only need to check once
listAccessible = aaa.canAccessList(r, lid, account)
end
if listAccessible or not v.private then
local doc = elastic.get('mbox_source', v.mid)
if doc and doc.source then
r:puts(getFromLine(r, doc.source))
r:puts("\n")
-- pick out individual lines (including last which may not have EOL)
for line in doc.source:gmatch("[^\r\n]*\r?\n?") do
-- check if 'From ' needs to be escaped
if line:match("^From ") then r:puts(">") end
-- TODO consider whether to optionally prefix '>From ', '^>>From ' etc.
-- If so, just change the RE to "^>*From "
r:puts(line) -- original line
end
r:puts("\n")
end
end
end
else
cross.contentType(r, "text/plain")
r:puts("Both list and date are required!\n")
end
return cross.OK
end
cross.start(handle)
|
Output the timestamp in UTC and fix field widths
|
Output the timestamp in UTC and fix field widths
This completes the fix for #190
|
Lua
|
apache-2.0
|
jimjag/ponymail,quenda/ponymail,quenda/ponymail,jimjag/ponymail,jimjag/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,quenda/ponymail,Humbedooh/ponymail,jimjag/ponymail
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.